diff options
Diffstat (limited to 'id/server/idserverlib/src/main/java/at/gv/egovernment')
81 files changed, 2780 insertions, 1266 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 1d71fd228..41b383f01 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 @@ -24,7 +24,6 @@ package at.gv.egovernment.moa.id.auth; import iaik.pki.PKIException; -import iaik.x509.CertificateFactory; import iaik.x509.X509Certificate; import java.io.ByteArrayInputStream; @@ -33,16 +32,12 @@ import java.io.InputStream; import java.security.GeneralSecurityException; import java.security.Principal; import java.security.cert.CertificateException; -//import java.security.cert.CertificateFactory; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; -import java.util.Set; import java.util.Vector; import javax.servlet.http.HttpServletRequest; @@ -73,7 +68,6 @@ import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder; import at.gv.egovernment.moa.id.auth.builder.GetIdentityLinkFormBuilder; import at.gv.egovernment.moa.id.auth.builder.InfoboxReadRequestBuilder; import at.gv.egovernment.moa.id.auth.builder.InfoboxValidatorParamsBuilder; -import at.gv.egovernment.moa.id.auth.builder.PersonDataBuilder; import at.gv.egovernment.moa.id.auth.builder.SelectBKUFormBuilder; import at.gv.egovernment.moa.id.auth.builder.VerifyXMLSignatureRequestBuilder; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; @@ -88,7 +82,6 @@ import at.gv.egovernment.moa.id.auth.invoke.SignatureVerificationInvoker; import at.gv.egovernment.moa.id.auth.parser.CreateXMLSignatureResponseParser; import at.gv.egovernment.moa.id.auth.parser.ExtendedInfoboxReadResponseParser; import at.gv.egovernment.moa.id.auth.parser.InfoboxReadResponseParser; -import at.gv.egovernment.moa.id.auth.parser.SAMLArtifactParser; import at.gv.egovernment.moa.id.auth.parser.VerifyXMLSignatureResponseParser; import at.gv.egovernment.moa.id.auth.servlet.AuthServlet; import at.gv.egovernment.moa.id.auth.servlet.PEPSConnectorServlet; @@ -115,7 +108,6 @@ import at.gv.egovernment.moa.id.config.auth.VerifyInfoboxParameters; import at.gv.egovernment.moa.id.config.stork.CPEPS; import at.gv.egovernment.moa.id.config.stork.STORKConfig; import at.gv.egovernment.moa.id.data.AuthenticationData; -import at.gv.egovernment.moa.id.moduls.IRequest; import at.gv.egovernment.moa.id.storage.AssertionStorage; import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; import at.gv.egovernment.moa.id.util.HTTPUtils; @@ -125,7 +117,6 @@ import at.gv.egovernment.moa.id.util.SSLUtils; import at.gv.egovernment.moa.id.util.client.mis.simple.MISMandate; import at.gv.egovernment.moa.logging.LogMsg; import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.Base64Utils; import at.gv.egovernment.moa.util.BoolUtils; import at.gv.egovernment.moa.util.Constants; import at.gv.egovernment.moa.util.DOMUtils; @@ -141,6 +132,7 @@ import eu.stork.vidp.messages.stork.QualityAuthenticationAssuranceLevel; import eu.stork.vidp.messages.stork.RequestedAttributes; import eu.stork.vidp.messages.util.SAMLUtil; import eu.stork.vidp.messages.util.XMLUtil; +//import java.security.cert.CertificateFactory; /** * API for MOA ID Authentication Service.<br> {@link AuthenticationSession} is @@ -2008,8 +2000,9 @@ public class AuthenticationServer implements MOAIDAuthConstants { // AuthConfigurationProvider.getInstance(); IdentityLink tempIdentityLink = null; - + if (session.getUseMandate()) { + session.setMandate(mandate); tempIdentityLink = new IdentityLink(); Element mandator = ParepUtils.extractMandator(mandate); String dateOfBirth = ""; @@ -2764,6 +2757,7 @@ public class AuthenticationServer implements MOAIDAuthConstants { OAAuthParameter oaParam = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(moasession.getPublicOAURLPrefix()); if (oaParam == null) throw new AuthenticationException("auth.00", new Object[] { moasession.getPublicOAURLPrefix() }); + //Start of STORK Processing STORKConfig storkConfig = AuthConfigurationProvider.getInstance().getStorkConfig(); @@ -2782,16 +2776,16 @@ public class AuthenticationServer implements MOAIDAuthConstants { Logger.debug("Issuer value: " + issuerValue); - QualityAuthenticationAssuranceLevel qaaLevel = null;//TODO UNCOMMENT AGAIN !! = STORKMessagesBuilder.buildQualityAuthenticationAssuranceLevel(oaParam.getQaaLevel().getValue()); - //Logger.debug("QAALevel: " + qaaLevel.getValue()); - + QualityAuthenticationAssuranceLevel qaaLevel = STORKMessagesBuilder.buildQualityAuthenticationAssuranceLevel(oaParam.getQaaLevel().getValue()); + Logger.debug("QAALevel: " + qaaLevel.getValue()); + RequestedAttributes requestedAttributes = null; - //TODO UNCOMMENT AGAIN !! requestedAttributes = oaParam.getRequestedAttributes(); + requestedAttributes = oaParam.getRequestedAttributes(); requestedAttributes.detach(); List<RequestedAttribute> reqAttributeList = new ArrayList<RequestedAttribute>(); List<RequestedAttribute> oaReqAttributeList = null; - //TODO UNCOMMENT AGAIN !! oaReqAttributeList = new ArrayList<RequestedAttribute>(oaParam.getRequestedAttributes().getRequestedAttributes()); + oaReqAttributeList = new ArrayList<RequestedAttribute>(oaParam.getRequestedAttributes().getRequestedAttributes()); //check if country specific attributes must be additionally requested if (!cpeps.getCountrySpecificRequestedAttributes().isEmpty()) { //add country specific attributes to be requested (Hierarchy: default oa attributes > country specific attributes > oa specific attributes @@ -2930,7 +2924,7 @@ public class AuthenticationServer implements MOAIDAuthConstants { } InputStream is = new ByteArrayInputStream(Base64.decode(base64CertString)); - + X509Certificate cert; try { cert = new X509Certificate(is); @@ -2939,13 +2933,7 @@ public class AuthenticationServer implements MOAIDAuthConstants { } catch (Throwable e) { throw new CertificateException(e); } - -// CertificateFactory cf; -// X509Certificate cert = null; -// cf = CertificateFactory.getInstance("X.509"); -// CertificateFactory -// cert = (X509Certificate)cf.generateCertificate(is); -// return cert; + } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java index 8279b28d8..cef9f9ff9 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java @@ -28,6 +28,7 @@ import iaik.pki.PKIException; import iaik.pki.jsse.IAIKX509TrustManager; import java.io.IOException; +import java.io.PrintWriter; import java.security.GeneralSecurityException; import java.util.Properties; @@ -36,6 +37,9 @@ import javax.activation.MailcapCommandMap; import javax.mail.Session; import javax.net.ssl.SSLSocketFactory; +import org.apache.commons.logging.impl.SLF4JLog; +import org.apache.log4j.config.PropertyPrinter; + import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.config.ConnectionParameter; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; @@ -158,6 +162,7 @@ public class MOAIDAuthInitializer { // Initializes IAIKX509TrustManager logging String log4jConfigURL = System.getProperty("log4j.configuration"); + Logger.info("Log4J Configuration: " + log4jConfigURL); if (log4jConfigURL != null) { IAIKX509TrustManager.initLog(new LoggerConfigImpl(log4jConfigURL)); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSession.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSession.java index 7a4c3da8b..4001fdd1a 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSession.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSession.java @@ -34,6 +34,8 @@ import java.util.Iterator; import java.util.List; import java.util.Vector; +import org.w3c.dom.Element; + import at.gv.egovernment.moa.id.auth.validator.InfoboxValidator; import at.gv.egovernment.moa.id.auth.validator.parep.ParepUtils; import at.gv.egovernment.moa.id.data.AuthenticationData; @@ -120,7 +122,14 @@ public class AuthenticationSession implements Serializable { private String ccc; /** + * + * Mandate element + */ + private Element mandate; + + /** * Reference value for mandate + * bussiness service for the assertion */ private String mandateReferenceValue; @@ -287,6 +296,7 @@ public class AuthenticationSession implements Serializable { this.mandateData = mandateData; } + // public AuthenticationData getAuthData() { // return authData; // } @@ -295,6 +305,7 @@ public class AuthenticationSession implements Serializable { // this.authData = authData; // } + public boolean isAuthenticatedUsed() { return authenticatedUsed; } @@ -1070,4 +1081,11 @@ public class AuthenticationSession implements Serializable { XMLVerifySignatureResponse = xMLVerifySignatureResponse; } + public Element getMandate() { + return mandate; + } + + public void setMandate(Element mandate) { + this.mandate = mandate; + } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AuthServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AuthServlet.java index 16041f8cb..187cf4fdb 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AuthServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AuthServlet.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.id.auth.servlet; import java.io.ByteArrayOutputStream; @@ -47,228 +46,312 @@ import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import at.gv.egovernment.moa.id.AuthenticationException; -import at.gv.egovernment.moa.id.auth.AuthenticationServer; import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.WrongParametersException; -import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder; -import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; +import at.gv.egovernment.moa.id.storage.ExceptionStoreImpl; +import at.gv.egovernment.moa.id.storage.IExceptionStore; +import at.gv.egovernment.moa.id.util.ServletUtils; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.BoolUtils; import at.gv.egovernment.moa.util.URLDecoder; -import at.gv.egovernment.moa.util.URLEncoder; /** - * Base class for MOA-ID Auth Servlets, providing standard error handling - * and constant names. + * Base class for MOA-ID Auth Servlets, providing standard error handling and + * constant names. * * @author Paul Ivancsics * @version $Id$ */ public class AuthServlet extends HttpServlet implements MOAIDAuthConstants { - - /** + /** * */ private static final long serialVersionUID = -6929905344382283738L; - - + protected static final String ERROR_CODE_PARAM = "errorid"; + @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - Logger.debug("GET " + this.getServletName()); + throws ServletException, IOException { + Logger.debug("GET " + this.getServletName()); this.setNoCachingHeadersInHttpRespone(req, resp); -} -/** - * Handles an error. <br>> - * <ul> - * <li>Logs the error</li> - * <li>Places error message and exception thrown into the request - * as request attributes (to be used by <code>"/errorpage-auth.jsp"</code>)</li> - * <li>Sets HTTP status 500 (internal server error)</li> - * </ul> - * - * @param errorMessage error message - * @param exceptionThrown exception thrown - * @param req servlet request - * @param resp servlet response - */ - protected void handleError( - String errorMessage, Throwable exceptionThrown, HttpServletRequest req, HttpServletResponse resp) { + } - - if(null != errorMessage) { + protected void handleErrorNoRedirect(String errorMessage, Throwable exceptionThrown, + HttpServletRequest req, HttpServletResponse resp) { + + if (null != errorMessage) { Logger.error(errorMessage); - req.setAttribute("ErrorMessage", errorMessage ); + req.setAttribute("ErrorMessage", errorMessage); } - - + if (null != exceptionThrown) { - if(null == errorMessage) errorMessage = exceptionThrown.getMessage(); + if (null == errorMessage) + errorMessage = exceptionThrown.getMessage(); Logger.error(errorMessage, exceptionThrown); req.setAttribute("ExceptionThrown", exceptionThrown); } - + if (Logger.isDebugEnabled()) { - req.setAttribute("LogLevel", "debug"); + req.setAttribute("LogLevel", "debug"); } - - //forward this to errorpage-auth.jsp where the HTML error page is generated + + // forward this to errorpage-auth.jsp where the HTML error page is + // generated ServletContext context = getServletContext(); - RequestDispatcher dispatcher = context.getRequestDispatcher("/errorpage-auth.jsp"); - try { - - resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES,MOAIDAuthConstants.HEADER_VALUE_EXPIRES); - resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA,MOAIDAuthConstants.HEADER_VALUE_PRAGMA); - resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL,MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); - resp.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL,MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); - - dispatcher.forward(req, resp); - } catch (ServletException e) { - Logger.error(e); - } catch (IOException e) { + RequestDispatcher dispatcher = context + .getRequestDispatcher("/errorpage-auth.jsp"); + try { + + resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, + MOAIDAuthConstants.HEADER_VALUE_EXPIRES); + resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, + MOAIDAuthConstants.HEADER_VALUE_PRAGMA); + resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, + MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); + resp.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, + MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); + + dispatcher.forward(req, resp); + } catch (ServletException e) { Logger.error(e); - } - + } catch (IOException e) { + Logger.error(e); + } } - /** - * Handles a <code>WrongParametersException</code>. - * @param req servlet request - * @param resp servlet response - */ - protected void handleWrongParameters(WrongParametersException ex, HttpServletRequest req, HttpServletResponse resp) { - Logger.error(ex.toString()); - req.setAttribute("WrongParameters", ex.getMessage()); - - // forward this to errorpage-auth.jsp where the HTML error page is generated - ServletContext context = getServletContext(); - RequestDispatcher dispatcher = context.getRequestDispatcher("/errorpage-auth.jsp"); - try { - resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES,MOAIDAuthConstants.HEADER_VALUE_EXPIRES); - resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA,MOAIDAuthConstants.HEADER_VALUE_PRAGMA); - resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL,MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); - resp.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL,MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); + + /** + * Handles an error. <br>> + * <ul> + * <li>Logs the error</li> + * <li>Places error message and exception thrown into the request as request + * attributes (to be used by <code>"/errorpage-auth.jsp"</code>)</li> + * <li>Sets HTTP status 500 (internal server error)</li> + * </ul> + * + * @param errorMessage + * error message + * @param exceptionThrown + * exception thrown + * @param req + * servlet request + * @param resp + * servlet response + */ + protected void handleError(String errorMessage, Throwable exceptionThrown, + HttpServletRequest req, HttpServletResponse resp) { + + if (null != errorMessage) { + Logger.error(errorMessage); + req.setAttribute("ErrorMessage", errorMessage); + } + + if (null != exceptionThrown) { + if (null == errorMessage) + errorMessage = exceptionThrown.getMessage(); + Logger.error(errorMessage, exceptionThrown); + req.setAttribute("ExceptionThrown", exceptionThrown); + } + + if (Logger.isDebugEnabled()) { + req.setAttribute("LogLevel", "debug"); + } + + IExceptionStore store = ExceptionStoreImpl.getStore(); + String id = store.storeException(exceptionThrown); + + String redirectURL = null; + + redirectURL = ServletUtils.getBaseUrl(req); + redirectURL += "/dispatcher?" + ERROR_CODE_PARAM + "=" + id; - dispatcher.forward(req, resp); - } catch (ServletException e) { - Logger.error(e); - } catch (IOException e) { - Logger.error(e); - } - } - - /** - * Logs all servlet parameters for debugging purposes. - */ - protected void logParameters(HttpServletRequest req) { - for (Enumeration params = req.getParameterNames(); params.hasMoreElements(); ) { - String parname = (String)params.nextElement(); - Logger.debug("Parameter " + parname + req.getParameter(parname)); - } - } - - /** - * Parses the request input stream for parameters, assuming parameters are encoded UTF-8 - * (no standard exists how browsers should encode them). - * - * @param req servlet request - * - * @return mapping parameter name -> value - * - * @throws IOException if parsing request parameters fails. - * - * @throws FileUploadException if parsing request parameters fails. - */ - protected Map getParameters(HttpServletRequest req) - throws IOException, FileUploadException { - - Map parameters = new HashMap(); - - - if (ServletFileUpload.isMultipartContent(req)) - { - // request is encoded as mulitpart/form-data - FileItemFactory factory = new DiskFileItemFactory(); - ServletFileUpload upload = null; - upload = new ServletFileUpload(factory); - List items = null; - items = upload.parseRequest(req); - for (int i = 0; i < items.size(); i++) - { - FileItem item = (FileItem) items.get(i); - if (item.isFormField()) - { - // Process only form fields - no file upload items - String logString = item.getString("UTF-8"); - - // TODO use RegExp - String startS = "<pr:Identification><pr:Value>"; - String endS = "</pr:Value><pr:Type>urn:publicid:gv.at:baseid</pr:Type>"; - String logWithMaskedBaseid = logString; - int start = logString.indexOf(startS); - if (start > -1) { - int end = logString.indexOf(endS); - if (end > -1) { - logWithMaskedBaseid = logString.substring(0, start); - logWithMaskedBaseid += startS; - logWithMaskedBaseid += "xxxxxxxxxxxxxxxxxxxxxxxx"; - logWithMaskedBaseid += logString.substring(end, logString.length()); - } - } - parameters.put(item.getFieldName(), item.getString("UTF-8")); - Logger.debug("Processed multipart/form-data request parameter: \nName: " + - item.getFieldName() + "\nValue: " + - logWithMaskedBaseid); - } - } - } - - else - { - // request is encoded as application/x-www-urlencoded - InputStream in = req.getInputStream(); - - String paramName; - String paramValueURLEncoded; - do { - paramName = new String(readBytesUpTo(in, '=')); - if (paramName.length() > 0) { - paramValueURLEncoded = readBytesUpTo(in, '&'); - String paramValue = URLDecoder.decode(paramValueURLEncoded, "UTF-8"); - parameters.put(paramName, paramValue); - } - } - while (paramName.length() > 0); - in.close(); - } - - return parameters; - } - - /** - * Reads bytes up to a delimiter, consuming the delimiter. - * @param in input stream - * @param delimiter delimiter character - * @return String constructed from the read bytes - * @throws IOException - */ - protected String readBytesUpTo(InputStream in, char delimiter) throws IOException { - ByteArrayOutputStream bout = new ByteArrayOutputStream(); - boolean done = false; - int b; - while (! done && (b = in.read()) >= 0) { - if (b == delimiter) - done = true; - else - bout.write(b); - } - return bout.toString(); - } + resp.setContentType("text/html"); + resp.setStatus(302); + resp.addHeader("Location", redirectURL); + Logger.debug("REDIRECT TO: " + redirectURL); + + return; + /* + // forward this to errorpage-auth.jsp where the HTML error page is + // generated + ServletContext context = getServletContext(); + RequestDispatcher dispatcher = context + .getRequestDispatcher("/errorpage-auth.jsp"); + try { + + resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, + MOAIDAuthConstants.HEADER_VALUE_EXPIRES); + resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, + MOAIDAuthConstants.HEADER_VALUE_PRAGMA); + resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, + MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); + resp.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, + MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); + + dispatcher.forward(req, resp); + } catch (ServletException e) { + Logger.error(e); + } catch (IOException e) { + Logger.error(e); + } + */ + } + + /** + * Handles a <code>WrongParametersException</code>. + * + * @param req + * servlet request + * @param resp + * servlet response + */ + protected void handleWrongParameters(WrongParametersException ex, + HttpServletRequest req, HttpServletResponse resp) { + Logger.error(ex.toString()); + req.setAttribute("WrongParameters", ex.getMessage()); + + // forward this to errorpage-auth.jsp where the HTML error page is + // generated + ServletContext context = getServletContext(); + RequestDispatcher dispatcher = context + .getRequestDispatcher("/errorpage-auth.jsp"); + try { + resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, + MOAIDAuthConstants.HEADER_VALUE_EXPIRES); + resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, + MOAIDAuthConstants.HEADER_VALUE_PRAGMA); + resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, + MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); + resp.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, + MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); + + dispatcher.forward(req, resp); + } catch (ServletException e) { + Logger.error(e); + } catch (IOException e) { + Logger.error(e); + } + } + + /** + * Logs all servlet parameters for debugging purposes. + */ + protected void logParameters(HttpServletRequest req) { + for (Enumeration params = req.getParameterNames(); params + .hasMoreElements();) { + String parname = (String) params.nextElement(); + Logger.debug("Parameter " + parname + req.getParameter(parname)); + } + } + + /** + * Parses the request input stream for parameters, assuming parameters are + * encoded UTF-8 (no standard exists how browsers should encode them). + * + * @param req + * servlet request + * + * @return mapping parameter name -> value + * + * @throws IOException + * if parsing request parameters fails. + * + * @throws FileUploadException + * if parsing request parameters fails. + */ + protected Map getParameters(HttpServletRequest req) throws IOException, + FileUploadException { + + Map parameters = new HashMap(); + + if (ServletFileUpload.isMultipartContent(req)) { + // request is encoded as mulitpart/form-data + FileItemFactory factory = new DiskFileItemFactory(); + ServletFileUpload upload = null; + upload = new ServletFileUpload(factory); + List items = null; + items = upload.parseRequest(req); + for (int i = 0; i < items.size(); i++) { + FileItem item = (FileItem) items.get(i); + if (item.isFormField()) { + // Process only form fields - no file upload items + String logString = item.getString("UTF-8"); + + // TODO use RegExp + String startS = "<pr:Identification><pr:Value>"; + String endS = "</pr:Value><pr:Type>urn:publicid:gv.at:baseid</pr:Type>"; + String logWithMaskedBaseid = logString; + int start = logString.indexOf(startS); + if (start > -1) { + int end = logString.indexOf(endS); + if (end > -1) { + logWithMaskedBaseid = logString.substring(0, start); + logWithMaskedBaseid += startS; + logWithMaskedBaseid += "xxxxxxxxxxxxxxxxxxxxxxxx"; + logWithMaskedBaseid += logString.substring(end, + logString.length()); + } + } + parameters + .put(item.getFieldName(), item.getString("UTF-8")); + Logger.debug("Processed multipart/form-data request parameter: \nName: " + + item.getFieldName() + + "\nValue: " + + logWithMaskedBaseid); + } + } + } + + else { + // request is encoded as application/x-www-urlencoded + InputStream in = req.getInputStream(); + + String paramName; + String paramValueURLEncoded; + do { + paramName = new String(readBytesUpTo(in, '=')); + if (paramName.length() > 0) { + paramValueURLEncoded = readBytesUpTo(in, '&'); + String paramValue = URLDecoder.decode(paramValueURLEncoded, + "UTF-8"); + parameters.put(paramName, paramValue); + } + } while (paramName.length() > 0); + in.close(); + } + + return parameters; + } + + /** + * Reads bytes up to a delimiter, consuming the delimiter. + * + * @param in + * input stream + * @param delimiter + * delimiter character + * @return String constructed from the read bytes + * @throws IOException + */ + protected String readBytesUpTo(InputStream in, char delimiter) + throws IOException { + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + boolean done = false; + int b; + while (!done && (b = in.read()) >= 0) { + if (b == delimiter) + done = true; + else + bout.write(b); + } + return bout.toString(); + } + /** * Calls the web application initializer. * @@ -277,51 +360,70 @@ public class AuthServlet extends HttpServlet implements MOAIDAuthConstants { public void init(ServletConfig servletConfig) throws ServletException { super.init(servletConfig); } - + /** * Set response headers to avoid caching - * @param request HttpServletRequest - * @param response HttpServletResponse + * + * @param request + * HttpServletRequest + * @param response + * HttpServletResponse */ - protected void setNoCachingHeadersInHttpRespone(HttpServletRequest request, HttpServletResponse response) { - response.setHeader(MOAIDAuthConstants.HEADER_EXPIRES,MOAIDAuthConstants.HEADER_VALUE_EXPIRES); - response.setHeader(MOAIDAuthConstants.HEADER_PRAGMA,MOAIDAuthConstants.HEADER_VALUE_PRAGMA); - response.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL,MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); - response.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL,MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); - + protected void setNoCachingHeadersInHttpRespone(HttpServletRequest request, + HttpServletResponse response) { + response.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, + MOAIDAuthConstants.HEADER_VALUE_EXPIRES); + response.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, + MOAIDAuthConstants.HEADER_VALUE_PRAGMA); + response.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, + MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); + response.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, + MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); + } - + + /** + * Adds a parameter to a URL. + * + * @param url + * the URL + * @param paramname + * parameter name + * @param paramvalue + * parameter value + * @return the URL with parameter added + */ + protected static String addURLParameter(String url, String paramname, + String paramvalue) { + String param = paramname + "=" + paramvalue; + if (url.indexOf("?") < 0) + return url + "?" + param; + else + return url + "&" + param; + } + /** - * Adds a parameter to a URL. - * @param url the URL - * @param paramname parameter name - * @param paramvalue parameter value - * @return the URL with parameter added - */ - protected static String addURLParameter(String url, String paramname, String paramvalue) { - String param = paramname + "=" + paramvalue; - if (url.indexOf("?") < 0) - return url + "?" + param; - else - return url + "&" + param; - } - - /** - * Checks if HTTP requests are allowed - * @param authURL requestURL - * @throws AuthenticationException if HTTP requests are not allowed - * @throws ConfigurationException - */ - protected void checkIfHTTPisAllowed(String authURL) throws AuthenticationException, ConfigurationException { + * Checks if HTTP requests are allowed + * + * @param authURL + * requestURL + * @throws AuthenticationException + * if HTTP requests are not allowed + * @throws ConfigurationException + */ + protected void checkIfHTTPisAllowed(String authURL) + throws AuthenticationException, ConfigurationException { // check if HTTP Connection may be allowed (through - // FRONTEND_SERVLETS_ENABLE_HTTP_CONNECTION_PROPERTY) - String boolStr = AuthConfigurationProvider.getInstance().getGenericConfigurationParameter( - AuthConfigurationProvider.FRONTEND_SERVLETS_ENABLE_HTTP_CONNECTION_PROPERTY); - if ((!authURL.startsWith("https:")) - && (false == BoolUtils.valueOf(boolStr))) - throw new AuthenticationException("auth.07", - new Object[] { authURL + "*" }); - - } + // FRONTEND_SERVLETS_ENABLE_HTTP_CONNECTION_PROPERTY) + String boolStr = AuthConfigurationProvider + .getInstance() + .getGenericConfigurationParameter( + AuthConfigurationProvider.FRONTEND_SERVLETS_ENABLE_HTTP_CONNECTION_PROPERTY); + if ((!authURL.startsWith("https:")) + && (false == BoolUtils.valueOf(boolStr))) + throw new AuthenticationException("auth.07", new Object[] { authURL + + "*" }); + + } } 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 0a3b8dc3e..935edb557 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 @@ -50,12 +50,11 @@ import at.gv.egovernment.moa.id.auth.parser.IdentityLinkAssertionParser; import at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.CreateIdentityLinkResponse; import at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.SZRGWClientException; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; +import at.gv.egovernment.moa.id.moduls.ModulUtils; import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; import at.gv.egovernment.moa.id.util.ParamValidatorUtils; import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.spss.MOAException; import at.gv.egovernment.moa.util.DOMUtils; -import at.gv.egovernment.moa.util.URLEncoder; /**
* Servlet requested for getting the foreign eID
@@ -182,11 +181,14 @@ public class GetForeignIDServlet extends AuthServlet { String samlArtifactBase64 =
AuthenticationServer.getInstance().getForeignAuthenticationData(sessionID); if (!samlArtifactBase64.equals("Redirect to Input Processor")) { - redirectURL = session.getOAURLRequested(); + /*redirectURL = session.getOAURLRequested(); if (!session.getBusinessService()) { redirectURL = addURLParameter(redirectURL, PARAM_TARGET, URLEncoder.encode(session.getTarget(), "UTF-8")); } redirectURL = addURLParameter(redirectURL, PARAM_SAMLARTIFACT, URLEncoder.encode(samlArtifactBase64, "UTF-8")); + redirectURL = resp.encodeRedirectURL(redirectURL);*/ + redirectURL = new DataURLBuilder().buildDataURL(session.getAuthURL(), + ModulUtils.buildAuthURL(session.getModul(), session.getAction()), samlArtifactBase64); redirectURL = resp.encodeRedirectURL(redirectURL); } else { 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 a74635232..d41d20def 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 @@ -21,9 +21,8 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ +package at.gv.egovernment.moa.id.auth.servlet; -package at.gv.egovernment.moa.id.auth.servlet;
-
import iaik.pki.PKIException; import java.io.IOException; @@ -59,166 +58,182 @@ import at.gv.egovernment.moa.id.util.client.mis.simple.MISSimpleClientException; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.DOMUtils; import at.gv.egovernment.moa.util.URLEncoder; -
-/**
- * Servlet requested for getting the foreign eID
- * provided by the security layer implementation.
- * Utilizes the {@link AuthenticationServer}.
- *
- */
-public class GetMISSessionIDServlet extends AuthServlet {
-
- /** + +/** + * Servlet requested for getting the foreign eID provided by the security layer + * implementation. Utilizes the {@link AuthenticationServer}. + * + */ +public class GetMISSessionIDServlet extends AuthServlet { + + /** * */ private static final long serialVersionUID = 4666952867085392597L; -/**
- * Constructor for GetMISSessionIDServlet.
- */
- public GetMISSessionIDServlet() {
- super();
- }
-
- /**
- * GET requested by security layer implementation to verify
- * that data URL resource is available.
- * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest, HttpServletResponse)
- */
- protected void doGet(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
-
- doPost(req, resp);
-
-// Logger.debug("GET GetMISSessionIDServlet");
-//
-// resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES,MOAIDAuthConstants.HEADER_VALUE_EXPIRES);
-// resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA,MOAIDAuthConstants.HEADER_VALUE_PRAGMA);
-// resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL,MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL);
-// resp.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL,MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE);
- }
-
- /**
- * Gets the signer certificate from the InfoboxReadRequest and
- * responds with a new
- * <code>CreateXMLSignatureRequest</code>.
- * <br>
- * Request parameters:
- * <ul>
- * <li>MOASessionID: ID of associated authentication session</li>
- * <li>XMLResponse: <code><InfoboxReadResponse></code></li>
- * </ul>
- * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest, HttpServletResponse)
- */
- protected void doPost(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
-
- Logger.debug("POST GetMISSessionIDServlet");
-
- resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES,MOAIDAuthConstants.HEADER_VALUE_EXPIRES);
- resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA,MOAIDAuthConstants.HEADER_VALUE_PRAGMA);
- resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL,MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL);
- resp.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL,MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE);
-
-// Map parameters;
-// try
-// {
-// parameters = getParameters(req);
-// } catch (FileUploadException e)
-// {
-// Logger.error("Parsing mulitpart/form-data request parameters failed: " + e.getMessage());
-// throw new IOException(e.getMessage());
-// }
-
- String sessionID = req.getParameter(PARAM_SESSIONID);
-
- // escape parameter strings
- sessionID = StringEscapeUtils.escapeHtml(sessionID);
-
- AuthenticationSession session = null;
- try {
- // check parameter
- if (!ParamValidatorUtils.isValidSessionID(sessionID))
- throw new WrongParametersException("VerifyCertificate", PARAM_SESSIONID, "auth.12");
-
- session = AuthenticationServer.getSession(sessionID);
-
- String misSessionID = session.getMISSessionID();
-
- AuthConfigurationProvider authConf= AuthConfigurationProvider.getInstance();
- ConnectionParameter connectionParameters = authConf.getOnlineMandatesConnectionParameter();
- SSLSocketFactory sslFactory = SSLUtils.getSSLSocketFactory(AuthConfigurationProvider.getInstance(), connectionParameters);
-
- List list = MISSimpleClient.sendGetMandatesRequest(connectionParameters.getUrl(), misSessionID, sslFactory);
-
- if (list == null) {
- Logger.error("Keine Vollmacht gefunden.");
- throw new MISSimpleClientException("Keine Vollmacht gefunden");
- }
- if (list.size() == 0) {
- Logger.error("Keine Vollmacht gefunden.");
- throw new MISSimpleClientException("Keine Vollmacht gefunden");
- }
-
- // for now: list contains only one element
- MISMandate mandate = (MISMandate)list.get(0); -
-
- // verify mandate signature
- AuthenticationServer.getInstance().verifyMandate(session, mandate);
- - byte[] byteMandate = mandate.getMandate(); - String stringMandate = new String(byteMandate); - Element mandateDoc = DOMUtils.parseDocument(stringMandate, false, null, null).getDocumentElement(); - - //TODO OW bPK (Offen: was bei saml:NameIdentifier NameQualifier="urn:publicid:gv.at:cdid+bpk"> und <saml:Attribute AttributeName="bPK" ) - System.out.println("\n\n\n OW BPK: " + mandate.getOWbPK()); - // TODO wenn OW bPK vorhanden - in SAML Assertion setzen! - - String redirectURL = null; - String samlArtifactBase64 = - AuthenticationServer.getInstance().verifyAuthenticationBlockMandate(session, mandateDoc); - - - if (!samlArtifactBase64.equals("Redirect to Input Processor")) { -// redirectURL = session.getOAURLRequested(); -// -// if (!session.getBusinessService()) { -// redirectURL = addURLParameter(redirectURL, PARAM_TARGET, URLEncoder.encode(session.getTarget(), "UTF-8")); -// } -// -// redirectURL = addURLParameter(redirectURL, PARAM_SAMLARTIFACT, URLEncoder.encode(samlArtifactBase64, "UTF-8")); -// redirectURL = resp.encodeRedirectURL(redirectURL); - - redirectURL = new DataURLBuilder().buildDataURL(session.getAuthURL(), - ModulUtils.buildAuthURL(session.getModul(), session.getAction()), samlArtifactBase64); - - } else { - redirectURL = new DataURLBuilder().buildDataURL(session.getAuthURL(), AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, session.getSessionID()); - + /** + * Constructor for GetMISSessionIDServlet. + */ + public GetMISSessionIDServlet() { + super(); + } + + /** + * GET requested by security layer implementation to verify that data URL + * resource is available. + * + * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest, + * HttpServletResponse) + */ + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + + doPost(req, resp); + + // Logger.debug("GET GetMISSessionIDServlet"); + // + // resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES,MOAIDAuthConstants.HEADER_VALUE_EXPIRES); + // resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA,MOAIDAuthConstants.HEADER_VALUE_PRAGMA); + // resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL,MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); + // resp.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL,MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); + } + + /** + * Gets the signer certificate from the InfoboxReadRequest and responds with + * a new <code>CreateXMLSignatureRequest</code>. <br> + * Request parameters: + * <ul> + * <li>MOASessionID: ID of associated authentication session</li> + * <li>XMLResponse: <code><InfoboxReadResponse></code></li> + * </ul> + * + * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest, + * HttpServletResponse) + */ + protected void doPost(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + + Logger.debug("POST GetMISSessionIDServlet"); + + resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, + MOAIDAuthConstants.HEADER_VALUE_EXPIRES); + resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, + MOAIDAuthConstants.HEADER_VALUE_PRAGMA); + resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, + MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); + resp.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, + MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); + + // Map parameters; + // try + // { + // parameters = getParameters(req); + // } catch (FileUploadException e) + // { + // Logger.error("Parsing mulitpart/form-data request parameters failed: " + // + e.getMessage()); + // throw new IOException(e.getMessage()); + // } + + String sessionID = req.getParameter(PARAM_SESSIONID); + + // escape parameter strings + sessionID = StringEscapeUtils.escapeHtml(sessionID); + + AuthenticationSession session = null; + try { + // check parameter + if (!ParamValidatorUtils.isValidSessionID(sessionID)) + throw new WrongParametersException("VerifyCertificate", + PARAM_SESSIONID, "auth.12"); + + session = AuthenticationServer.getSession(sessionID); + + String misSessionID = session.getMISSessionID(); + + AuthConfigurationProvider authConf = AuthConfigurationProvider + .getInstance(); + ConnectionParameter connectionParameters = authConf + .getOnlineMandatesConnectionParameter(); + SSLSocketFactory sslFactory = SSLUtils.getSSLSocketFactory( + AuthConfigurationProvider.getInstance(), + connectionParameters); + + List list = MISSimpleClient.sendGetMandatesRequest( + connectionParameters.getUrl(), misSessionID, sslFactory); + + if (list == null) { + Logger.error("Keine Vollmacht gefunden."); + throw new MISSimpleClientException("Keine Vollmacht gefunden"); + } + if (list.size() == 0) { + Logger.error("Keine Vollmacht gefunden."); + throw new MISSimpleClientException("Keine Vollmacht gefunden"); + } + + // for now: list contains only one element + MISMandate mandate = (MISMandate) list.get(0); + + // verify mandate signature + AuthenticationServer.getInstance().verifyMandate(session, mandate); + + byte[] byteMandate = mandate.getMandate(); + String stringMandate = new String(byteMandate); + Element mandateDoc = DOMUtils.parseDocument(stringMandate, false, + null, null).getDocumentElement(); + + // TODO OW bPK (Offen: was bei saml:NameIdentifier + // NameQualifier="urn:publicid:gv.at:cdid+bpk"> und <saml:Attribute + // AttributeName="bPK" ) + System.out.println("\n\n\n OW BPK: " + mandate.getOWbPK()); + // TODO wenn OW bPK vorhanden - in SAML Assertion setzen! + + String redirectURL = null; + String samlArtifactBase64 = AuthenticationServer.getInstance() + .verifyAuthenticationBlockMandate(session, mandateDoc); + + if (!samlArtifactBase64.equals("Redirect to Input Processor")) { + + redirectURL = session.getOAURLRequested(); + if (!session.getBusinessService()) { + // redirectURL = addURLParameter(redirectURL, PARAM_TARGET, + // URLEncoder.encode(session.getTarget(), "UTF-8")); + } + // redirectURL = addURLParameter(redirectURL, + // PARAM_SAMLARTIFACT, URLEncoder.encode(samlArtifactBase64, + // "UTF-8")); + redirectURL = new DataURLBuilder().buildDataURL( + session.getAuthURL(), + ModulUtils.buildAuthURL(session.getModul(), + session.getAction()), samlArtifactBase64); + redirectURL = resp.encodeRedirectURL(redirectURL); + + } else { + redirectURL = new DataURLBuilder().buildDataURL( + session.getAuthURL(), + AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, + session.getSessionID()); + } resp.setContentType("text/html"); resp.setStatus(302); - - resp.addHeader("Location", redirectURL); + + resp.addHeader("Location", redirectURL); Logger.debug("REDIRECT TO: " + redirectURL); -
- }
- catch (MOAIDException ex) {
- handleError(null, ex, req, resp);
- } catch (GeneralSecurityException ex) {
- handleError(null, ex, req, resp);
- } catch (PKIException e) {
- handleError(null, e, req, resp);
- } catch (MISSimpleClientException e) {
- handleError(null, e, req, resp);
+ + } catch (MOAIDException ex) { + handleError(null, ex, req, resp); + } catch (GeneralSecurityException ex) { + handleError(null, ex, req, resp); + } catch (PKIException e) { + handleError(null, e, req, resp); + } catch (MISSimpleClientException e) { + handleError(null, e, req, resp); } catch (SAXException e) { handleError(null, e, req, resp); } catch (ParserConfigurationException e) { handleError(null, e, req, resp); - }
- } - -
-
- }
+ } + } + +} 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 0b30022f1..3c8892e33 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 @@ -24,12 +24,12 @@ import at.gv.egovernment.moa.id.auth.data.IdentityLink; import at.gv.egovernment.moa.id.auth.stork.STORKException;
import at.gv.egovernment.moa.id.auth.stork.STORKResponseProcessor;
import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException;
+import at.gv.egovernment.moa.id.moduls.ModulUtils;
import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage;
import at.gv.egovernment.moa.id.util.HTTPUtils;
import at.gv.egovernment.moa.logging.Logger;
import at.gv.egovernment.moa.util.DOMUtils;
import at.gv.egovernment.moa.util.StringUtils;
-import at.gv.egovernment.moa.util.URLEncoder;
import eu.stork.mw.messages.saml.STORKAuthnRequest;
import eu.stork.mw.messages.saml.STORKResponse;
import eu.stork.vidp.messages.util.XMLUtil;
@@ -202,11 +202,14 @@ public class PEPSConnectorServlet extends AuthServlet { //redirect
String redirectURL = null;
if (!samlArtifactBase64.equals("Redirect to Input Processor")) {
- redirectURL = moaSession.getOAURLRequested();
+ /*redirectURL = moaSession.getOAURLRequested();
if (!moaSession.getBusinessService()) {
redirectURL = addURLParameter(redirectURL, PARAM_TARGET, URLEncoder.encode(moaSession.getTarget(), "UTF-8"));
}
redirectURL = addURLParameter(redirectURL, PARAM_SAMLARTIFACT, URLEncoder.encode(samlArtifactBase64, "UTF-8"));
+ redirectURL = response.encodeRedirectURL(redirectURL);*/
+ redirectURL = new DataURLBuilder().buildDataURL(moaSession.getAuthURL(),
+ ModulUtils.buildAuthURL(moaSession.getModul(), moaSession.getAction()), samlArtifactBase64);
redirectURL = response.encodeRedirectURL(redirectURL);
} else {
redirectURL = new DataURLBuilder().buildDataURL(moaSession.getAuthURL(), AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, moaSession.getSessionID());
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 fae69d81a..4c4671084 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 @@ -148,7 +148,7 @@ public class VerifyCertificateServlet extends AuthServlet { }
else {
// Foreign Identities Modus
-
+ session.setForeignMode(true);
String createXMLSignatureRequest = AuthenticationServer.getInstance().createXMLSignatureRequestForeignID(sessionID, cert);
// build dataurl (to the GetForeignIDSerlvet)
String dataurl =
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 77817ac72..8eaa8341c 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 @@ -148,7 +148,7 @@ public class VerifyIdentityLinkServlet extends AuthServlet { if (createXMLSignatureRequestOrRedirect == null) { // no identity link found - + boolean useMandate = session.getUseMandate(); if (useMandate) { Logger.error("Online-Mandate Mode for foreign citizencs not supported."); 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 0771fb86c..d798ce9d6 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 @@ -326,7 +326,7 @@ public class AuthConfigurationProvider extends ConfigurationProvider { //Initialize OpenSAML for STORK - Logger.trace("Starting initialization of OpenSAML..."); + Logger.info("Starting initialization of OpenSAML..."); STORKBootstrap.bootstrap(); Logger.debug("OpenSAML successfully initialized"); 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 10dd2cfea..7c174de77 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 @@ -133,17 +133,17 @@ public class OAAuthParameter extends OAParameter { /** * STORK QAA Level, Default = 4 */ - // private QualityAuthenticationAssuranceLevel qaaLevel = STORKMessagesBuilder.buildQualityAuthenticationAssuranceLevel(4); + private QualityAuthenticationAssuranceLevel qaaLevel = STORKMessagesBuilder.buildQualityAuthenticationAssuranceLevel(4); /** * STORK RequestedAttributes for Online Application * Default RequestedAttributes are: eIdentifier, givenName, surname, dateOfBirth */ - //private RequestedAttributes requestedAttributes = STORKMessagesBuilder.buildRequestedAttributes( -// STORKMessagesBuilder.buildRequestedAttribute(STORKConstants.STORK_ATTRIBUTE_EIDENTIFIER, true, null), -// STORKMessagesBuilder.buildRequestedAttribute(STORKConstants.STORK_ATTRIBUTE_GIVENNAME, true, null), -// STORKMessagesBuilder.buildRequestedAttribute(STORKConstants.STORK_ATTRIBUTE_SURNAME, true, null), -// STORKMessagesBuilder.buildRequestedAttribute(STORKConstants.STORK_ATTRIBUTE_DATEOFBIRTH, false, null)); + private RequestedAttributes requestedAttributes = STORKMessagesBuilder.buildRequestedAttributes( + STORKMessagesBuilder.buildRequestedAttribute(STORKConstants.STORK_ATTRIBUTE_EIDENTIFIER, true, null), + STORKMessagesBuilder.buildRequestedAttribute(STORKConstants.STORK_ATTRIBUTE_GIVENNAME, true, null), + STORKMessagesBuilder.buildRequestedAttribute(STORKConstants.STORK_ATTRIBUTE_SURNAME, true, null), + STORKMessagesBuilder.buildRequestedAttribute(STORKConstants.STORK_ATTRIBUTE_DATEOFBIRTH, false, null)); /** @@ -469,33 +469,33 @@ public class OAAuthParameter extends OAParameter { * Returns the defined STORK QAALevel * @return STORK QAALevel */ - /*public QualityAuthenticationAssuranceLevel getQaaLevel() { + public QualityAuthenticationAssuranceLevel getQaaLevel() { return qaaLevel; - }*/ + } /** * Sets the STORK QAALevel * @param qaaLevel */ - /*public void setQaaLevel(QualityAuthenticationAssuranceLevel qaaLevel) { + public void setQaaLevel(QualityAuthenticationAssuranceLevel qaaLevel) { this.qaaLevel = qaaLevel; - }*/ + } /** * Returns the desired STORK Requested Attributes * @return STORK Requested Attributes */ - //public RequestedAttributes getRequestedAttributes() { - // return requestedAttributes; - //} + public RequestedAttributes getRequestedAttributes() { + return requestedAttributes; + } /** * Sets the desired STORK Requested Attributes * @param requestedAttributes */ - //public void setRequestedAttributes(RequestedAttributes requestedAttributes) { - // this.requestedAttributes = requestedAttributes; - //} + public void setRequestedAttributes(RequestedAttributes requestedAttributes) { + this.requestedAttributes = requestedAttributes; + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/entrypoints/AuthDispatcherServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/entrypoints/AuthDispatcherServlet.java deleted file mode 100644 index e04600b42..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/entrypoints/AuthDispatcherServlet.java +++ /dev/null @@ -1,263 +0,0 @@ -package at.gv.egovernment.moa.id.entrypoints; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; - -import javax.servlet.ServletConfig; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import at.gv.egovernment.moa.id.MOAIDException; -import at.gv.egovernment.moa.id.auth.MOAIDAuthInitializer; -import at.gv.egovernment.moa.id.auth.WrongParametersException; -import at.gv.egovernment.moa.id.auth.servlet.AuthServlet; -import at.gv.egovernment.moa.id.moduls.AuthenticationManager; -import at.gv.egovernment.moa.id.moduls.IAction; -import at.gv.egovernment.moa.id.moduls.IModulInfo; -import at.gv.egovernment.moa.id.moduls.IRequest; -import at.gv.egovernment.moa.id.moduls.ModulStorage; -import at.gv.egovernment.moa.id.moduls.NoPassivAuthenticationException; -import at.gv.egovernment.moa.id.moduls.ServletInfo; -import at.gv.egovernment.moa.id.moduls.ServletType; -import at.gv.egovernment.moa.id.util.MOAIDMessageProvider; -import at.gv.egovernment.moa.logging.Logger; - -public class AuthDispatcherServlet extends AuthServlet { - - /** - * - */ - private static final long serialVersionUID = 1L; - - public static final String PARAM_TARGET_PATH = "mod"; - public static final String PARAM_TARGET_PROTOCOL = "action"; -/* public static final String PARAM_DISPATCHER_TARGETS = "DispatcherTargets"; - public static final String PARAM_DISPATCHER_TYPE = "DispatcherType"; - public static final String PARAM_DISPATCHER_TYPE_UNAUTH = "UNAUTH"; - public static final String PARAM_DISPATCHER_TYPE_AUTH = "AUTH"; - public static String SYSTEM_NEWLINE = System.getProperty("line.separator"); - - private HashMap<String, HashMap<String, HttpServlet>> endpointMap = new HashMap<String, HashMap<String, HttpServlet>>(); - - private void registerModule(IModulInfo modulInfo) { - - HashMap<String, HttpServlet> tempMap = new HashMap<String, HttpServlet>(); - - try { - - String path = modulInfo.getPath(); - - if (path == null) { - throw new Exception(String.format( - "%s does not return a valid target path!", - new Object[] { modulInfo.getClass().getName() })); - } - - Logger.debug("Registering: " + modulInfo.getName() + " under " - + path); - - List<ServletInfo> servletInfos = modulInfo.getServlets(); - - Iterator<ServletInfo> servletInfoIterator = servletInfos.iterator(); - - while (servletInfoIterator.hasNext()) { - - ServletInfo servletInfo = servletInfoIterator.next(); - - if (servletInfo.getType() == ServletType.AUTH) { - HttpServlet servlet = servletInfo.getServletInstance(); - String target = servletInfo.getTarget(); - - if (target == null) { - throw new Exception( - String.format( - "%s does not return a valid target identifier!", - new Object[] { servlet.getClass() - .getName() })); - } - - if (tempMap.containsKey(target)) { - throw new Exception(String.format( - "%s tried to overwrite %s/%s", new Object[] { - servlet.getClass().getName(), path, - target })); - } - - tempMap.put(target, servlet); - Logger.info("Registered Servlet class: " - + servlet.getClass().getName() + " OK"); - } - - } - - // when there was no error we register all servlets into the real - // endpoint map ... - if (!tempMap.isEmpty()) { - endpointMap.put(path, tempMap); - } - } catch (Throwable e) { - Logger.error("Registering Modul class: " - + modulInfo.getClass().getName() + " FAILED!!", e); - } - } -*/ - @Override - public void init(ServletConfig config) throws ServletException { - try { - super.init(config); - MOAIDAuthInitializer.initialize(); - Logger.info(MOAIDMessageProvider.getInstance().getMessage( - "init.00", null)); - } catch (Exception ex) { - Logger.fatal( - MOAIDMessageProvider.getInstance().getMessage("init.02", - null), ex); - throw new ServletException(ex); - } - Logger.info("Auth dispatcher Servlet initialization"); -/* - List<IModulInfo> modules = ModulStorage.getAllModules(); - Iterator<IModulInfo> it = modules.iterator(); - while (it.hasNext()) { - IModulInfo info = it.next(); - String targetClass = info.getClass().getName(); - try { - registerModule(info); - } catch (Throwable e) { - Logger.error("Registering Class " + targetClass + " FAILED!!", - e); - } - }*/ - } - - protected void processRequest(HttpServletRequest req, - HttpServletResponse resp) throws ServletException, IOException { - try { - Object pathObject = req.getParameter(PARAM_TARGET_PATH); - String path = null; - - HttpSession session = req.getSession(); - - if (pathObject != null && (pathObject instanceof String)) { - path = (String) pathObject; - } - - if (path == null) { - path = (String) session.getAttribute(PARAM_TARGET_PATH); - } - - Object protocolObject = req.getParameter(PARAM_TARGET_PROTOCOL); - String protocol = null; - if (protocolObject != null && (protocolObject instanceof String)) { - protocol = (String) protocolObject; - } - - if (protocol == null) { - protocol = (String) session.getAttribute(PARAM_TARGET_PROTOCOL); - } - - Logger.debug("dispatching to " + path + " protocol " + protocol); -/* - if (path != null && protocol != null - && endpointMap.containsKey(path)) { - - IModulInfo info = ModulStorage.getModuleByPath(path); - - if (info == null) { - resp.sendError(HttpServletResponse.SC_NOT_FOUND); - Logger.error("Path " + path + " has no module registered"); - return; - } - - IAction action = info.getAction(protocol); - - if (action == null) { - resp.sendError(HttpServletResponse.SC_NOT_FOUND); - Logger.error("Action " + protocol + " is not available!"); - return; - } - - - - try { - IRequest configuration = info.preProcess(req, resp, protocol); - - if(configuration.forceAuth()) { - session.setAttribute(PARAM_TARGET_PATH, path); - session.setAttribute(PARAM_TARGET_PROTOCOL, protocol); - - AuthenticationManager.doAuthentication(req, resp, - configuration); - return; - } - - if (!AuthenticationManager.isAuthenticated(req, resp)) { - - session.setAttribute(PARAM_TARGET_PATH, path); - session.setAttribute(PARAM_TARGET_PROTOCOL, protocol); - - if(configuration.isPassiv()) { - throw new NoPassivAuthenticationException(); - } - - AuthenticationManager.doAuthentication(req, resp, - configuration); - return; - } - - HashMap<String, HttpServlet> pathMap = endpointMap.get(path); - Logger.debug("found path"); - if (pathMap.containsKey(protocol)) { - Logger.debug("found protocol"); - try { - HttpServlet servlet = (HttpServlet) pathMap - .get(protocol); - String forward = servlet.getClass().getName(); - Logger.info("Forwarding to Servlet: " + forward); - getServletContext().getNamedDispatcher(forward) - .forward(req, resp); - // TODO: disabled SSO - AuthenticationManager.logout(req, resp); - return; - } catch (Throwable e) { - e.printStackTrace(); - resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - } - } - } - catch (Throwable e) { - // Try handle module specific, if not possible rethrow - if(!info.generateErrorMessage(e, req, resp)) { - throw e; - } - } - }*/ - resp.sendError(HttpServletResponse.SC_NOT_FOUND); - }/* catch (WrongParametersException ex) { - handleWrongParameters(ex, req, resp); - } catch (MOAIDException ex) { - handleError(null, ex, req, resp); - } */catch (Throwable e) { - e.printStackTrace(); - resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - } - - } - - @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - processRequest(req, resp); - } - - @Override - protected void doPost(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - processRequest(req, resp); - } -} 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 abfb4a1c0..244197379 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 @@ -20,6 +20,7 @@ import at.gv.egovernment.moa.id.moduls.IRequest; 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.storage.ExceptionStoreImpl; import at.gv.egovernment.moa.id.util.MOAIDMessageProvider; import at.gv.egovernment.moa.logging.Logger; @@ -33,64 +34,6 @@ public class DispatcherServlet extends AuthServlet { public static final String PARAM_TARGET_MODULE = "mod"; public static final String PARAM_TARGET_ACTION = "action"; - /* - * public static final String PARAM_DISPATCHER_TARGETS = - * "DispatcherTargets"; public static final String PARAM_DISPATCHER_TYPE = - * "DispatcherType"; public static final String PARAM_DISPATCHER_TYPE_UNAUTH - * = "UNAUTH"; public static final String PARAM_DISPATCHER_TYPE_AUTH = - * "AUTH"; public static String SYSTEM_NEWLINE = - * System.getProperty("line.separator"); - */ - /* - * private HashMap<String, HashMap<String, HttpServlet>> endpointMap = new - * HashMap<String, HashMap<String, HttpServlet>>(); - * - * private void registerModule(IModulInfo modulInfo) { - * - * HashMap<String, HttpServlet> tempMap = new HashMap<String, - * HttpServlet>(); - * - * try { - * - * String path = modulInfo.getPath(); - * - * if (path == null) { throw new Exception(String.format( - * "%s does not return a valid target path!", new Object[] { - * modulInfo.getClass().getName() })); } - * - * Logger.debug("Registering: " + modulInfo.getName() + " under " + path); - * - * List<ServletInfo> servletInfos = modulInfo.getServlets(); - * - * Iterator<ServletInfo> servletInfoIterator = servletInfos.iterator(); - * - * while (servletInfoIterator.hasNext()) { - * - * ServletInfo servletInfo = servletInfoIterator.next(); - * - * if (servletInfo.getType() == ServletType.UNAUTH) { HttpServlet servlet = - * servletInfo.getServletInstance(); String target = - * servletInfo.getTarget(); - * - * if (target == null) { throw new Exception( String.format( - * "%s does not return a valid target identifier!", new Object[] { - * servlet.getClass() .getName() })); } - * - * if (tempMap.containsKey(target)) { throw new Exception(String.format( - * "%s tried to overwrite %s/%s", new Object[] { - * servlet.getClass().getName(), path, target })); } - * - * tempMap.put(target, servlet); Logger.info("Registered Servlet class: " + - * servlet.getClass().getName() + " OK"); } - * - * } - * - * // when there was no error we register all servlets into the real // - * endpoint map ... if (!tempMap.isEmpty()) { endpointMap.put(path, - * tempMap); } } catch (Throwable e) { - * Logger.error("Registering Modul class: " + modulInfo.getClass().getName() - * + " FAILED!!", e); } } - */ @Override public void init(ServletConfig config) throws ServletException { try { @@ -105,20 +48,53 @@ public class DispatcherServlet extends AuthServlet { throw new ServletException(ex); } Logger.info("Dispatcher Servlet initialization"); - - /* - * List<IModulInfo> modules = ModulStorage.getAllModules(); - * Iterator<IModulInfo> it = modules.iterator(); while (it.hasNext()) { - * IModulInfo info = it.next(); String targetClass = - * info.getClass().getName(); try { registerModule(info); } catch - * (Throwable e) { Logger.error("Registering Class " + targetClass + - * " FAILED!!", e); } } - */ } protected void processRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { + Logger.info("REQUEST: " + req.getRequestURI()); + Logger.info("QUERY : " + req.getQueryString()); + String errorid = req.getParameter(ERROR_CODE_PARAM); + if (errorid != null) { + + Throwable throwable = ExceptionStoreImpl.getStore() + .fetchException(errorid); + ExceptionStoreImpl.getStore().removeException(errorid); + + if (throwable != null) { + + IRequest errorRequest = RequestStorage + .getPendingRequest(req.getSession()); + if (errorRequest != null) { + try { + IModulInfo handlingModule = ModulStorage + .getModuleByPath(errorRequest + .requestedModule()); + if (handlingModule != null) { + if (handlingModule.generateErrorMessage( + throwable, req, resp, errorRequest)) { + return; + } + } + } catch (Throwable e) { + Logger.error(e); + handleErrorNoRedirect(throwable.getMessage(), + throwable, req, resp); + } + } + 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; if (moduleObject != null && (moduleObject instanceof String)) { @@ -181,8 +157,7 @@ public class DispatcherServlet extends AuthServlet { HttpSession httpSession = req.getSession(); IRequest protocolRequest = null; try { - protocolRequest = RequestStorage - .getPendingRequest(httpSession); + protocolRequest = RequestStorage.getPendingRequest(httpSession); if (protocolRequest != null) { // check if pending request is same protocol and action @@ -253,12 +228,10 @@ public class DispatcherServlet extends AuthServlet { } moduleAction.processRequest(protocolRequest, req, resp); - - RequestStorage.removePendingRequest(httpSession); - + RequestStorage.removePendingRequest(httpSession); authmanager.logout(req, resp); - + } catch (Throwable e) { e.printStackTrace(); // Try handle module specific, if not possible rethrow diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/ExternalPVPSessionStore.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/ExternalPVPSessionStore.java new file mode 100644 index 000000000..1e3c6145f --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/ExternalPVPSessionStore.java @@ -0,0 +1,28 @@ +package at.gv.egovernment.moa.id.protocols.pvp2x; + +import java.util.HashMap; +import java.util.Map; + +import org.opensaml.saml2.metadata.SPSSODescriptor; +import org.opensaml.xml.io.MarshallingException; + +public class ExternalPVPSessionStore { + + private Map<String, SPSSODescriptor> externalSessions = new HashMap<String, SPSSODescriptor>(); + + public boolean contains(String sessionID) { + return externalSessions.containsKey(sessionID); + } + + public void put(String sessionID, SPSSODescriptor sso) throws MarshallingException { + externalSessions.put(sessionID, sso); + } + + public SPSSODescriptor get(String sessionID) { + return externalSessions.get(sessionID); + } + + public void remove(String sessionID) { + externalSessions.remove(sessionID); + } +} 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 d9129165e..59eaa90b1 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 @@ -1,6 +1,5 @@ package at.gv.egovernment.moa.id.protocols.pvp2x; -import java.io.IOException; import java.io.StringWriter; import java.util.List; @@ -8,32 +7,28 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; -import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; +import org.joda.time.DateTime; import org.opensaml.Configuration; import org.opensaml.common.xml.SAMLConstants; -import org.opensaml.saml2.metadata.ArtifactResolutionService; +import org.opensaml.saml2.core.NameIDType; import org.opensaml.saml2.metadata.ContactPerson; +import org.opensaml.saml2.metadata.EntitiesDescriptor; import org.opensaml.saml2.metadata.EntityDescriptor; import org.opensaml.saml2.metadata.IDPSSODescriptor; 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.io.MarshallingException; -import org.opensaml.xml.security.SecurityException; import org.opensaml.xml.security.credential.Credential; import org.opensaml.xml.security.credential.UsageType; import org.opensaml.xml.security.keyinfo.KeyInfoGenerator; import org.opensaml.xml.security.x509.X509KeyInfoGeneratorFactory; import org.opensaml.xml.signature.Signature; -import org.opensaml.xml.signature.SignatureException; import org.opensaml.xml.signature.Signer; import org.w3c.dom.Document; @@ -43,8 +38,8 @@ import at.gv.egovernment.moa.id.moduls.IRequest; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.PVPAttributeBuilder; import at.gv.egovernment.moa.id.protocols.pvp2x.config.PVPConfiguration; import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialProvider; -import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialsNotAvailableException; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; +import at.gv.egovernment.moa.logging.Logger; public class MetadataAction implements IAction { @@ -52,9 +47,20 @@ public class MetadataAction implements IAction { HttpServletResponse httpResp) throws MOAIDException { try { + EntitiesDescriptor idpEntitiesDescriptor = + SAML2Utils.createSAMLObject(EntitiesDescriptor.class); + + idpEntitiesDescriptor.setName(PVPConfiguration.getInstance().getIDPIssuerName()); + + idpEntitiesDescriptor.setID(SAML2Utils.getSecureIdentifier()); + + idpEntitiesDescriptor.setValidUntil(new DateTime().plusWeeks(4)); + EntityDescriptor idpEntityDescriptor = SAML2Utils .createSAMLObject(EntityDescriptor.class); + idpEntitiesDescriptor.getEntityDescriptors().add(idpEntityDescriptor); + idpEntityDescriptor .setEntityID("https://localhost:8443/moa-id-auth"); @@ -83,13 +89,15 @@ public class MetadataAction implements IAction { Signature signature = CredentialProvider .getIDPSignature(credential); - idpEntityDescriptor.setSignature(signature); + idpEntitiesDescriptor.setSignature(signature); IDPSSODescriptor idpSSODescriptor = SAML2Utils .createSAMLObject(IDPSSODescriptor.class); - idpSSODescriptor.setWantAuthnRequestsSigned(true); - + idpSSODescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS); + + idpSSODescriptor.setWantAuthnRequestsSigned(true); + if (PVPConfiguration.getInstance().getIDPSSOPostService() != null) { SingleSignOnService postSingleSignOnService = SAML2Utils .createSAMLObject(SingleSignOnService.class); @@ -116,7 +124,7 @@ public class MetadataAction implements IAction { redirectSingleSignOnService); } - if (PVPConfiguration.getInstance().getIDPResolveSOAPService() != null) { + /*if (PVPConfiguration.getInstance().getIDPResolveSOAPService() != null) { ArtifactResolutionService artifactResolutionService = SAML2Utils .createSAMLObject(ArtifactResolutionService.class); @@ -125,14 +133,31 @@ public class MetadataAction implements IAction { artifactResolutionService.setLocation(PVPConfiguration .getInstance().getIDPResolveSOAPService()); + artifactResolutionService.setIndex(0); + idpSSODescriptor.getArtifactResolutionServices().add( artifactResolutionService); - } + }*/ idpSSODescriptor.getKeyDescriptors().add(signKeyDescriptor); idpSSODescriptor.getAttributes().addAll(PVPAttributeBuilder.buildSupportedEmptyAttributes()); + NameIDFormat persistenNameIDFormat = SAML2Utils.createSAMLObject(NameIDFormat.class); + persistenNameIDFormat.setFormat(NameIDType.PERSISTENT); + + idpSSODescriptor.getNameIDFormats().add(persistenNameIDFormat); + + NameIDFormat transientNameIDFormat = SAML2Utils.createSAMLObject(NameIDFormat.class); + transientNameIDFormat.setFormat(NameIDType.TRANSIENT); + + idpSSODescriptor.getNameIDFormats().add(transientNameIDFormat); + + NameIDFormat unspecifiedNameIDFormat = SAML2Utils.createSAMLObject(NameIDFormat.class); + unspecifiedNameIDFormat.setFormat(NameIDType.UNSPECIFIED); + + idpSSODescriptor.getNameIDFormats().add(unspecifiedNameIDFormat); + idpEntityDescriptor.getRoleDescriptors().add(idpSSODescriptor); DocumentBuilder builder; @@ -142,8 +167,8 @@ public class MetadataAction implements IAction { builder = factory.newDocumentBuilder(); Document document = builder.newDocument(); Marshaller out = Configuration.getMarshallerFactory() - .getMarshaller(idpEntityDescriptor); - out.marshall(idpEntityDescriptor, document); + .getMarshaller(idpEntitiesDescriptor); + out.marshall(idpEntitiesDescriptor, document); Signer.signObject(signature); @@ -165,33 +190,10 @@ public class MetadataAction implements IAction { httpResp.getOutputStream().close(); - } catch (CredentialsNotAvailableException e) { - e.printStackTrace(); - } catch (SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (ParserConfigurationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (MarshallingException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (SignatureException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (TransformerConfigurationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (TransformerFactoryConfigurationError e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (TransformerException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + } catch (Exception e) { + Logger.error("Failed to generate metadata", e); + throw new MOAIDException("pvp2.13", null); + } } public boolean needAuthentication(IRequest req, HttpServletRequest httpReq, 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 11710904b..41aa459ec 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 @@ -11,13 +11,19 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringEscapeUtils; +import org.opensaml.DefaultBootstrap; import org.opensaml.common.xml.SAMLConstants; import org.opensaml.saml2.core.AuthnRequest; import org.opensaml.saml2.core.RequestAbstractType; +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.StatusResponseType; +import org.opensaml.saml2.metadata.AssertionConsumerService; +import org.opensaml.saml2.metadata.AttributeConsumingService; +import org.opensaml.saml2.metadata.EntityDescriptor; +import org.opensaml.saml2.metadata.SPSSODescriptor; +import org.opensaml.xml.ConfigurationException; import at.gv.egovernment.moa.id.MOAIDException; import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; @@ -34,11 +40,13 @@ 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.config.PVPConfiguration; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.MandateAttributesNotHandleAbleException; +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.ChainSAMLValidator; -import at.gv.egovernment.moa.id.protocols.pvp2x.validation.SAMLSignatureValidator; -import at.gv.egovernment.moa.id.protocols.pvp2x.verification.ChainSAMLVerifier; -import at.gv.egovernment.moa.id.protocols.pvp2x.verification.SAMLVerifierMOASP; +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.ParamValidatorUtils; public class PVP2XProtocol implements IModulInfo, MOAIDAuthConstants { @@ -57,11 +65,7 @@ public class PVP2XProtocol implements IModulInfo, MOAIDAuthConstants { private static HashMap<String, IAction> actions = new HashMap<String, IAction>(); - private ChainSAMLVerifier samlVerifier = new ChainSAMLVerifier(); - - private ChainSAMLValidator samlValidator = new ChainSAMLValidator(); - - static { + static { servletList.add(new ServletInfo(PVPProcessor.class, REDIRECT, ServletType.AUTH)); servletList.add(new ServletInfo(PVPProcessor.class, POST, @@ -98,11 +102,11 @@ public class PVP2XProtocol implements IModulInfo, MOAIDAuthConstants { return PATH; } - private IDecoder findDecoder(String action) { + private IDecoder findDecoder(String action, HttpServletRequest req) { Iterator<IDecoder> decoderIT = decoder.iterator(); while (decoderIT.hasNext()) { IDecoder decoder = decoderIT.next(); - if (decoder.handleDecode(action)) { + if (decoder.handleDecode(action, req)) { return decoder; } } @@ -112,10 +116,6 @@ public class PVP2XProtocol implements IModulInfo, MOAIDAuthConstants { public PVP2XProtocol() { super(); - - samlVerifier.addVerifier(new SAMLVerifierMOASP()); - - samlValidator.addValidator(new SAMLSignatureValidator()); } public IRequest preProcess(HttpServletRequest request, @@ -125,7 +125,7 @@ public class PVP2XProtocol implements IModulInfo, MOAIDAuthConstants { return new PVPTargetConfiguration(); } - IDecoder decoder = findDecoder(action); + IDecoder decoder = findDecoder(action, request); if (decoder == null) { return null; } @@ -140,13 +140,11 @@ public class PVP2XProtocol implements IModulInfo, MOAIDAuthConstants { //Logger.info("SAML : " + xml); - // TODO: verify samlReq - //samlValidator.validateRequest(samlReq); - - // TODO: validate samlReq for - //samlVerifier.verifyRequest(samlReq); - - // TODO: OAURL is AssertionConsumerService URL from entitydescriptor ... + if(!moaRequest.isVerified()) { + SAMLVerificationEngine engine = new SAMLVerificationEngine(); + engine.verifyRequest(samlReq, TrustEngineFactory.getSignatureKnownKeysTrustEngine()); + moaRequest.setVerified(true); + } if(!(samlReq instanceof AuthnRequest)) { throw new MOAIDException("Unsupported request", new Object[] {}); @@ -155,16 +153,28 @@ public class PVP2XProtocol implements IModulInfo, MOAIDAuthConstants { AuthnRequest authnRequest = (AuthnRequest)samlReq; Integer aIdx = authnRequest.getAssertionConsumerServiceIndex(); - int idx = 0; + int assertionidx = 0; if(aIdx != null) { - idx = aIdx.intValue(); + assertionidx = aIdx.intValue(); } - String oaURL = moaRequest.getEntityMetadata(). - getSPSSODescriptor(SAMLConstants.SAML20P_NS). - getAssertionConsumerServices().get(idx).getLocation(); + aIdx = authnRequest.getAttributeConsumingServiceIndex(); + int attributeIdx = 0; + + if(aIdx != null) { + attributeIdx = aIdx.intValue(); + } + EntityDescriptor metadata = moaRequest.getEntityMetadata(); + if(metadata == null) { + throw new NoMetadataInformationException(); + } + SPSSODescriptor spSSODescriptor = metadata.getSPSSODescriptor(SAMLConstants.SAML20P_NS); + AssertionConsumerService consumerService = spSSODescriptor.getAssertionConsumerServices().get(assertionidx); + AttributeConsumingService attributeConsumer = spSSODescriptor.getAttributeConsumingServices().get(attributeIdx); + String oaURL = consumerService.getLocation(); + String binding = consumerService.getBinding(); String entityID = moaRequest.getEntityMetadata().getEntityID(); //String oaURL = (String) request.getParameter(PARAM_OA); @@ -173,9 +183,19 @@ public class PVP2XProtocol implements IModulInfo, MOAIDAuthConstants { throw new WrongParametersException("StartAuthentication", PARAM_OA, "auth.12"); config.setOAURL(oaURL); + config.setBinding(binding); config.setRequest(moaRequest); config.setTarget(PVPConfiguration.getInstance().getTargetForSP(entityID)); + String useMandate = request.getParameter(PARAM_USEMANDATE); + if(useMandate != null) { + if(useMandate.equals("true")) { + if(!CheckMandateAttributes.canHandleMandate(attributeConsumer)) { + throw new MandateAttributesNotHandleAbleException(); + } + } + } + request.getSession().setAttribute(PARAM_OA, oaURL); return config; @@ -193,23 +213,52 @@ public class PVP2XProtocol implements IModulInfo, MOAIDAuthConstants { throw e; } - StatusResponseType samlResponse = - SAML2Utils.createSAMLObject(StatusResponseType.class); + if(!(protocolRequest instanceof PVPTargetConfiguration) ) { + throw e; + } + PVPTargetConfiguration pvpRequest = (PVPTargetConfiguration)protocolRequest; + + Response samlResponse = + SAML2Utils.createSAMLObject(Response.class); Status status = SAML2Utils.createSAMLObject(Status.class); StatusCode statusCode = SAML2Utils.createSAMLObject(StatusCode.class); StatusMessage statusMessage = SAML2Utils.createSAMLObject(StatusMessage.class); if(e instanceof NoPassivAuthenticationException) { statusCode.setValue(StatusCode.NO_PASSIVE_URI); statusMessage.setMessage(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); + } } else { statusCode.setValue(StatusCode.RESPONDER_URI); statusMessage.setMessage(e.getLocalizedMessage()); } status.setStatusCode(statusCode); - status.setStatusMessage(statusMessage); + if(statusMessage.getMessage() != null) { + status.setStatusMessage(statusMessage); + } samlResponse.setStatus(status); - IEncoder encoder = new RedirectBinding(); + + IEncoder encoder = null; + + if(pvpRequest.getBinding().equals(SAMLConstants.SAML2_REDIRECT_BINDING_URI)) { + encoder = new RedirectBinding(); + } else if(pvpRequest.getBinding().equals(SAMLConstants.SAML2_ARTIFACT_BINDING_URI)) { + // TODO: not supported YET!! + //binding = new ArtifactBinding(); + } else if(pvpRequest.getBinding().equals(SAMLConstants.SAML2_POST_BINDING_URI)) { + encoder = new PostBinding(); + } + + if(encoder == null) { + // default to redirect binding + encoder = new RedirectBinding(); + } encoder.encodeRespone(request, response, samlResponse, protocolRequest.getOAURL()); return true; @@ -221,9 +270,11 @@ public class PVP2XProtocol implements IModulInfo, MOAIDAuthConstants { public IAction canHandleRequest(HttpServletRequest request, HttpServletResponse response) { - if(request.getParameter("SAMLRequest") != null) { + if(request.getParameter("SAMLRequest") != null && request.getMethod().equals("GET")) { return getAction(REDIRECT); - } + } else if(request.getParameter("SAMLRequest") != null && request.getMethod().equals("POST")) { + return getAction(POST); + } if(METADATA.equals(request.getParameter("action"))) { return getAction(METADATA); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPConstants.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPConstants.java index b818a2d8a..5875a37c7 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPConstants.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPConstants.java @@ -1,6 +1,12 @@ package at.gv.egovernment.moa.id.protocols.pvp2x; public interface PVPConstants { + + public static final String STORK_QAA_1_1 = "http://www.ref.gv.at/ns/names/agiz/stork/qaa/1"; + public static final String STORK_QAA_1_2 = "http://www.ref.gv.at/ns/names/agiz/stork/qaa/1-2"; + public static final String STORK_QAA_1_3 = "http://www.ref.gv.at/ns/names/agiz/stork/qaa/1-3"; + public static final String STORK_QAA_1_4 = "http://www.ref.gv.at/ns/names/agiz/stork/qaa/1-4"; + public static final String URN_OID_PREFIX = "urn:oid:"; public static final String PVP_VERSION_OID = "1.2.40.0.10.2.1.1.261.10"; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPTargetConfiguration.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPTargetConfiguration.java index 1f13cdfb5..d15c307a1 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPTargetConfiguration.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPTargetConfiguration.java @@ -5,6 +5,7 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.binding.MOARequest; public class PVPTargetConfiguration extends RequestImpl { MOARequest request; + String binding; public MOARequest getRequest() { return request; @@ -13,4 +14,12 @@ public class PVPTargetConfiguration extends RequestImpl { public void setRequest(MOARequest request) { this.request = request; } + + public String getBinding() { + return binding; + } + + public void setBinding(String binding) { + this.binding = binding; + } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/SAMLRequestNotSignedException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/SAMLRequestNotSignedException.java deleted file mode 100644 index 40f5685ad..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/SAMLRequestNotSignedException.java +++ /dev/null @@ -1,17 +0,0 @@ -package at.gv.egovernment.moa.id.protocols.pvp2x; - -import at.gv.egovernment.moa.id.MOAIDException; - -public class SAMLRequestNotSignedException extends MOAIDException { - - public SAMLRequestNotSignedException(String messageId, Object[] parameters) { - super(messageId, parameters); - // TODO Auto-generated constructor stub - } - - /** - * - */ - private static final long serialVersionUID = 1L; - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/SAMLRequestNotSupported.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/SAMLRequestNotSupported.java deleted file mode 100644 index 16b388a09..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/SAMLRequestNotSupported.java +++ /dev/null @@ -1,16 +0,0 @@ -package at.gv.egovernment.moa.id.protocols.pvp2x; - -import at.gv.egovernment.moa.id.MOAIDException; - -public class SAMLRequestNotSupported extends MOAIDException { - - public SAMLRequestNotSupported(String messageId, Object[] parameters) { - super(messageId, parameters); - } - - /** - * - */ - private static final long serialVersionUID = 1244883178458802767L; - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/ArtifactBinding.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/ArtifactBinding.java index 8f83812a6..1d51d91f1 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/ArtifactBinding.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/ArtifactBinding.java @@ -1,12 +1,5 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.binding; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.UnrecoverableKeyException; -import java.security.cert.CertificateException; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -14,6 +7,7 @@ import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.runtime.RuntimeConstants; import org.opensaml.common.SAMLObject; import org.opensaml.common.binding.BasicSAMLMessageContext; +import org.opensaml.common.xml.SAMLConstants; import org.opensaml.saml2.binding.encoding.HTTPArtifactEncoder; import org.opensaml.saml2.core.RequestAbstractType; import org.opensaml.saml2.core.StatusResponseType; @@ -68,11 +62,10 @@ public class ArtifactBinding implements IDecoder, IEncoder { BasicSAMLMessageContext<SAMLObject, SAMLObject, SAMLObject> context = new BasicSAMLMessageContext<SAMLObject, SAMLObject, SAMLObject>(); SingleSignOnService service = new SingleSignOnServiceBuilder() .buildObject(); - service.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Artifact"); + service.setBinding(SAMLConstants.SAML2_ARTIFACT_BINDING_URI); service.setLocation(targetLocation); context.setOutboundSAMLMessageSigningCredential(credentials); context.setPeerEntityEndpoint(service); - // context.setOutboundMessage(authReq); context.setOutboundSAMLMessage(response); context.setOutboundMessageTransport(responseAdapter); @@ -97,7 +90,7 @@ public class ArtifactBinding implements IDecoder, IEncoder { return null; } - public boolean handleDecode(String action) { + public boolean handleDecode(String action, HttpServletRequest req) { // TODO Auto-generated method stub return false; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/IDecoder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/IDecoder.java index 2778016ba..0f82d9a3f 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/IDecoder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/IDecoder.java @@ -6,14 +6,16 @@ import javax.servlet.http.HttpServletResponse; import org.opensaml.ws.message.decoder.MessageDecodingException; import org.opensaml.xml.security.SecurityException; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; + public interface IDecoder { public MOARequest decodeRequest(HttpServletRequest req, HttpServletResponse resp) - throws MessageDecodingException, SecurityException; + throws MessageDecodingException, SecurityException, PVP2Exception; public MOAResponse decodeRespone(HttpServletRequest req, HttpServletResponse resp) - throws MessageDecodingException, SecurityException; + throws MessageDecodingException, SecurityException, PVP2Exception; - public boolean handleDecode(String action); + public boolean handleDecode(String action, HttpServletRequest req); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/IEncoder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/IEncoder.java index f2c392a2a..66526534d 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/IEncoder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/IEncoder.java @@ -8,12 +8,23 @@ import org.opensaml.saml2.core.StatusResponseType; import org.opensaml.ws.message.encoder.MessageEncodingException; import org.opensaml.xml.security.SecurityException; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; + public interface IEncoder { public void encodeRequest(HttpServletRequest req, HttpServletResponse resp, RequestAbstractType request, String targetLocation) - throws MessageEncodingException, SecurityException; + throws MessageEncodingException, SecurityException, PVP2Exception; + /** + * Encoder SAML Response + * @param req The http request + * @param resp The http response + * @param response The repsonse object + * @param targetLocation + * @throws MessageEncodingException + * @throws SecurityException + */ public void encodeRespone(HttpServletRequest req, HttpServletResponse resp, StatusResponseType response, String targetLocation) - throws MessageEncodingException, SecurityException; + throws MessageEncodingException, SecurityException, PVP2Exception; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/MOAURICompare.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/MOAURICompare.java new file mode 100644 index 000000000..513939e5d --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/MOAURICompare.java @@ -0,0 +1,12 @@ +package at.gv.egovernment.moa.id.protocols.pvp2x.binding; + +import org.opensaml.common.binding.decoding.URIComparator; + +public class MOAURICompare implements URIComparator { + + public boolean compare(String uri1, String uri2) { + // TODO: implement proper equalizer for rewritten URLS + return true; + } + +} 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 c7d779fa2..6e826005d 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 @@ -7,13 +7,16 @@ import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.runtime.RuntimeConstants; import org.opensaml.common.SAMLObject; import org.opensaml.common.binding.BasicSAMLMessageContext; +import org.opensaml.common.xml.SAMLConstants; import org.opensaml.saml2.binding.decoding.HTTPPostDecoder; import org.opensaml.saml2.binding.encoding.HTTPPostEncoder; import org.opensaml.saml2.core.RequestAbstractType; import org.opensaml.saml2.core.Response; import org.opensaml.saml2.core.StatusResponseType; +import org.opensaml.saml2.metadata.SPSSODescriptor; import org.opensaml.saml2.metadata.SingleSignOnService; import org.opensaml.saml2.metadata.impl.SingleSignOnServiceBuilder; +import org.opensaml.saml2.metadata.provider.MetadataProviderException; import org.opensaml.ws.message.decoder.MessageDecodingException; import org.opensaml.ws.message.encoder.MessageEncodingException; import org.opensaml.ws.transport.http.HttpServletRequestAdapter; @@ -21,11 +24,11 @@ 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.signature.Signature; -import at.gv.egovernment.moa.id.protocols.pvp2x.PVP2XProtocol; +import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialsNotAvailableException; +import at.gv.egovernment.moa.logging.Logger; public class PostBinding implements IDecoder, IEncoder { @@ -44,9 +47,6 @@ public class PostBinding implements IDecoder, IEncoder { Credential credentials = CredentialProvider .getIDPSigningCredential(); - Signature signer = CredentialProvider.getIDPSignature(credentials); - response.setSignature(signer); - VelocityEngine engine = new VelocityEngine(); engine.setProperty(RuntimeConstants.ENCODING_DEFAULT, "UTF-8"); engine.setProperty(RuntimeConstants.OUTPUT_ENCODING, "UTF-8"); @@ -63,7 +63,7 @@ public class PostBinding implements IDecoder, IEncoder { BasicSAMLMessageContext<SAMLObject, SAMLObject, SAMLObject> context = new BasicSAMLMessageContext<SAMLObject, SAMLObject, SAMLObject>(); SingleSignOnService service = new SingleSignOnServiceBuilder() .buildObject(); - service.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-REDIRECT"); + service.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); service.setLocation(targetLocation); context.setOutboundSAMLMessageSigningCredential(credentials); context.setPeerEntityEndpoint(service); @@ -86,13 +86,24 @@ public class PostBinding implements IDecoder, IEncoder { BasicSAMLMessageContext<RequestAbstractType, ?, ?> messageContext = new BasicSAMLMessageContext<RequestAbstractType, SAMLObject, SAMLObject>(); messageContext .setInboundMessageTransport(new HttpServletRequestAdapter(req)); + decode.setURIComparator(new MOAURICompare()); + messageContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME); + + try { + messageContext.setMetadataProvider(new MOAMetadataProvider()); + } catch (MetadataProviderException e) { + Logger.error("Failed to get Metadata Provider"); + throw new SecurityException("Failed to get Metadata Provider"); + } + decode.decode(messageContext); RequestAbstractType inboundMessage = (RequestAbstractType) messageContext .getInboundMessage(); - + MOARequest request = new MOARequest(inboundMessage); - + request.setVerified(false); + request.setEntityMetadata(messageContext.getPeerEntityMetadata()); return request; } @@ -105,16 +116,21 @@ public class PostBinding implements IDecoder, IEncoder { BasicSAMLMessageContext<Response, ?, ?> messageContext = new BasicSAMLMessageContext<Response, SAMLObject, SAMLObject>(); messageContext .setInboundMessageTransport(new HttpServletRequestAdapter(req)); + + messageContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME); + decode.decode(messageContext); Response inboundMessage = (Response) messageContext.getInboundMessage(); - + MOAResponse moaResponse = new MOAResponse(inboundMessage); + moaResponse.setVerified(false); + moaResponse.setEntityMetadata(messageContext.getPeerEntityMetadata()); return moaResponse; } - public boolean handleDecode(String action) { - return (action.equals(PVP2XProtocol.POST)); + public boolean handleDecode(String action, HttpServletRequest req) { + return (req.getMethod().equals("POST")); } } 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 92a6b6002..4e7b08b21 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 @@ -5,6 +5,7 @@ import javax.servlet.http.HttpServletResponse; import org.opensaml.common.SAMLObject; import org.opensaml.common.binding.BasicSAMLMessageContext; +import org.opensaml.common.xml.SAMLConstants; import org.opensaml.saml2.binding.decoding.HTTPRedirectDeflateDecoder; import org.opensaml.saml2.binding.encoding.HTTPRedirectDeflateEncoder; import org.opensaml.saml2.binding.security.SAML2HTTPRedirectDeflateSignatureRule; @@ -25,20 +26,20 @@ 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.signature.Signature; import at.gv.egovernment.moa.id.protocols.pvp2x.PVP2XProtocol; import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialsNotAvailableException; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.TrustEngineFactory; +import at.gv.egovernment.moa.logging.Logger; public class RedirectBinding implements IDecoder, IEncoder { public void encodeRequest(HttpServletRequest req, HttpServletResponse resp, RequestAbstractType request, String targetLocation) throws MessageEncodingException, SecurityException { - + //TODO: implement } public void encodeRespone(HttpServletRequest req, HttpServletResponse resp, @@ -48,17 +49,13 @@ public class RedirectBinding implements IDecoder, IEncoder { Credential credentials = CredentialProvider .getIDPSigningCredential(); - Signature signer = CredentialProvider.getIDPSignature(credentials); - response.setSignature(signer); - - HTTPRedirectDeflateEncoder encoder = new HTTPRedirectDeflateEncoder(); HttpServletResponseAdapter responseAdapter = new HttpServletResponseAdapter( resp, true); BasicSAMLMessageContext<SAMLObject, SAMLObject, SAMLObject> context = new BasicSAMLMessageContext<SAMLObject, SAMLObject, SAMLObject>(); SingleSignOnService service = new SingleSignOnServiceBuilder() .buildObject(); - service.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-REDIRECT"); + service.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); service.setLocation(targetLocation); context.setOutboundSAMLMessageSigningCredential(credentials); context.setPeerEntityEndpoint(service); @@ -79,6 +76,7 @@ public class RedirectBinding implements IDecoder, IEncoder { HTTPRedirectDeflateDecoder decode = new HTTPRedirectDeflateDecoder( new BasicParserPool()); + decode.setURIComparator(new MOAURICompare()); BasicSAMLMessageContext<RequestAbstractType, ?, ?> messageContext = new BasicSAMLMessageContext<RequestAbstractType, SAMLObject, SAMLObject>(); messageContext .setInboundMessageTransport(new HttpServletRequestAdapter(req)); @@ -86,8 +84,8 @@ public class RedirectBinding implements IDecoder, IEncoder { try { messageContext.setMetadataProvider(new MOAMetadataProvider()); } catch (MetadataProviderException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + Logger.error("Failed to get Metadata Provider"); + throw new SecurityException("Failed to get Metadata Provider"); } SAML2HTTPRedirectDeflateSignatureRule signatureRule = new SAML2HTTPRedirectDeflateSignatureRule( @@ -99,6 +97,7 @@ public class RedirectBinding implements IDecoder, IEncoder { policy); messageContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME); messageContext.setSecurityPolicyResolver(resolver); + decode.decode(messageContext); signatureRule.evaluate(messageContext); @@ -121,7 +120,6 @@ public class RedirectBinding implements IDecoder, IEncoder { messageContext .setInboundMessageTransport(new HttpServletRequestAdapter(req)); - // TODO: used to verify signature! SAML2HTTPRedirectDeflateSignatureRule signatureRule = new SAML2HTTPRedirectDeflateSignatureRule( TrustEngineFactory.getSignatureKnownKeysTrustEngine()); @@ -132,6 +130,14 @@ public class RedirectBinding implements IDecoder, IEncoder { policy); messageContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME); messageContext.setSecurityPolicyResolver(resolver); + MOAMetadataProvider provider = null; + try { + provider = new MOAMetadataProvider(); + } catch (MetadataProviderException e) { + Logger.error("Failed to get Metadata Provider"); + throw new SecurityException("Failed to get Metadata Provider"); + } + messageContext.setMetadataProvider(provider); decode.decode(messageContext); @@ -143,7 +149,7 @@ public class RedirectBinding implements IDecoder, IEncoder { return moaResponse; } - public boolean handleDecode(String action) { - return (action.equals(PVP2XProtocol.REDIRECT)); + public boolean handleDecode(String action, HttpServletRequest req) { + return (action.equals(PVP2XProtocol.REDIRECT) && req.getMethod().equals("GET")); } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/SoapBinding.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/SoapBinding.java index 027dab15a..04ec3eaee 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/SoapBinding.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/SoapBinding.java @@ -5,23 +5,31 @@ import javax.servlet.http.HttpServletResponse; import org.opensaml.common.SAMLObject; import org.opensaml.common.binding.BasicSAMLMessageContext; +import org.opensaml.common.xml.SAMLConstants; import org.opensaml.saml2.binding.encoding.HTTPSOAP11Encoder; import org.opensaml.saml2.core.RequestAbstractType; -import org.opensaml.saml2.core.Response; import org.opensaml.saml2.core.StatusResponseType; +import org.opensaml.saml2.metadata.SingleSignOnService; +import org.opensaml.saml2.metadata.impl.SingleSignOnServiceBuilder; import org.opensaml.ws.message.decoder.MessageDecodingException; import org.opensaml.ws.message.encoder.MessageEncodingException; import org.opensaml.ws.soap.soap11.decoder.http.HTTPSOAP11Decoder; import org.opensaml.ws.transport.http.HttpServletRequestAdapter; +import org.opensaml.ws.transport.http.HttpServletResponseAdapter; import org.opensaml.xml.security.SecurityException; +import org.opensaml.xml.security.credential.Credential; import at.gv.egovernment.moa.id.protocols.pvp2x.PVP2XProtocol; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.BindingNotSupportedException; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; +import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialProvider; +import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialsNotAvailableException; public class SoapBinding implements IDecoder, IEncoder { public MOARequest decodeRequest(HttpServletRequest req, HttpServletResponse resp) throws MessageDecodingException, - SecurityException { + SecurityException, PVP2Exception { HTTPSOAP11Decoder soapDecoder = new HTTPSOAP11Decoder(); BasicSAMLMessageContext<RequestAbstractType, ?, ?> messageContext = new BasicSAMLMessageContext<RequestAbstractType, SAMLObject, SAMLObject>(); @@ -40,38 +48,40 @@ public class SoapBinding implements IDecoder, IEncoder { public MOAResponse decodeRespone(HttpServletRequest req, HttpServletResponse resp) throws MessageDecodingException, - SecurityException { - HTTPSOAP11Decoder soapDecoder = new HTTPSOAP11Decoder(); - BasicSAMLMessageContext<Response, ?, ?> messageContext = - new BasicSAMLMessageContext<Response, SAMLObject, SAMLObject>(); - messageContext - .setInboundMessageTransport(new HttpServletRequestAdapter( - req)); - soapDecoder.decode(messageContext); - - Response inboundMessage = (Response) messageContext - .getInboundMessage(); - - MOAResponse moaResponse = new MOAResponse(inboundMessage); - return moaResponse; + SecurityException, PVP2Exception { + throw new BindingNotSupportedException(SAMLConstants.SAML2_SOAP11_BINDING_URI + " response"); } - public boolean handleDecode(String action) { + public boolean handleDecode(String action, HttpServletRequest req) { return (action.equals(PVP2XProtocol.SOAP)); } public void encodeRequest(HttpServletRequest req, HttpServletResponse resp, RequestAbstractType request, String targetLocation) - throws MessageEncodingException, SecurityException { - // TODO Auto-generated method stub + throws MessageEncodingException, SecurityException, PVP2Exception { } public void encodeRespone(HttpServletRequest req, HttpServletResponse resp, StatusResponseType response, String targetLocation) - throws MessageEncodingException, SecurityException { - HTTPSOAP11Encoder encoder = new HTTPSOAP11Encoder(); - + throws MessageEncodingException, SecurityException, PVP2Exception { + try { + Credential credentials = CredentialProvider + .getIDPSigningCredential(); + + HTTPSOAP11Encoder encoder = new HTTPSOAP11Encoder(); + HttpServletResponseAdapter responseAdapter = new HttpServletResponseAdapter( + resp, true); + BasicSAMLMessageContext<SAMLObject, SAMLObject, SAMLObject> context = new BasicSAMLMessageContext<SAMLObject, SAMLObject, SAMLObject>(); + context.setOutboundSAMLMessageSigningCredential(credentials); + context.setOutboundSAMLMessage(response); + context.setOutboundMessageTransport(responseAdapter); + + encoder.encode(context); + } catch (CredentialsNotAvailableException e) { + e.printStackTrace(); + throw new SecurityException(e); + } } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAttributeBuilder.java index dc0a2884a..1962d1c7b 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAttributeBuilder.java @@ -15,8 +15,21 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.EIDIssuingNat import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.EIDSectorForIDAttributeBuilder; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.GivenNameAttributeBuilder; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.IAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateFullMandateAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateLegalPersonFullNameAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateLegalPersonSourcePinAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateLegalPersonSourcePinTypeAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateNaturalPersonBPKAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateNaturalPersonBirthDateAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateNaturalPersonFamilyNameAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateNaturalPersonGivenNameAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateProfRepDescAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateProfRepOIDAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateReferenceValueAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateTypeAttributeBuilder; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.PVPVersionAttributeBuilder; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.PrincipalNameAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; public class PVPAttributeBuilder { @@ -28,6 +41,7 @@ public class PVPAttributeBuilder { static { builders = new HashMap<String, IAttributeBuilder>(); + // Citizen Token normal addBuilder(new PVPVersionAttributeBuilder()); addBuilder(new PrincipalNameAttributeBuilder()); addBuilder(new GivenNameAttributeBuilder()); @@ -36,10 +50,25 @@ public class PVPAttributeBuilder { addBuilder(new EIDCitizenQAALevelAttributeBuilder()); addBuilder(new EIDIssuingNationAttributeBuilder()); addBuilder(new EIDSectorForIDAttributeBuilder()); + + // Mandate Attributes + addBuilder(new MandateTypeAttributeBuilder()); + addBuilder(new MandateLegalPersonFullNameAttributeBuilder()); + addBuilder(new MandateLegalPersonSourcePinAttributeBuilder()); + addBuilder(new MandateLegalPersonSourcePinTypeAttributeBuilder()); + addBuilder(new MandateNaturalPersonBirthDateAttributeBuilder()); + addBuilder(new MandateNaturalPersonBPKAttributeBuilder()); + addBuilder(new MandateNaturalPersonFamilyNameAttributeBuilder()); + addBuilder(new MandateNaturalPersonGivenNameAttributeBuilder()); + addBuilder(new MandateTypeAttributeBuilder()); + addBuilder(new MandateProfRepOIDAttributeBuilder()); + addBuilder(new MandateProfRepDescAttributeBuilder()); + addBuilder(new MandateReferenceValueAttributeBuilder()); + addBuilder(new MandateFullMandateAttributeBuilder()); } public static Attribute buildAttribute(String name, - AuthenticationSession authSession) { + AuthenticationSession authSession) throws PVP2Exception { if (builders.containsKey(name)) { return builders.get(name).build(authSession); } 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 new file mode 100644 index 000000000..2038ef5a5 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java @@ -0,0 +1,228 @@ +package at.gv.egovernment.moa.id.protocols.pvp2x.builder.assertion; + +import java.util.Iterator; + +import org.joda.time.DateTime; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.Assertion; +import org.opensaml.saml2.core.Attribute; +import org.opensaml.saml2.core.AttributeStatement; +import org.opensaml.saml2.core.Audience; +import org.opensaml.saml2.core.AudienceRestriction; +import org.opensaml.saml2.core.AuthnContext; +import org.opensaml.saml2.core.AuthnContextClassRef; +import org.opensaml.saml2.core.AuthnRequest; +import org.opensaml.saml2.core.AuthnStatement; +import org.opensaml.saml2.core.Conditions; +import org.opensaml.saml2.core.Issuer; +import org.opensaml.saml2.core.NameID; +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.metadata.AttributeConsumingService; +import org.opensaml.saml2.metadata.EntityDescriptor; +import org.opensaml.saml2.metadata.NameIDFormat; +import org.opensaml.saml2.metadata.RequestedAttribute; +import org.opensaml.saml2.metadata.SPSSODescriptor; + +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.PVPAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.config.PVPConfiguration; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NameIDFormatNotSupportedException; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NoAuthContextException; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.QAANotSupportedException; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.UnprovideableAttributeException; +import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; +import at.gv.egovernment.moa.logging.Logger; + +public class PVP2AssertionBuilder implements PVPConstants { + public static Assertion buildAssertion(AuthnRequest authnRequest, + AuthenticationSession authSession, EntityDescriptor peerEntity) throws PVP2Exception { + Assertion assertion = SAML2Utils.createSAMLObject(Assertion.class); + + RequestedAuthnContext reqAuthnContext = authnRequest + .getRequestedAuthnContext(); + + if (reqAuthnContext == null) { + throw new NoAuthContextException(); + } + + boolean stork_qaa_1_4_found = false; + + Iterator<AuthnContextClassRef> reqAuthnContextClassRefIt = reqAuthnContext + .getAuthnContextClassRefs().iterator(); + + 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)) { + stork_qaa_1_4_found = true; + break; + } + } + } + + 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(" "); + } + } + + } + AuthnContextClassRef authnContextClassRef = SAML2Utils + .createSAMLObject(AuthnContextClassRef.class); + authnContextClassRef.setAuthnContextClassRef(authContextsb.toString()); + AuthnContext authnContext = SAML2Utils + .createSAMLObject(AuthnContext.class); + authnContext.setAuthnContextClassRef(authnContextClassRef); + + AuthnStatement authnStatement = SAML2Utils + .createSAMLObject(AuthnStatement.class); + String remoteSessionID = SAML2Utils.getSecureIdentifier(); + authnStatement.setAuthnInstant(new DateTime()); + // currently dummy id ... + authnStatement.setSessionIndex(remoteSessionID); + authnStatement.setAuthnContext(authnContext); + + assertion.getAuthnStatements().add(authnStatement); + + SPSSODescriptor spSSODescriptor = peerEntity + .getSPSSODescriptor(SAMLConstants.SAML20P_NS); + + Integer aIdx = authnRequest.getAttributeConsumingServiceIndex(); + int idx = 0; + + if (aIdx != null) { + idx = aIdx.intValue(); + } + + AttributeConsumingService attributeConsumingService = spSSODescriptor + .getAttributeConsumingServices().get(idx); + + AttributeStatement attributeStatement = SAML2Utils + .createSAMLObject(AttributeStatement.class); + + Subject subject = SAML2Utils.createSAMLObject(Subject.class); + NameID subjectNameID = SAML2Utils.createSAMLObject(NameID.class); + boolean foundFormat = false; + 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); } } + */ + + Iterator<RequestedAttribute> it = attributeConsumingService + .getRequestAttributes().iterator(); + while (it.hasNext()) { + RequestedAttribute reqAttribut = it.next(); + try { + Attribute attr = PVPAttributeBuilder.buildAttribute( + reqAttribut.getName(), authSession); + 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()); + } + } + } + + if (attributeStatement.getAttributes().size() > 0) { + assertion.getAttributeStatements().add(attributeStatement); + } + + subjectNameID.setFormat(NameID.PERSISTENT); + subjectNameID.setNameQualifier(authSession.getAssertionAuthData() + .getIdentificationType()); + subjectNameID.setValue(authSession.getAssertionAuthData() + .getIdentificationValue()); + // } + + subject.setNameID(subjectNameID); + + SubjectConfirmation subjectConfirmation = SAML2Utils + .createSAMLObject(SubjectConfirmation.class); + subjectConfirmation.setMethod(SubjectConfirmation.METHOD_BEARER); + SubjectConfirmationData subjectConfirmationData = SAML2Utils + .createSAMLObject(SubjectConfirmationData.class); + subjectConfirmationData.setInResponseTo(authnRequest.getID()); + subjectConfirmationData.setNotOnOrAfter(new DateTime().plusMinutes(20)); + subjectConfirmationData.setRecipient(peerEntity.getEntityID()); + + subjectConfirmation.setSubjectConfirmationData(subjectConfirmationData); + + subject.getSubjectConfirmations().add(subjectConfirmation); + + Conditions conditions = SAML2Utils.createSAMLObject(Conditions.class); + AudienceRestriction audienceRestriction = SAML2Utils + .createSAMLObject(AudienceRestriction.class); + Audience audience = SAML2Utils.createSAMLObject(Audience.class); + + audience.setAudienceURI(peerEntity.getEntityID()); + audienceRestriction.getAudiences().add(audience); + conditions.setNotBefore(new DateTime()); + conditions.setNotOnOrAfter(new DateTime().plusMinutes(20)); + conditions.getAudienceRestrictions().add(audienceRestriction); + + assertion.setConditions(conditions); + + Issuer issuer = SAML2Utils.createSAMLObject(Issuer.class); + issuer.setValue(PVPConfiguration.getInstance().getIDPIssuerName()); + issuer.setFormat(NameID.ENTITY); + assertion.setIssuer(issuer); + assertion.setSubject(subject); + assertion.setID(SAML2Utils.getSecureIdentifier()); + assertion.setIssueInstant(new DateTime()); + + return assertion; + } +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/BPKAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/BPKAttributeBuilder.java index 0b1d80e0d..ae3715b57 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/BPKAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/BPKAttributeBuilder.java @@ -11,7 +11,7 @@ public class BPKAttributeBuilder extends BaseAttributeBuilder { } public Attribute build(AuthenticationSession authSession) { - String bpk = authSession.getIdentityLink().getIdentificationValue(); + String bpk = authSession.getAssertionAuthData().getIdentificationValue(); if(bpk.length() > BPK_MAX_LENGTH) { bpk = bpk.substring(0, BPK_MAX_LENGTH); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/BaseAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/BaseAttributeBuilder.java index d62cf72b1..d3c79c939 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/BaseAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/BaseAttributeBuilder.java @@ -35,6 +35,7 @@ public abstract class BaseAttributeBuilder implements PVPConstants, IAttributeBu SAML2Utils.createSAMLObject(Attribute.class); attribute.setFriendlyName(friendlyName); attribute.setName(name); + attribute.setNameFormat(Attribute.URI_REFERENCE); attribute.getAttributeValues().add(buildAttributeStringValue(value)); return attribute; } @@ -45,6 +46,7 @@ public abstract class BaseAttributeBuilder implements PVPConstants, IAttributeBu SAML2Utils.createSAMLObject(Attribute.class); attribute.setFriendlyName(friendlyName); attribute.setName(name); + attribute.setNameFormat(Attribute.URI_REFERENCE); attribute.getAttributeValues().add(buildAttributeIntegerValue(value)); return attribute; } @@ -54,6 +56,7 @@ public abstract class BaseAttributeBuilder implements PVPConstants, IAttributeBu SAML2Utils.createSAMLObject(Attribute.class); attribute.setFriendlyName(friendlyName); attribute.setName(name); + attribute.setNameFormat(Attribute.URI_REFERENCE); return attribute; } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDCitizenQAALevelAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDCitizenQAALevelAttributeBuilder.java index 5524ed44d..d9c66e6f0 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDCitizenQAALevelAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDCitizenQAALevelAttributeBuilder.java @@ -12,7 +12,7 @@ public class EIDCitizenQAALevelAttributeBuilder extends BaseAttributeBuilder { public Attribute build(AuthenticationSession authSession) { return buildIntegerAttribute(EID_CITIZEN_QAA_LEVEL_FRIENDLY_NAME, - EID_CITIZEN_QAA_LEVEL_NAME, 2); + EID_CITIZEN_QAA_LEVEL_NAME, 4); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDIssuingNationAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDIssuingNationAttributeBuilder.java index 251d263d9..2452e35c9 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDIssuingNationAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDIssuingNationAttributeBuilder.java @@ -1,8 +1,14 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; +import iaik.x509.X509Certificate; + +import javax.naming.ldap.LdapName; +import javax.naming.ldap.Rdn; + import org.opensaml.saml2.core.Attribute; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.logging.Logger; public class EIDIssuingNationAttributeBuilder extends BaseAttributeBuilder { @@ -12,13 +18,37 @@ public class EIDIssuingNationAttributeBuilder extends BaseAttributeBuilder { public Attribute build(AuthenticationSession authSession) { String countryCode = "AT"; - if(authSession.getStorkAuthnRequest() != null) { - countryCode = authSession.getStorkAuthnRequest().getCitizenCountryCode(); + + + if (authSession.getStorkAuthnRequest() != null) { + countryCode = authSession.getStorkAuthnRequest() + .getCitizenCountryCode(); + } else { + + //TODO: replace with TSL lookup when TSL is ready! + X509Certificate certificate = authSession.getSignerCertificate(); + + if (certificate != null) { + try { + LdapName ln = new LdapName(certificate.getIssuerDN() + .getName()); + for (Rdn rdn : ln.getRdns()) { + if (rdn.getType().equalsIgnoreCase("C")) { + Logger.info("C is: " + rdn.getValue()); + countryCode = rdn.getValue().toString(); + break; + } + } + } catch (Exception e) { + Logger.error("Failed to extract country code from certificate", e); + } + } } + return buildStringAttribute(EID_ISSUING_NATION_FRIENDLY_NAME, EID_ISSUING_NATION_NAME, countryCode); } - + public Attribute buildEmpty() { return buildemptyAttribute(EID_ISSUING_NATION_FRIENDLY_NAME, EID_ISSUING_NATION_NAME); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDSectorForIDAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDSectorForIDAttributeBuilder.java index c91a87548..9b0c0a289 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDSectorForIDAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDSectorForIDAttributeBuilder.java @@ -12,7 +12,7 @@ public class EIDSectorForIDAttributeBuilder extends BaseAttributeBuilder { public Attribute build(AuthenticationSession authSession) { return buildStringAttribute(EID_SECTOR_FOR_IDENTIFIER_FRIENDLY_NAME, - EID_SECTOR_FOR_IDENTIFIER_NAME, authSession.getIdentityLink().getIdentificationType()); + EID_SECTOR_FOR_IDENTIFIER_NAME, authSession.getAssertionAuthData().getIdentificationType()); } public Attribute buildEmpty() { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/IAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/IAttributeBuilder.java index 96c12f413..3ed4e3870 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/IAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/IAttributeBuilder.java @@ -3,9 +3,10 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; import org.opensaml.saml2.core.Attribute; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; public interface IAttributeBuilder { public String getName(); - public Attribute build(AuthenticationSession authSession); + public Attribute build(AuthenticationSession authSession) throws PVP2Exception; public Attribute buildEmpty(); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateFullMandateAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateFullMandateAttributeBuilder.java new file mode 100644 index 000000000..9e51f97ae --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateFullMandateAttributeBuilder.java @@ -0,0 +1,48 @@ +package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; + +import java.io.IOException; + +import javax.xml.transform.TransformerException; + +import org.opensaml.saml2.core.Attribute; + +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.auth.validator.parep.ParepValidator; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; +import at.gv.egovernment.moa.id.protocols.pvp2x.utils.AttributeExtractor; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.DOMUtils; + +public class MandateFullMandateAttributeBuilder extends BaseAttributeBuilder { + + public String getName() { + return MANDATE_FULL_MANDATE_NAME; + } + + public Attribute build(AuthenticationSession authSession) + throws PVP2Exception { + if (authSession.getUseMandate()) { + if (authSession.getMandate() != null) { + String fullMandate; + try { + fullMandate = DOMUtils.serializeNode(authSession + .getMandate()); + return buildStringAttribute(MANDATE_FULL_MANDATE_FRIENDLY_NAME, + MANDATE_FULL_MANDATE_NAME, fullMandate); + } catch (TransformerException e) { + Logger.error("Failed to generate Full Mandate", e); + } catch (IOException e) { + Logger.error("Failed to generate Full Mandate", e); + } + } + } + return null; + + } + + public Attribute buildEmpty() { + return buildemptyAttribute(MANDATE_FULL_MANDATE_FRIENDLY_NAME, + MANDATE_FULL_MANDATE_NAME); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateLegalPersonFullNameAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateLegalPersonFullNameAttributeBuilder.java new file mode 100644 index 000000000..f52f5786d --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateLegalPersonFullNameAttributeBuilder.java @@ -0,0 +1,48 @@ +package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; + +import org.opensaml.saml2.core.Attribute; +import org.w3c.dom.Element; + +import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; +import at.gv.e_government.reference.namespace.persondata._20020228_.CorporateBodyType; +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NoMandateDataAvailableException; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; +import at.gv.egovernment.moa.id.util.MandateBuilder; +import at.gv.egovernment.moa.logging.Logger; + +public class MandateLegalPersonFullNameAttributeBuilder extends BaseAttributeBuilder { + + public String getName() { + return MANDATE_LEG_PER_FULL_NAME_NAME; + } + + public Attribute build(AuthenticationSession authSession) throws PVP2Exception { + if(authSession.getUseMandate()) { + Element mandate = authSession.getMandate(); + if(mandate == null) { + throw new NoMandateDataAvailableException(); + } + Mandate mandateObject = MandateBuilder.buildMandate(mandate); + if(mandateObject == null) { + throw new NoMandateDataAvailableException(); + } + CorporateBodyType corporation = mandateObject.getMandator().getCorporateBody(); + if(corporation == null) { + Logger.error("No corporation mandate"); + throw new NoMandateDataAvailableException(); + } + + return buildStringAttribute(MANDATE_LEG_PER_FULL_NAME_FRIENDLY_NAME, + MANDATE_LEG_PER_FULL_NAME_NAME, corporation.getFullName()); + } + return null; + + } + + public Attribute buildEmpty() { + return buildemptyAttribute(MANDATE_LEG_PER_FULL_NAME_FRIENDLY_NAME, + MANDATE_LEG_PER_FULL_NAME_NAME); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateLegalPersonSourcePinAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateLegalPersonSourcePinAttributeBuilder.java new file mode 100644 index 000000000..ac55c2347 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateLegalPersonSourcePinAttributeBuilder.java @@ -0,0 +1,61 @@ +package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; + +import org.opensaml.saml2.core.Attribute; +import org.w3c.dom.Element; + +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; +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NoMandateDataAvailableException; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; +import at.gv.egovernment.moa.id.util.MandateBuilder; +import at.gv.egovernment.moa.logging.Logger; + +public class MandateLegalPersonSourcePinAttributeBuilder extends BaseAttributeBuilder { + + public String getName() { + return MANDATE_LEG_PER_SOURCE_PIN_NAME; + } + + public Attribute build(AuthenticationSession authSession) throws PVP2Exception { + if(authSession.getUseMandate()) { + Element mandate = authSession.getMandate(); + if(mandate == null) { + throw new NoMandateDataAvailableException(); + } + Mandate mandateObject = MandateBuilder.buildMandate(mandate); + if(mandateObject == null) { + throw new NoMandateDataAvailableException(); + } + CorporateBodyType corporation = mandateObject.getMandator().getCorporateBody(); + if(corporation == null) { + Logger.error("No corporation mandate"); + throw new NoMandateDataAvailableException(); + } + IdentificationType id = null; + if(corporation.getIdentification().size() == 0) { + Logger.error("Failed to generate IdentificationType"); + throw new NoMandateDataAvailableException(); + } + id = corporation.getIdentification().get(0); + /*if(authSession.getBusinessService()) { + id = MandateBuilder.getWBPKIdentification(corporation); + } else { + id = MandateBuilder.getBPKIdentification(corporation); + }*/ + /*if(id == null) { + Logger.error("Failed to generate IdentificationType"); + throw new NoMandateDataAvailableException(); + }*/ + return buildStringAttribute(MANDATE_LEG_PER_SOURCE_PIN_FRIENDLY_NAME, + MANDATE_LEG_PER_SOURCE_PIN_NAME, id.getValue().getValue()); + } + return null; + + } + + public Attribute buildEmpty() { + return buildemptyAttribute(MANDATE_LEG_PER_SOURCE_PIN_FRIENDLY_NAME, MANDATE_LEG_PER_SOURCE_PIN_NAME); + } +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateLegalPersonSourcePinTypeAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateLegalPersonSourcePinTypeAttributeBuilder.java new file mode 100644 index 000000000..d5ebdea24 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateLegalPersonSourcePinTypeAttributeBuilder.java @@ -0,0 +1,64 @@ +package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; + +import org.opensaml.saml2.core.Attribute; +import org.w3c.dom.Element; + +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; +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NoMandateDataAvailableException; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; +import at.gv.egovernment.moa.id.util.MandateBuilder; +import at.gv.egovernment.moa.logging.Logger; + +public class MandateLegalPersonSourcePinTypeAttributeBuilder extends + BaseAttributeBuilder { + + public String getName() { + return MANDATE_LEG_PER_SOURCE_PIN_TYPE_NAME; + } + + public Attribute build(AuthenticationSession authSession) + throws PVP2Exception { + if (authSession.getUseMandate()) { + Element mandate = authSession.getMandate(); + if (mandate == null) { + throw new NoMandateDataAvailableException(); + } + Mandate mandateObject = MandateBuilder.buildMandate(mandate); + if (mandateObject == null) { + throw new NoMandateDataAvailableException(); + } + CorporateBodyType corporation = mandateObject.getMandator() + .getCorporateBody(); + if (corporation == null) { + Logger.error("No corporate mandate"); + throw new NoMandateDataAvailableException(); + } + IdentificationType id = null; + if(corporation.getIdentification().size() == 0) { + Logger.error("Failed to generate IdentificationType"); + throw new NoMandateDataAvailableException(); + } + id = corporation.getIdentification().get(0); + /*id = MandateBuilder.getBPKIdentification(corporate); + if (id == null) { + Logger.error("Failed to generate IdentificationType"); + throw new NoMandateDataAvailableException(); + }*/ + return buildStringAttribute( + MANDATE_LEG_PER_SOURCE_PIN_TYPE_FRIENDLY_NAME, + MANDATE_LEG_PER_SOURCE_PIN_TYPE_NAME, id.getType()); + } + return null; + + } + + public Attribute buildEmpty() { + return buildemptyAttribute( + MANDATE_LEG_PER_SOURCE_PIN_TYPE_FRIENDLY_NAME, + MANDATE_LEG_PER_SOURCE_PIN_TYPE_NAME); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonBPKAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonBPKAttributeBuilder.java new file mode 100644 index 000000000..b53b92aca --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonBPKAttributeBuilder.java @@ -0,0 +1,61 @@ +package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; + +import org.opensaml.saml2.core.Attribute; +import org.w3c.dom.Element; + +import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; +import at.gv.e_government.reference.namespace.persondata._20020228_.IdentificationType; +import at.gv.e_government.reference.namespace.persondata._20020228_.PhysicalPersonType; +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NoMandateDataAvailableException; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; +import at.gv.egovernment.moa.id.util.MandateBuilder; +import at.gv.egovernment.moa.logging.Logger; + +public class MandateNaturalPersonBPKAttributeBuilder extends BaseAttributeBuilder { + + public String getName() { + return MANDATE_NAT_PER_BPK_NAME; + } + + public Attribute build(AuthenticationSession authSession) throws PVP2Exception { + if(authSession.getUseMandate()) { + Element mandate = authSession.getMandate(); + if(mandate == null) { + throw new NoMandateDataAvailableException(); + } + Mandate mandateObject = MandateBuilder.buildMandate(mandate); + if(mandateObject == null) { + throw new NoMandateDataAvailableException(); + } + PhysicalPersonType physicalPerson = mandateObject.getMandator() + .getPhysicalPerson(); + if (physicalPerson == null) { + Logger.error("No physicalPerson mandate"); + throw new NoMandateDataAvailableException(); + } + IdentificationType id = null; + id = physicalPerson.getIdentification().get(0); + /*if(authSession.getBusinessService()) { + id = MandateBuilder.getWBPKIdentification(physicalPerson); + } else { + id = MandateBuilder.getBPKIdentification(physicalPerson); + }*/ + if(id == null) { + Logger.error("Failed to generate IdentificationType"); + throw new NoMandateDataAvailableException(); + } + return buildStringAttribute(MANDATE_NAT_PER_BPK_FRIENDLY_NAME, + MANDATE_NAT_PER_BPK_NAME, id.getValue().getValue()); + } + return null; + + } + + public Attribute buildEmpty() { + return buildemptyAttribute(MANDATE_NAT_PER_BPK_FRIENDLY_NAME, + MANDATE_NAT_PER_BPK_NAME); + } + + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonBirthDateAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonBirthDateAttributeBuilder.java new file mode 100644 index 000000000..eae3023db --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonBirthDateAttributeBuilder.java @@ -0,0 +1,71 @@ +package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; + +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.opensaml.saml2.core.Attribute; +import org.w3c.dom.Element; + +import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; +import at.gv.e_government.reference.namespace.persondata._20020228_.PhysicalPersonType; +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.InvalidDateFormatException; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NoMandateDataAvailableException; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; +import at.gv.egovernment.moa.id.util.MandateBuilder; +import at.gv.egovernment.moa.logging.Logger; + +public class MandateNaturalPersonBirthDateAttributeBuilder extends + BaseAttributeBuilder { + + public String getName() { + return MANDATE_NAT_PER_BIRTHDATE_NAME; + } + + public Attribute build(AuthenticationSession authSession) + throws PVP2Exception { + if (authSession.getUseMandate()) { + Element mandate = authSession.getMandate(); + if (mandate == null) { + throw new NoMandateDataAvailableException(); + } + Mandate mandateObject = MandateBuilder.buildMandate(mandate); + if (mandateObject == null) { + throw new NoMandateDataAvailableException(); + } + PhysicalPersonType physicalPerson = mandateObject.getMandator() + .getPhysicalPerson(); + if (physicalPerson == null) { + Logger.error("No physicalPerson mandate"); + throw new NoMandateDataAvailableException(); + } + + String dateOfBirth = physicalPerson.getDateOfBirth(); + try { + DateFormat mandateFormat = new SimpleDateFormat( + MandateBuilder.MANDATE_DATE_OF_BIRTH_FORMAT); + Date date = mandateFormat.parse(dateOfBirth); + DateFormat pvpDateFormat = new SimpleDateFormat( + MANDATE_NAT_PER_BIRTHDATE_FORMAT_PATTERN); + String dateString = pvpDateFormat.format(date); + + return buildStringAttribute( + MANDATE_NAT_PER_BIRTHDATE_FRIENDLY_NAME, + MANDATE_NAT_PER_BIRTHDATE_NAME, dateString); + } catch (ParseException e) { + e.printStackTrace(); + throw new InvalidDateFormatException(); + } + } + return null; + + } + + public Attribute buildEmpty() { + return buildemptyAttribute(MANDATE_NAT_PER_BIRTHDATE_FRIENDLY_NAME, + MANDATE_NAT_PER_BIRTHDATE_NAME); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonFamilyNameAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonFamilyNameAttributeBuilder.java new file mode 100644 index 000000000..38d540883 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonFamilyNameAttributeBuilder.java @@ -0,0 +1,58 @@ +package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; + +import java.util.Iterator; + +import org.opensaml.saml2.core.Attribute; +import org.w3c.dom.Element; + +import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; +import at.gv.e_government.reference.namespace.persondata._20020228_.PersonNameType.FamilyName; +import at.gv.e_government.reference.namespace.persondata._20020228_.PhysicalPersonType; +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NoMandateDataAvailableException; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; +import at.gv.egovernment.moa.id.util.MandateBuilder; +import at.gv.egovernment.moa.logging.Logger; + +public class MandateNaturalPersonFamilyNameAttributeBuilder extends BaseAttributeBuilder { + + public String getName() { + return MANDATE_NAT_PER_FAMILY_NAME_NAME; + } + + public Attribute build(AuthenticationSession authSession) throws PVP2Exception { + if(authSession.getUseMandate()) { + Element mandate = authSession.getMandate(); + if(mandate == null) { + throw new NoMandateDataAvailableException(); + } + Mandate mandateObject = MandateBuilder.buildMandate(mandate); + if(mandateObject == null) { + throw new NoMandateDataAvailableException(); + } + PhysicalPersonType physicalPerson = mandateObject.getMandator().getPhysicalPerson(); + if(physicalPerson == null) { + Logger.error("No physicalPerson mandate"); + throw new NoMandateDataAvailableException(); + } + + StringBuilder sb = new StringBuilder(); + Iterator<FamilyName> fNamesit = physicalPerson.getName().getFamilyName().iterator(); + + while(fNamesit.hasNext()) { + sb.append(" " + fNamesit.next().getValue()); + } + + return buildStringAttribute(MANDATE_NAT_PER_FAMILY_NAME_FRIENDLY_NAME, + MANDATE_NAT_PER_FAMILY_NAME_NAME, sb.toString()); + } + return null; + + } + + public Attribute buildEmpty() { + return buildemptyAttribute(MANDATE_NAT_PER_FAMILY_NAME_FRIENDLY_NAME, + MANDATE_NAT_PER_FAMILY_NAME_NAME); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonGivenNameAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonGivenNameAttributeBuilder.java new file mode 100644 index 000000000..a876f600b --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonGivenNameAttributeBuilder.java @@ -0,0 +1,57 @@ +package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; + +import java.util.Iterator; + +import org.opensaml.saml2.core.Attribute; +import org.w3c.dom.Element; + +import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; +import at.gv.e_government.reference.namespace.persondata._20020228_.PhysicalPersonType; +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NoMandateDataAvailableException; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; +import at.gv.egovernment.moa.id.util.MandateBuilder; +import at.gv.egovernment.moa.logging.Logger; + +public class MandateNaturalPersonGivenNameAttributeBuilder extends BaseAttributeBuilder { + + public String getName() { + return MANDATE_NAT_PER_GIVEN_NAME_NAME; + } + + public Attribute build(AuthenticationSession authSession) throws PVP2Exception { + if(authSession.getUseMandate()) { + Element mandate = authSession.getMandate(); + if(mandate == null) { + throw new NoMandateDataAvailableException(); + } + Mandate mandateObject = MandateBuilder.buildMandate(mandate); + if(mandateObject == null) { + throw new NoMandateDataAvailableException(); + } + PhysicalPersonType physicalPerson = mandateObject.getMandator().getPhysicalPerson(); + if(physicalPerson == null) { + Logger.error("No physicalPerson mandate"); + throw new NoMandateDataAvailableException(); + } + + StringBuilder sb = new StringBuilder(); + Iterator<String> gNamesit = physicalPerson.getName().getGivenName().iterator(); + + while(gNamesit.hasNext()) { + sb.append(" " + gNamesit.next()); + } + + return buildStringAttribute(MANDATE_NAT_PER_GIVEN_NAME_FRIENDLY_NAME, + MANDATE_NAT_PER_GIVEN_NAME_NAME, sb.toString()); + } + return null; + + } + + public Attribute buildEmpty() { + return buildemptyAttribute(MANDATE_NAT_PER_GIVEN_NAME_FRIENDLY_NAME, + MANDATE_NAT_PER_GIVEN_NAME_NAME); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateProfRepDescAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateProfRepDescAttributeBuilder.java new file mode 100644 index 000000000..6a066874a --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateProfRepDescAttributeBuilder.java @@ -0,0 +1,45 @@ +package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; + +import org.opensaml.saml2.core.Attribute; +import org.w3c.dom.Element; + +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.auth.validator.parep.ParepValidator; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NoMandateDataAvailableException; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; +import at.gv.egovernment.moa.id.protocols.pvp2x.utils.AttributeExtractor; + +public class MandateProfRepDescAttributeBuilder extends BaseAttributeBuilder { + + public String getName() { + return MANDATE_PROF_REP_DESC_NAME; + } + + public Attribute build(AuthenticationSession authSession) throws PVP2Exception { + if(authSession.getUseMandate()) { + Element mandate = authSession.getMandate(); + if(mandate == null) { + throw new NoMandateDataAvailableException(); + } + + String text = AttributeExtractor.extractSAMLAttributeOA( + ParepValidator.EXT_SAML_MANDATE_OIDTEXTUALDESCRIPTION, + authSession); + + if(text == null) { + return null; + } + + return buildStringAttribute(MANDATE_PROF_REP_DESC_FRIENDLY_NAME, + MANDATE_PROF_REP_DESC_NAME, text); + + } + return null; + + } + + public Attribute buildEmpty() { + return buildemptyAttribute(MANDATE_PROF_REP_DESC_FRIENDLY_NAME, + MANDATE_PROF_REP_DESC_NAME); + } +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateProfRepOIDAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateProfRepOIDAttributeBuilder.java new file mode 100644 index 000000000..ddc7f6671 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateProfRepOIDAttributeBuilder.java @@ -0,0 +1,46 @@ +package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; + +import org.opensaml.saml2.core.Attribute; +import org.w3c.dom.Element; + +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.auth.validator.parep.ParepValidator; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NoMandateDataAvailableException; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; +import at.gv.egovernment.moa.id.protocols.pvp2x.utils.AttributeExtractor; + +public class MandateProfRepOIDAttributeBuilder extends BaseAttributeBuilder { + + public String getName() { + return MANDATE_PROF_REP_OID_NAME; + } + + public Attribute build(AuthenticationSession authSession) throws PVP2Exception { + if(authSession.getUseMandate()) { + Element mandate = authSession.getMandate(); + if(mandate == null) { + throw new NoMandateDataAvailableException(); + } + + String oid = AttributeExtractor.extractSAMLAttributeOA( + ParepValidator.EXT_SAML_MANDATE_OID, + authSession); + + if(oid == null) { + return null; + } + + return buildStringAttribute(MANDATE_PROF_REP_OID_FRIENDLY_NAME, + MANDATE_PROF_REP_OID_NAME, oid); + + } + return null; + + } + + public Attribute buildEmpty() { + return buildemptyAttribute(MANDATE_PROF_REP_OID_FRIENDLY_NAME, + MANDATE_PROF_REP_OID_NAME); + } +} +
\ No newline at end of file diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateReferenceValueAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateReferenceValueAttributeBuilder.java new file mode 100644 index 000000000..8625eddeb --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateReferenceValueAttributeBuilder.java @@ -0,0 +1,40 @@ +package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; + +import org.opensaml.saml2.core.Attribute; +import org.w3c.dom.Element; + +import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NoMandateDataAvailableException; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; +import at.gv.egovernment.moa.id.util.MandateBuilder; + +public class MandateReferenceValueAttributeBuilder extends BaseAttributeBuilder { + + public String getName() { + return MANDATE_REFERENCE_VALUE_NAME; + } + + public Attribute build(AuthenticationSession authSession) throws PVP2Exception { + if(authSession.getUseMandate()) { + Element mandate = authSession.getMandate(); + if(mandate == null) { + throw new NoMandateDataAvailableException(); + } + Mandate mandateObject = MandateBuilder.buildMandate(mandate); + if(mandateObject == null) { + throw new NoMandateDataAvailableException(); + } + + return buildStringAttribute(MANDATE_REFERENCE_VALUE_FRIENDLY_NAME, + MANDATE_REFERENCE_VALUE_NAME, mandateObject.getMandateID()); + } + return null; + + } + + public Attribute buildEmpty() { + return buildemptyAttribute(MANDATE_REFERENCE_VALUE_FRIENDLY_NAME, + MANDATE_REFERENCE_VALUE_NAME); + } +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateTypeAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateTypeAttributeBuilder.java new file mode 100644 index 000000000..0064ed102 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateTypeAttributeBuilder.java @@ -0,0 +1,38 @@ +package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; + +import org.opensaml.saml2.core.Attribute; +import org.w3c.dom.Element; + +import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.ResponderErrorException; +import at.gv.egovernment.moa.id.util.MandateBuilder; + +public class MandateTypeAttributeBuilder extends BaseAttributeBuilder { + + public String getName() { + return MANDATE_TYPE_NAME; + } + + public Attribute build(AuthenticationSession authSession) throws ResponderErrorException { + if(authSession.getUseMandate()) { + Element mandate = authSession.getMandate(); + if(mandate == null) { + throw new ResponderErrorException("No mandate data available", null); + } + Mandate mandateObject = MandateBuilder.buildMandate(mandate); + if(mandateObject == null) { + throw new ResponderErrorException("No mandate data available", null); + } + + return buildStringAttribute(MANDATE_TYPE_FRIENDLY_NAME, MANDATE_TYPE_NAME, mandateObject.getAnnotation()); + } + return null; + + } + + public Attribute buildEmpty() { + return buildemptyAttribute(MANDATE_TYPE_FRIENDLY_NAME, MANDATE_TYPE_NAME); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/PVPConfiguration.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/PVPConfiguration.java index d38c900bc..c8059b2f9 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/PVPConfiguration.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/PVPConfiguration.java @@ -3,15 +3,11 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.config; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; -import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Properties; import java.util.Set; -import javax.xml.namespace.QName; - -import org.opensaml.saml2.common.Extensions; import org.opensaml.saml2.metadata.Company; import org.opensaml.saml2.metadata.ContactPerson; import org.opensaml.saml2.metadata.ContactPersonTypeEnumeration; @@ -24,15 +20,6 @@ import org.opensaml.saml2.metadata.OrganizationName; import org.opensaml.saml2.metadata.OrganizationURL; import org.opensaml.saml2.metadata.SurName; import org.opensaml.saml2.metadata.TelephoneNumber; -import org.opensaml.xml.Namespace; -import org.opensaml.xml.NamespaceManager; -import org.opensaml.xml.XMLObject; -import org.opensaml.xml.schema.XSBooleanValue; -import org.opensaml.xml.util.AttributeMap; -import org.opensaml.xml.util.IDIndex; -import org.opensaml.xml.validation.ValidationException; -import org.opensaml.xml.validation.Validator; -import org.w3c.dom.Element; import at.gv.egovernment.moa.id.config.ConfigurationProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.Digester; @@ -41,226 +28,266 @@ import at.gv.egovernment.moa.logging.Logger; public class PVPConfiguration { private static PVPConfiguration instance; - + public static PVPConfiguration getInstance() { - if(instance == null) { + if (instance == null) { instance = new PVPConfiguration(); } return instance; } + + public static final String PVP2_METADATA = "/pvp2/metadata"; + public static final String PVP2_REDIRECT = "/pvp2/redirect"; + public static final String PVP2_POST = "/pvp2/post"; public static final String PVP_CONFIG_FILE = "pvp2config.properties"; public static final String IDP_JAVAKEYSTORE = "idp.ks.file"; public static final String IDP_KEYALIAS = "idp.ks.alias"; public static final String IDP_KS_PASS = "idp.ks.kspassword"; public static final String IDP_KEY_PASS = "idp.ks.keypassword"; - + public static final String IDP_ISSUER_NAME = "idp.issuer.name"; - - public static final String METADATA_FILE = "md.file"; - + + public static final String METADATA_FILE = "md.dir"; + public static final String METADATA_EXTENSION = "md.ext"; + public static final String IDP_ENTITY = "idp.entityid"; public static final String IDP_ORG_NAME = "idp.org.name"; public static final String IDP_ORG_DISPNAME = "idp.org.dispname"; public static final String IDP_ORG_URL = "idp.org.url"; - - public static final String IDP_POST_SSO_SERVICE = "idp.sso.post"; - public static final String IDP_REDIRECT_SSO_SERVICE = "idp.sso.redirect"; - public static final String IDP_SOAP_RESOLVE_SERVICE = "idp.resolve.soap"; - + + public static final String IDP_PUBLIC_URL = "idp.public.url"; + public static final String IDP_TRUST_STORE = "idp.truststore"; public static final String SP_TARGET_PREFIX = "sp.target."; - + public static final String IDP_CONTACT_PREFIX = "idp.contact"; public static final String IDP_CONTACT_LIST = "idp.contact_list"; - + public static final String IDP_CONTACT_SURNAME = "surname"; public static final String IDP_CONTACT_GIVENNAME = "givenname"; public static final String IDP_CONTACT_MAIL = "mail"; public static final String IDP_CONTACT_TYPE = "type"; public static final String IDP_CONTACT_COMPANY = "company"; public static final String IDP_CONTACT_PHONE = "phone"; - - + Properties props = new Properties(); - + private PVPConfiguration() { try { - String fileName = System.getProperty(ConfigurationProvider.CONFIG_PROPERTY_NAME); + String fileName = System + .getProperty(ConfigurationProvider.CONFIG_PROPERTY_NAME); String pathName = (new File(fileName)).getParent(); String configFile = pathName + "/" + PVP_CONFIG_FILE; - + Logger.info("PVP Config file " + configFile); FileInputStream is = new FileInputStream(configFile); props.load(is); is.close(); - } catch(Exception e) { + } catch (Exception e) { e.printStackTrace(); } } + public String getIDPPublicPath() { + String publicPath = props.getProperty(IDP_PUBLIC_URL); + if(publicPath != null) { + if(publicPath.endsWith("/")) { + publicPath = publicPath.substring(0, publicPath.length()-2); + } + } + return publicPath; + } + public String getIDPSSOPostService() { - return props.getProperty(IDP_POST_SSO_SERVICE); + return getIDPPublicPath() + PVP2_POST; } - + public String getIDPSSORedirectService() { - return props.getProperty(IDP_REDIRECT_SSO_SERVICE); + return getIDPPublicPath() + PVP2_REDIRECT; } - public String getIDPResolveSOAPService() { - return props.getProperty(IDP_SOAP_RESOLVE_SERVICE); + public String getIDPSSOMetadataService() { + return getIDPPublicPath() + PVP2_METADATA; } - + public String getIDPKeyStoreFilename() { return props.getProperty(IDP_JAVAKEYSTORE); } - + public String getIDPKeyStorePassword() { return props.getProperty(IDP_KS_PASS); } - + public String getIDPKeyAlias() { return props.getProperty(IDP_KEYALIAS); } - + public String getIDPKeyPassword() { return props.getProperty(IDP_KEY_PASS); } - + public String getIDPIssuerName() { return props.getProperty(IDP_ISSUER_NAME); } - - public String getMetadataFile() { - return props.getProperty(METADATA_FILE); + + public List<String> getMetadataFiles() { + String filter = props.getProperty(METADATA_EXTENSION); + + if (filter == null) { + filter = ".mdxml"; + } + + List<String> files = new ArrayList<String>(); + + File[] faFiles = new File(props.getProperty(METADATA_FILE)).listFiles(); + for (File file : faFiles) { + if (!file.isDirectory()) { + if (file.getName().endsWith(filter)) { + files.add(file.getAbsolutePath()); + } + } + } + + return files; } - + public String getTargetForSP(String sp) { String spHash = Digester.toSHA1(sp.getBytes()); Logger.info("SHA hash for sp: " + sp + " => " + spHash); return props.getProperty(SP_TARGET_PREFIX + spHash); } - + public String getTrustEntityCertificate(String entityID) { String path = props.getProperty(IDP_TRUST_STORE); - if(path == null) { + if (path == null) { return null; } - - if(!path.endsWith("/")) { + + if (!path.endsWith("/")) { path = path + "/"; } - + String entityIDHash = Digester.toSHA1(entityID.getBytes()); - + return path + entityIDHash; } - + public List<ContactPerson> getIDPContacts() { List<ContactPerson> list = new ArrayList<ContactPerson>(); - + String contactList = props.getProperty(IDP_CONTACT_LIST); - - if(contactList != null) { - + + if (contactList != null) { + String[] contact_keys = contactList.split(","); - - for(int i = 0; i < contact_keys.length; i++) { - + + for (int i = 0; i < contact_keys.length; i++) { + String key = contact_keys[i]; - - ContactPerson person = SAML2Utils.createSAMLObject(ContactPerson.class); - - String type = props.getProperty(IDP_CONTACT_PREFIX + - "." + key + "." + IDP_CONTACT_TYPE); - - if(type == null) { - Logger.error("IDP Contact with key " + key + " has no type defined!"); + + ContactPerson person = SAML2Utils + .createSAMLObject(ContactPerson.class); + + String type = props.getProperty(IDP_CONTACT_PREFIX + "." + key + + "." + IDP_CONTACT_TYPE); + + if (type == null) { + Logger.error("IDP Contact with key " + key + + " has no type defined!"); break; } - + ContactPersonTypeEnumeration enumType = null; - - if(type.equals(ContactPersonTypeEnumeration.ADMINISTRATIVE.toString())) { + + if (type.equals(ContactPersonTypeEnumeration.ADMINISTRATIVE + .toString())) { enumType = ContactPersonTypeEnumeration.ADMINISTRATIVE; - } else if(type.equals(ContactPersonTypeEnumeration.BILLING.toString())){ + } else if (type.equals(ContactPersonTypeEnumeration.BILLING + .toString())) { enumType = ContactPersonTypeEnumeration.BILLING; - } else if(type.equals(ContactPersonTypeEnumeration.OTHER.toString())){ + } else if (type.equals(ContactPersonTypeEnumeration.OTHER + .toString())) { enumType = ContactPersonTypeEnumeration.OTHER; - }else if(type.equals(ContactPersonTypeEnumeration.SUPPORT.toString())){ + } else if (type.equals(ContactPersonTypeEnumeration.SUPPORT + .toString())) { enumType = ContactPersonTypeEnumeration.SUPPORT; - }else if(type.equals(ContactPersonTypeEnumeration.TECHNICAL.toString())){ + } else if (type.equals(ContactPersonTypeEnumeration.TECHNICAL + .toString())) { enumType = ContactPersonTypeEnumeration.TECHNICAL; } - - if(enumType == null) { - Logger.error("IDP Contact with key " + key + " has invalid type defined: " + - type); + + if (enumType == null) { + Logger.error("IDP Contact with key " + key + + " has invalid type defined: " + type); break; } - + person.setType(enumType); - - String givenName = props.getProperty(IDP_CONTACT_PREFIX + - "." + key + "." + IDP_CONTACT_GIVENNAME); - - if(givenName != null) { - GivenName name = SAML2Utils.createSAMLObject(GivenName.class); + + String givenName = props.getProperty(IDP_CONTACT_PREFIX + "." + + key + "." + IDP_CONTACT_GIVENNAME); + + if (givenName != null) { + GivenName name = SAML2Utils + .createSAMLObject(GivenName.class); name.setName(givenName); person.setGivenName(name); } - - String company = props.getProperty(IDP_CONTACT_PREFIX + - "." + key + "." + IDP_CONTACT_COMPANY); - - if(company != null) { + + String company = props.getProperty(IDP_CONTACT_PREFIX + "." + + key + "." + IDP_CONTACT_COMPANY); + + if (company != null) { Company comp = SAML2Utils.createSAMLObject(Company.class); comp.setName(company); person.setCompany(comp); } - - String surname = props.getProperty(IDP_CONTACT_PREFIX + - "." + key + "." + IDP_CONTACT_SURNAME); - - if(surname != null) { + + String surname = props.getProperty(IDP_CONTACT_PREFIX + "." + + key + "." + IDP_CONTACT_SURNAME); + + if (surname != null) { SurName name = SAML2Utils.createSAMLObject(SurName.class); name.setName(surname); person.setSurName(name); } - + Set<Object> keySet = props.keySet(); Iterator<Object> keyIt = keySet.iterator(); - - while(keyIt.hasNext()) { - + + while (keyIt.hasNext()) { + String currentKey = keyIt.next().toString(); - - if(currentKey.startsWith(IDP_CONTACT_PREFIX + - "." + key + "." + IDP_CONTACT_PHONE)) { + + if (currentKey.startsWith(IDP_CONTACT_PREFIX + "." + key + + "." + IDP_CONTACT_PHONE)) { String phone = props.getProperty(currentKey); - - if(phone != null) { - TelephoneNumber telePhone = SAML2Utils.createSAMLObject(TelephoneNumber.class); + + if (phone != null) { + TelephoneNumber telePhone = SAML2Utils + .createSAMLObject(TelephoneNumber.class); telePhone.setNumber(phone); person.getTelephoneNumbers().add(telePhone); } - } else if(currentKey.startsWith(IDP_CONTACT_PREFIX + - "." + key + "." + IDP_CONTACT_MAIL)) { + } else if (currentKey.startsWith(IDP_CONTACT_PREFIX + "." + + key + "." + IDP_CONTACT_MAIL)) { String mail = props.getProperty(currentKey); - - if(mail != null) { - EmailAddress mailAddress = SAML2Utils.createSAMLObject(EmailAddress.class); + + if (mail != null) { + EmailAddress mailAddress = SAML2Utils + .createSAMLObject(EmailAddress.class); mailAddress.setAddress(mail); person.getEmailAddresses().add(mailAddress); } } } list.add(person); - } + } } return list; } - + public Organization getIDPOrganisation() { Organization org = SAML2Utils.createSAMLObject(Organization.class); @@ -268,22 +295,22 @@ public class PVPConfiguration { String org_dispname = props.getProperty(IDP_ORG_DISPNAME); String org_url = props.getProperty(IDP_ORG_URL); - if(org_name == null || org_dispname == null || org_url == null) { + if (org_name == null || org_dispname == null || org_url == null) { return null; } - - OrganizationDisplayName dispName = SAML2Utils.createSAMLObject( - OrganizationDisplayName.class); + + OrganizationDisplayName dispName = SAML2Utils + .createSAMLObject(OrganizationDisplayName.class); dispName.setName(new LocalizedString(org_dispname, "de")); org.getDisplayNames().add(dispName); - - OrganizationName name = SAML2Utils.createSAMLObject( - OrganizationName.class); + + OrganizationName name = SAML2Utils + .createSAMLObject(OrganizationName.class); name.setName(new LocalizedString(org_name, "de")); org.getOrganizationNames().add(name); - - OrganizationURL url = SAML2Utils.createSAMLObject( - OrganizationURL.class); + + OrganizationURL url = SAML2Utils + .createSAMLObject(OrganizationURL.class); url.setURL(new LocalizedString(org_url, "de")); org.getURLs().add(url); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/BindingNotSupportedException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/BindingNotSupportedException.java new file mode 100644 index 000000000..51c4b7e72 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/BindingNotSupportedException.java @@ -0,0 +1,19 @@ +package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; + +import org.opensaml.saml2.core.StatusCode; + +public class BindingNotSupportedException extends PVP2Exception { + + public BindingNotSupportedException(String binding) { + super("pvp2.11", new Object[] {binding}); + this.statusCodeValue = StatusCode.UNSUPPORTED_BINDING_URI; + } + + /** + * + */ + private static final long serialVersionUID = -7227603941387879360L; + + + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/InvalidAssertionConsumerServiceException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/InvalidAssertionConsumerServiceException.java new file mode 100644 index 000000000..521b55580 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/InvalidAssertionConsumerServiceException.java @@ -0,0 +1,17 @@ +package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; + +import org.opensaml.saml2.core.StatusCode; + +public class InvalidAssertionConsumerServiceException extends PVP2Exception { + + public InvalidAssertionConsumerServiceException(int idx) { + super("pvp2.00", new Object[]{idx}); + this.statusCodeValue = StatusCode.REQUESTER_URI; + } + + /** + * + */ + private static final long serialVersionUID = 7861790149343943091L; + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/InvalidDateFormatException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/InvalidDateFormatException.java new file mode 100644 index 000000000..799d26ccb --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/InvalidDateFormatException.java @@ -0,0 +1,17 @@ +package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; + +import org.opensaml.saml2.core.StatusCode; + +public class InvalidDateFormatException extends PVP2Exception { + + public InvalidDateFormatException() { + super("pvp2.02", null); + this.statusCodeValue = StatusCode.REQUESTER_URI; + } + + /** + * + */ + private static final long serialVersionUID = -6867976890237846085L; + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/MandateAttributesNotHandleAbleException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/MandateAttributesNotHandleAbleException.java new file mode 100644 index 000000000..41a56639a --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/MandateAttributesNotHandleAbleException.java @@ -0,0 +1,17 @@ +package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; + +import org.opensaml.saml2.core.StatusCode; + +public class MandateAttributesNotHandleAbleException extends PVP2Exception { + + public MandateAttributesNotHandleAbleException() { + super("pvp2.03", null); + this.statusCodeValue = StatusCode.REQUESTER_URI; + } + + /** + * + */ + private static final long serialVersionUID = -1466424425852327722L; + +} 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 new file mode 100644 index 000000000..7dc9d5645 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/NameIDFormatNotSupportedException.java @@ -0,0 +1,14 @@ +package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; + +public class NameIDFormatNotSupportedException extends PVP2Exception { + + public NameIDFormatNotSupportedException(String nameIDFormat) { + super("pvp2.12", new Object[] {nameIDFormat}); + } + + /** + * + */ + private static final long serialVersionUID = -2270762519437873336L; + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/NoAuthContextException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/NoAuthContextException.java new file mode 100644 index 000000000..cd81de30f --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/NoAuthContextException.java @@ -0,0 +1,17 @@ +package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; + +import org.opensaml.saml2.core.StatusCode; + +public class NoAuthContextException extends PVP2Exception { + + /** + * + */ + private static final long serialVersionUID = 7040652043174500992L; + + public NoAuthContextException() { + super("pvp2.04", null); + this.statusCodeValue = StatusCode.REQUESTER_URI; + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/NoCredentialsException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/NoCredentialsException.java new file mode 100644 index 000000000..6af97301f --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/NoCredentialsException.java @@ -0,0 +1,21 @@ +package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; + +import org.opensaml.saml2.core.StatusCode; + +public class NoCredentialsException extends PVP2Exception { + + public static final String MOA_IDP_TARGET = "MOA-ID"; + + public NoCredentialsException(String target) { + super("pvp2.08", new Object[] {target}); + this.statusCodeValue = StatusCode.REQUEST_DENIED_URI; + } + + /** + * + */ + private static final long serialVersionUID = -9086515080686076313L; + + + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/NoMandateDataAvailableException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/NoMandateDataAvailableException.java new file mode 100644 index 000000000..d24905f68 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/NoMandateDataAvailableException.java @@ -0,0 +1,14 @@ +package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; + +public class NoMandateDataAvailableException extends PVP2Exception { + + public NoMandateDataAvailableException() { + super("pvp2.06", null); + } + + /** + * + */ + private static final long serialVersionUID = 4540420741715406351L; + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/NoMetadataInformationException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/NoMetadataInformationException.java new file mode 100644 index 000000000..c45820cfb --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/NoMetadataInformationException.java @@ -0,0 +1,17 @@ +package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; + +import org.opensaml.saml2.core.StatusCode; + +public class NoMetadataInformationException extends PVP2Exception { + + public NoMetadataInformationException() { + super("pvp2.15", null); + this.statusCodeValue = StatusCode.UNKNOWN_PRINCIPAL_URI; + } + + /** + * + */ + private static final long serialVersionUID = -4608068445208032193L; + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/PVP2EncodingException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/PVP2EncodingException.java new file mode 100644 index 000000000..a9bd8104e --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/PVP2EncodingException.java @@ -0,0 +1,18 @@ +package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; + +public class PVP2EncodingException extends PVP2Exception { + + public PVP2EncodingException() { + super("pvp2.01", null); + } + + public PVP2EncodingException(Throwable wrapped) { + super("pvp2.01", null, wrapped); + } + + /** + * + */ + private static final long serialVersionUID = -1348774139990071020L; + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/PVP2Exception.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/PVP2Exception.java new file mode 100644 index 000000000..990a76562 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/PVP2Exception.java @@ -0,0 +1,39 @@ +package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; + +import org.opensaml.saml2.core.StatusCode; + +import at.gv.egovernment.moa.id.MOAIDException; + +public abstract class PVP2Exception extends MOAIDException { + + protected String statusCodeValue = StatusCode.RESPONDER_URI; + protected String statusMessageValue = null; + + public PVP2Exception(String messageId, Object[] parameters, + Throwable wrapped) { + super(messageId, parameters, wrapped); + this.statusMessageValue = this.getMessage(); + } + + public PVP2Exception(String messageId, Object[] parameters) { + super(messageId, parameters); + this.statusMessageValue = this.getMessage(); + } + + + public String getStatusCodeValue() { + return (this.statusCodeValue); + } + + public String getStatusMessageValue() { + return (this.statusMessageValue); + } + + /** + * + */ + private static final long serialVersionUID = 7669537952484421069L; + + + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/QAANotSupportedException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/QAANotSupportedException.java new file mode 100644 index 000000000..be22be859 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/QAANotSupportedException.java @@ -0,0 +1,18 @@ +package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; + +import org.opensaml.saml2.core.StatusCode; + + +public class QAANotSupportedException extends PVP2Exception { + + public QAANotSupportedException(String qaa) { + super("pvp2.05", new Object[] {qaa}); + this.statusCodeValue = StatusCode.REQUESTER_URI; + } + + /** + * + */ + private static final long serialVersionUID = -3964192953884089323L; + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/RequestDeniedException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/RequestDeniedException.java new file mode 100644 index 000000000..61c41d82b --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/RequestDeniedException.java @@ -0,0 +1,17 @@ +package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; + +import org.opensaml.saml2.core.StatusCode; + +public class RequestDeniedException extends PVP2Exception { + + public RequestDeniedException() { + super("pvp2.14", null); + this.statusCodeValue = StatusCode.REQUEST_DENIED_URI; + } + + /** + * + */ + private static final long serialVersionUID = 4415896615794730553L; + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/ResponderErrorException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/ResponderErrorException.java new file mode 100644 index 000000000..a24320cbc --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/ResponderErrorException.java @@ -0,0 +1,22 @@ +package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; + +import org.opensaml.saml2.core.StatusCode; + +public class ResponderErrorException extends PVP2Exception { + + /** + * + */ + private static final long serialVersionUID = -425416760138285446L; + + public ResponderErrorException(String messageId, Object[] parameters, + Throwable wrapped) { + super(messageId, parameters, wrapped); + this.statusCodeValue = StatusCode.RESPONDER_URI; + } + + public ResponderErrorException(String messageId, Object[] parameters) { + super(messageId, parameters); + this.statusCodeValue = StatusCode.RESPONDER_URI; + } +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/SAMLRequestNotSignedException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/SAMLRequestNotSignedException.java new file mode 100644 index 000000000..e0f576205 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/SAMLRequestNotSignedException.java @@ -0,0 +1,22 @@ +package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; + +import org.opensaml.saml2.core.StatusCode; + +public class SAMLRequestNotSignedException extends PVP2Exception { + + public SAMLRequestNotSignedException() { + super("pvp2.07", null); + this.statusCodeValue = StatusCode.REQUESTER_URI; + } + + public SAMLRequestNotSignedException(Throwable e) { + super("pvp2.07", null, e); + this.statusCodeValue = StatusCode.REQUESTER_URI; + } + + /** + * + */ + private static final long serialVersionUID = 1L; + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/SAMLRequestNotSupported.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/SAMLRequestNotSupported.java new file mode 100644 index 000000000..029470b94 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/SAMLRequestNotSupported.java @@ -0,0 +1,18 @@ +package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; + +import org.opensaml.saml2.core.StatusCode; + + +public class SAMLRequestNotSupported extends PVP2Exception { + + public SAMLRequestNotSupported() { + super("pvp2.09", null); + this.statusCodeValue = StatusCode.REQUEST_UNSUPPORTED_URI; + } + + /** + * + */ + private static final long serialVersionUID = 1244883178458802767L; + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/UnprovideableAttributeException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/UnprovideableAttributeException.java new file mode 100644 index 000000000..0a91cc61a --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/UnprovideableAttributeException.java @@ -0,0 +1,15 @@ +package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; + +import org.opensaml.saml2.core.StatusCode; + +public class UnprovideableAttributeException extends PVP2Exception { + /** + * + */ + private static final long serialVersionUID = 3972197758163647157L; + + public UnprovideableAttributeException(String attributeName) { + super("pvp2.10", new Object[] {attributeName}); + this.statusCodeValue = StatusCode.UNKNOWN_ATTR_PROFILE_URI; + } +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/MOAMetadataProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/MOAMetadataProvider.java index 71de16a97..b38b862ef 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/MOAMetadataProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/MOAMetadataProvider.java @@ -1,6 +1,7 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.metadata; import java.io.File; +import java.util.Iterator; import java.util.List; import javax.xml.namespace.QName; @@ -8,6 +9,7 @@ import javax.xml.namespace.QName; import org.opensaml.saml2.metadata.EntitiesDescriptor; import org.opensaml.saml2.metadata.EntityDescriptor; import org.opensaml.saml2.metadata.RoleDescriptor; +import org.opensaml.saml2.metadata.provider.ChainingMetadataProvider; import org.opensaml.saml2.metadata.provider.FilesystemMetadataProvider; import org.opensaml.saml2.metadata.provider.MetadataFilter; import org.opensaml.saml2.metadata.provider.MetadataProvider; @@ -17,20 +19,30 @@ import org.opensaml.xml.parse.BasicParserPool; import at.gv.egovernment.moa.id.protocols.pvp2x.config.PVPConfiguration; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.MetadataSignatureFilter; +import at.gv.egovernment.moa.logging.Logger; public class MOAMetadataProvider implements MetadataProvider { MetadataProvider internalProvider; public MOAMetadataProvider() throws MetadataProviderException { - FilesystemMetadataProvider fsProvider = new FilesystemMetadataProvider( - new File(PVPConfiguration.getInstance().getMetadataFile())); - fsProvider.setParserPool(new BasicParserPool()); - internalProvider = fsProvider; - internalProvider.setRequireValidMetadata(true); - MetadataFilter filter = new MetadataSignatureFilter(); - internalProvider.setMetadataFilter(filter); - fsProvider.initialize(); + ChainingMetadataProvider chainProvider = new ChainingMetadataProvider(); + Logger.info("Loading metadata"); + List<String> files = PVPConfiguration.getInstance().getMetadataFiles(); + Iterator<String> fileIt = files.iterator(); + while (fileIt.hasNext()) { + String file = fileIt.next(); + Logger.info("Loading metadata file: " + file); + FilesystemMetadataProvider fsProvider = new FilesystemMetadataProvider( + new File(file)); + fsProvider.setParserPool(new BasicParserPool()); + fsProvider.setRequireValidMetadata(true); + MetadataFilter filter = new MetadataSignatureFilter(); + fsProvider.setMetadataFilter(filter); + chainProvider.addMetadataProvider(fsProvider); + fsProvider.initialize(); + } + internalProvider = chainProvider; } public boolean requireValidMetadata() { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/ArtifactResolution.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/ArtifactResolution.java index 3d2bd33b0..c18296383 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/ArtifactResolution.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/ArtifactResolution.java @@ -8,9 +8,13 @@ import org.opensaml.common.binding.artifact.SAMLArtifactMap.SAMLArtifactMapEntry import org.opensaml.saml2.core.ArtifactResolve; import org.opensaml.saml2.core.ArtifactResponse; +import at.gv.egovernment.moa.id.MOAIDException; import at.gv.egovernment.moa.id.protocols.pvp2x.PVPAssertionStorage; import at.gv.egovernment.moa.id.protocols.pvp2x.binding.MOARequest; +import at.gv.egovernment.moa.id.protocols.pvp2x.binding.SoapBinding; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.RequestDeniedException; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; +import at.gv.egovernment.moa.logging.Logger; public class ArtifactResolution implements IRequestHandler { @@ -19,24 +23,33 @@ public class ArtifactResolution implements IRequestHandler { } public void process(MOARequest obj, HttpServletRequest req, - HttpServletResponse resp) { - if(!handleObject(obj)) { - // TODO: throw exception - return; + HttpServletResponse resp) throws MOAIDException { + if (!handleObject(obj)) { + throw new MOAIDException("pvp2.13", null); } - - ArtifactResolve artifactResolve = (ArtifactResolve)obj.getSamlRequest(); + + ArtifactResolve artifactResolve = (ArtifactResolve) obj + .getSamlRequest(); String artifactID = artifactResolve.getArtifact().getArtifact(); - + PVPAssertionStorage pvpAssertion = PVPAssertionStorage.getInstance(); - if(!pvpAssertion.contains(artifactID)) { - // TODO: send not found ... + + if (!pvpAssertion.contains(artifactID)) { + throw new RequestDeniedException(); } else { - SAMLArtifactMapEntry assertion = pvpAssertion.get(artifactID); - ArtifactResponse response = SAML2Utils.createSAMLObject(ArtifactResponse.class); - response.setMessage(assertion.getSamlMessage()); - response.setIssueInstant(new DateTime()); + try { + SAMLArtifactMapEntry assertion = pvpAssertion.get(artifactID); + ArtifactResponse response = SAML2Utils + .createSAMLObject(ArtifactResponse.class); + response.setMessage(assertion.getSamlMessage()); + response.setIssueInstant(new DateTime()); + SoapBinding encoder = new SoapBinding(); + encoder.encodeRespone(req, resp, response, null); + } catch (Exception e) { + Logger.error("Failed to resolve artifact", e); + } } + } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/AuthnRequestHandler.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/AuthnRequestHandler.java index 86e941db7..db41bf389 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 @@ -1,44 +1,37 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.requestHandler; -import java.util.Iterator; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.joda.time.DateTime; import org.opensaml.common.xml.SAMLConstants; -import org.opensaml.saml2.core.ArtifactResponse; import org.opensaml.saml2.core.Assertion; -import org.opensaml.saml2.core.Attribute; -import org.opensaml.saml2.core.AttributeStatement; -import org.opensaml.saml2.core.AuthnContext; -import org.opensaml.saml2.core.AuthnContextClassRef; import org.opensaml.saml2.core.AuthnRequest; -import org.opensaml.saml2.core.AuthnStatement; import org.opensaml.saml2.core.Issuer; import org.opensaml.saml2.core.NameID; -import org.opensaml.saml2.core.Subject; -import org.opensaml.saml2.metadata.AttributeConsumingService; -import org.opensaml.saml2.metadata.RequestedAttribute; +import org.opensaml.saml2.core.Response; +import org.opensaml.saml2.metadata.AssertionConsumerService; +import org.opensaml.saml2.metadata.EntityDescriptor; import org.opensaml.saml2.metadata.SPSSODescriptor; import org.opensaml.ws.message.encoder.MessageEncodingException; import org.opensaml.xml.security.SecurityException; import at.gv.egovernment.moa.id.MOAIDException; -import at.gv.egovernment.moa.id.auth.AuthenticationServer; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.data.AuthenticationData; import at.gv.egovernment.moa.id.moduls.AuthenticationManager; +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; 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.builder.PVPAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.binding.RedirectBinding; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.assertion.PVP2AssertionBuilder; import at.gv.egovernment.moa.id.protocols.pvp2x.config.PVPConfiguration; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.BindingNotSupportedException; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.InvalidAssertionConsumerServiceException; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; +import at.gv.egovernment.moa.logging.Logger; -public class AuthnRequestHandler implements IRequestHandler { +public class AuthnRequestHandler implements IRequestHandler, PVPConstants { public boolean handleObject(MOARequest obj) { return (obj.getSamlRequest() instanceof AuthnRequest); @@ -46,117 +39,77 @@ public class AuthnRequestHandler implements IRequestHandler { public void process(MOARequest obj, HttpServletRequest req, HttpServletResponse resp) throws MOAIDException { - if(!handleObject(obj)) { - throw new MOAIDException("INVALID HANDLER SELECETED", null); + if (!handleObject(obj)) { + throw new MOAIDException("pvp2.13", null); } - - AuthnRequest authnRequest = (AuthnRequest)obj.getSamlRequest(); - - Assertion assertion = SAML2Utils.createSAMLObject(Assertion.class); - AuthnContextClassRef authnContextClassRef = SAML2Utils.createSAMLObject(AuthnContextClassRef.class); - authnContextClassRef.setAuthnContextClassRef(AuthnContext.SMARTCARD_PKI_AUTHN_CTX); - - AuthnContext authnContext = SAML2Utils.createSAMLObject(AuthnContext.class); - authnContext.setAuthnContextClassRef(authnContextClassRef); - - AuthnStatement authnStatement = SAML2Utils.createSAMLObject(AuthnStatement.class); - - authnStatement.setAuthnInstant(new DateTime()); - authnStatement.setAuthnContext(authnContext); - - assertion.getAuthnStatements().add(authnStatement); - - SPSSODescriptor spSSODescriptor = obj.getEntityMetadata(). - getSPSSODescriptor(SAMLConstants.SAML20P_NS); - - AttributeConsumingService attributeConsumingService = - spSSODescriptor.getAttributeConsumingServices().iterator().next(); - + AuthnRequest authnRequest = (AuthnRequest) obj.getSamlRequest(); + EntityDescriptor peerEntity = obj.getEntityMetadata(); + AuthenticationManager authmanager = AuthenticationManager.getInstance(); AuthenticationSession authSession =authmanager.getAuthenticationSession(req.getSession()); - AttributeStatement attributeStatement = SAML2Utils.createSAMLObject(AttributeStatement.class); - - Iterator<RequestedAttribute> it = attributeConsumingService.getRequestAttributes().iterator(); - while(it.hasNext()) { - RequestedAttribute reqAttribut = it.next(); - Attribute attr = PVPAttributeBuilder.buildAttribute(reqAttribut.getName(), authSession); - if(attr == null) { - if(reqAttribut.isRequired()) { - throw new MOAIDException("Cannot provide requested attribute " + reqAttribut.getName(), null); - } - } else { - attributeStatement.getAttributes().add(attr); - } - } - - if(attributeStatement.getAttributes().size() > 0) { - assertion.getAttributeStatements().add(attributeStatement); - } + // authSession.getM - Subject subject = SAML2Utils.createSAMLObject(Subject.class); - NameID subjectNameID = SAML2Utils.createSAMLObject(NameID.class); - subjectNameID.setFormat(NameID.PERSISTENT); + Assertion assertion = PVP2AssertionBuilder.buildAssertion(authnRequest, authSession, peerEntity); + + Response authResponse = SAML2Utils.createSAMLObject(Response.class); - - //TL: AuthData generation is moved to Assertion generation. - - //TODO: LOAD oaParam from request and not from MOASession in case of SSO - OAAuthParameter oaParam = AuthConfigurationProvider.getInstance() - .getOnlineApplicationParameter(authSession.getPublicOAURLPrefix()); - - AuthenticationData authData = AuthenticationServer.buildAuthenticationData(authSession, - oaParam, - authSession.getTarget()); - - //TL: getIdentificationValue holds the baseID --> change to pBK - //subjectNameID.setValue(authData.getIdentificationValue()); - if (authSession.getBusinessService()) - subjectNameID.setValue(authData.getWBPK()); - else - subjectNameID.setValue(authData.getBPK()); - - subject.setNameID(subjectNameID); - - //assertion.getAttributeStatements().add(CitizenTokenBuilder.buildCitizenToken(obj, authSession)); - - Issuer issuer = SAML2Utils.createSAMLObject(Issuer.class); - issuer.setValue(PVPConfiguration.getInstance().getIDPIssuerName()); - issuer.setFormat(NameID.ENTITY); - assertion.setIssuer(issuer); - assertion.setSubject(subject); - - ArtifactResponse authResponse = SAML2Utils.createSAMLObject(ArtifactResponse.class); - Issuer nissuer = SAML2Utils.createSAMLObject(Issuer.class); nissuer.setValue(PVPConfiguration.getInstance().getIDPIssuerName()); nissuer.setFormat(NameID.ENTITY); authResponse.setIssuer(nissuer); authResponse.setInResponseTo(authnRequest.getID()); - authResponse.setMessage(assertion); + authResponse.getAssertions().add(assertion); authResponse.setStatus(SAML2Utils.getSuccessStatus()); - + Integer aIdx = authnRequest.getAssertionConsumerServiceIndex(); int idx = 0; - - if(aIdx != null) { + + if (aIdx != null) { idx = aIdx.intValue(); } - - String oaURL = spSSODescriptor. - getAssertionConsumerServices().get(idx).getLocation(); - - IEncoder binding = new PostBinding(); + SPSSODescriptor spSSODescriptor = peerEntity + .getSPSSODescriptor(SAMLConstants.SAML20P_NS); + + AssertionConsumerService consumerService = spSSODescriptor + .getAssertionConsumerServices().get(idx); + + if (consumerService == null) { + throw new InvalidAssertionConsumerServiceException(idx); + } + String oaURL = consumerService.getLocation(); + + IEncoder binding = null; + + if (consumerService.getBinding().equals( + SAMLConstants.SAML2_REDIRECT_BINDING_URI)) { + binding = new RedirectBinding(); + } else if (consumerService.getBinding().equals( + SAMLConstants.SAML2_ARTIFACT_BINDING_URI)) { + // TODO: not supported YET!! + binding = new ArtifactBinding(); + } else if (consumerService.getBinding().equals( + SAMLConstants.SAML2_POST_BINDING_URI)) { + binding = new PostBinding(); + } + + if (binding == null) { + throw new BindingNotSupportedException(consumerService.getBinding()); + } + try { binding.encodeRespone(req, resp, authResponse, oaURL); + // TODO add remoteSessionID to AuthSession ExternalPVPSessionStore } catch (MessageEncodingException e) { + Logger.error("Message Encoding exception", e); + throw new MOAIDException("pvp2.01", null, e); } catch (SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + Logger.error("Security exception", e); + throw new MOAIDException("pvp2.01", null, e); } } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/RequestManager.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/RequestManager.java index 0e5fa9b1e..9121f7558 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/RequestManager.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/RequestManager.java @@ -8,8 +8,8 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import at.gv.egovernment.moa.id.MOAIDException; -import at.gv.egovernment.moa.id.protocols.pvp2x.SAMLRequestNotSupported; import at.gv.egovernment.moa.id.protocols.pvp2x.binding.MOARequest; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.SAMLRequestNotSupported; public class RequestManager { @@ -27,6 +27,7 @@ public class RequestManager { private RequestManager() { handler = new ArrayList<IRequestHandler>(); handler.add(new AuthnRequestHandler()); + handler.add(new ArtifactResolution()); } public void handle(MOARequest obj, HttpServletRequest req, HttpServletResponse resp) @@ -41,6 +42,6 @@ public class RequestManager { } // not handled - throw new SAMLRequestNotSupported("NOTSUPPORTED", null); + throw new SAMLRequestNotSupported(); } } 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 5f9f4d63b..4a1cd45da 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 @@ -1,5 +1,6 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.signer; +import iaik.pkcs.pkcs12.PKCS12; import iaik.x509.X509Certificate; import java.io.File; @@ -22,35 +23,30 @@ import org.opensaml.xml.signature.SignatureConstants; 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; +import at.gv.egovernment.moa.util.KeyStoreUtils; public class CredentialProvider { - public static Credential getIDPSigningCredential() throws CredentialsNotAvailableException { + public static Credential getIDPSigningCredential() + throws CredentialsNotAvailableException { KeyStore keyStore; PVPConfiguration config = PVPConfiguration.getInstance(); try { - keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); + keyStore = KeyStoreUtils.loadKeyStore(config.getIDPKeyStoreFilename(), + config.getIDPKeyStorePassword()); - FileInputStream inputStream = new FileInputStream( - config.getIDPKeyStoreFilename()); - keyStore.load(inputStream, config.getIDPKeyStorePassword().toCharArray()); - inputStream.close(); + KeyStoreX509CredentialAdapter credentials = new KeyStoreX509CredentialAdapter( + keyStore, config.getIDPKeyAlias(), config + .getIDPKeyPassword().toCharArray()); - KeyStoreX509CredentialAdapter credentials = new KeyStoreX509CredentialAdapter(keyStore, config.getIDPKeyAlias(), - config.getIDPKeyPassword().toCharArray()); - //PrivateKey key = (PrivateKey) keyStore.getKey(config.getIDPKeyAlias(), - // config.getIDPKeyPassword().toCharArray()); - //Certificate cert = keyStore.getCertificate(config.getIDPKeyAlias()); - //credentials.setPublicKey(cert.getPublicKey()); - //credentials.setPrivateKey(key); credentials.setUsageType(UsageType.SIGNING); return credentials; - } catch(Exception e) { + } catch (Exception e) { Logger.error("Failed to generate IDP Signing credentials"); e.printStackTrace(); throw new CredentialsNotAvailableException(e.getMessage(), null); } } - + public static Signature getIDPSignature(Credential credentials) { Signature signer = SAML2Utils.createSAMLObject(Signature.class); signer.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256); @@ -58,10 +54,12 @@ public class CredentialProvider { signer.setSigningCredential(credentials); return signer; } - - public static Credential getSPTrustedCredential(String entityID) throws CredentialsNotAvailableException { - String filename = PVPConfiguration.getInstance().getTrustEntityCertificate(entityID); - + + public static Credential getSPTrustedCredential(String entityID) + throws CredentialsNotAvailableException { + String filename = PVPConfiguration.getInstance() + .getTrustEntityCertificate(entityID); + iaik.x509.X509Certificate cert; try { cert = new X509Certificate(new FileInputStream(new File(filename))); @@ -75,37 +73,33 @@ public class CredentialProvider { e.printStackTrace(); throw new CredentialsNotAvailableException(e.getMessage(), null); } - + BasicX509Credential credential = new BasicX509Credential(); credential.setEntityId(entityID); credential.setUsageType(UsageType.SIGNING); credential.setPublicKey(cert.getPublicKey()); - - return credential; - } - - public static Credential getTrustedCredential() throws CredentialsNotAvailableException { - String filename = PVPConfiguration.getInstance().getTrustEntityCertificate("sp.crt"); - - iaik.x509.X509Certificate cert; - try { - cert = new X509Certificate(new FileInputStream(new File(filename))); - } catch (CertificateException e) { - e.printStackTrace(); - throw new CredentialsNotAvailableException(e.getMessage(), null); - } catch (FileNotFoundException e) { - e.printStackTrace(); - throw new CredentialsNotAvailableException(e.getMessage(), null); - } catch (IOException e) { - e.printStackTrace(); - throw new CredentialsNotAvailableException(e.getMessage(), null); - } - - BasicX509Credential credential = new BasicX509Credential(); - credential.setEntityId("sp.crt"); - credential.setUsageType(UsageType.SIGNING); - credential.setPublicKey(cert.getPublicKey()); - + return credential; } + /* + * public static Credential getTrustedCredential() throws + * CredentialsNotAvailableException { String filename = + * PVPConfiguration.getInstance().getTrustEntityCertificate("sp.crt"); + * + * iaik.x509.X509Certificate cert; try { cert = new X509Certificate(new + * FileInputStream(new File(filename))); } catch (CertificateException e) { + * e.printStackTrace(); throw new + * CredentialsNotAvailableException(e.getMessage(), null); } catch + * (FileNotFoundException e) { e.printStackTrace(); throw new + * CredentialsNotAvailableException(e.getMessage(), null); } catch + * (IOException e) { e.printStackTrace(); throw new + * CredentialsNotAvailableException(e.getMessage(), null); } + * + * BasicX509Credential credential = new BasicX509Credential(); + * credential.setEntityId("sp.crt"); + * credential.setUsageType(UsageType.SIGNING); + * credential.setPublicKey(cert.getPublicKey()); + * + * return credential; } + */ } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/utils/AttributeExtractor.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/utils/AttributeExtractor.java new file mode 100644 index 000000000..a59fc17c5 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/utils/AttributeExtractor.java @@ -0,0 +1,66 @@ +package at.gv.egovernment.moa.id.protocols.pvp2x.utils; + +import java.util.Iterator; +import java.util.List; + +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.auth.data.ExtendedSAMLAttribute; +import at.gv.egovernment.moa.id.auth.validator.parep.ParepValidator; + +public class AttributeExtractor { + + public static String extractSAMLAttributeOA(String name, + AuthenticationSession authSession) { + List extAttributes = authSession.getExtendedSAMLAttributesOA(); + if(extAttributes == null) { + return null; + } + Iterator extAttributesIt = extAttributes.iterator(); + String value = null; + while(extAttributesIt.hasNext()) { + Object attr = extAttributesIt.next(); + if(attr instanceof ExtendedSAMLAttribute) { + ExtendedSAMLAttribute extAttribute = (ExtendedSAMLAttribute) attr; + if(extAttribute.getName().equals(name)) { + if(extAttribute.getValue() instanceof String) { + return extAttribute.getValue().toString(); + } + break; + } + } + } + return null; + } + + public static String extractSAMLAttributeAUTH(String name, + AuthenticationSession authSession) { + List extAttributes = authSession.getExtendedSAMLAttributesAUTH(); + if(extAttributes == null) { + return null; + } + Iterator extAttributesIt = extAttributes.iterator(); + String value = null; + while(extAttributesIt.hasNext()) { + Object attr = extAttributesIt.next(); + if(attr instanceof ExtendedSAMLAttribute) { + ExtendedSAMLAttribute extAttribute = (ExtendedSAMLAttribute) attr; + if(extAttribute.getName().equals(name)) { + if(extAttribute.getValue() instanceof String) { + return extAttribute.getValue().toString(); + } + break; + } + } + } + return null; + } + + public static String extractSAMLAttributeBOTH(String name, + AuthenticationSession authSession) { + String value = extractSAMLAttributeOA(name, authSession); + if(value == null) { + value = extractSAMLAttributeAUTH(name, authSession); + } + return value; + } +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/utils/CheckMandateAttributes.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/utils/CheckMandateAttributes.java new file mode 100644 index 000000000..66d0b1d46 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/utils/CheckMandateAttributes.java @@ -0,0 +1,47 @@ +package at.gv.egovernment.moa.id.protocols.pvp2x.utils; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.opensaml.saml2.metadata.AttributeConsumingService; +import org.opensaml.saml2.metadata.RequestedAttribute; + +import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; + +public class CheckMandateAttributes implements PVPConstants { + private static List<String> minMandateAttributes; + + static { + minMandateAttributes = new ArrayList<String>(); + minMandateAttributes.add(MANDATE_TYPE_NAME); + + minMandateAttributes.add(MANDATE_LEG_PER_FULL_NAME_NAME); + minMandateAttributes.add(MANDATE_LEG_PER_SOURCE_PIN_NAME); + minMandateAttributes.add(MANDATE_LEG_PER_SOURCE_PIN_TYPE_NAME); + + minMandateAttributes.add(MANDATE_NAT_PER_BIRTHDATE_NAME); + minMandateAttributes.add(MANDATE_NAT_PER_GIVEN_NAME_NAME); + minMandateAttributes.add(MANDATE_NAT_PER_BPK_NAME); + minMandateAttributes.add(MANDATE_NAT_PER_FAMILY_NAME_NAME); + + minMandateAttributes.add(MANDATE_PROF_REP_OID_NAME); + minMandateAttributes.add(MANDATE_PROF_REP_DESC_NAME); + minMandateAttributes.add(MANDATE_REFERENCE_VALUE_NAME); + } + + public static boolean canHandleMandate(AttributeConsumingService attributeConsumer) { + List<String> attrList = new ArrayList<String>(minMandateAttributes); + Iterator<RequestedAttribute> attrIt = attributeConsumer.getRequestAttributes().iterator(); + + while(attrIt.hasNext()) { + RequestedAttribute reqAttr = attrIt.next(); + + if(attrList.contains(reqAttr.getName())) { + attrList.remove(reqAttr.getName()); + } + } + + return attrList.isEmpty(); + } +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/utils/SAML2Utils.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/utils/SAML2Utils.java index 0fa5a7193..d6ac121b1 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/utils/SAML2Utils.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/utils/SAML2Utils.java @@ -1,6 +1,7 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.utils; import java.io.IOException; +import java.security.NoSuchAlgorithmException; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilder; @@ -9,6 +10,7 @@ import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import org.opensaml.Configuration; +import org.opensaml.common.impl.SecureRandomIdentifierGenerator; import org.opensaml.saml2.core.Status; import org.opensaml.saml2.core.StatusCode; import org.opensaml.xml.XMLObject; @@ -17,6 +19,8 @@ import org.opensaml.xml.io.Marshaller; import org.opensaml.xml.io.MarshallingException; import org.w3c.dom.Document; +import eu.stork.vidp.messages.common.STORKBootstrap; + public class SAML2Utils { public static <T> T createSAMLObject(final Class<T> clazz) { @@ -36,6 +40,12 @@ public class SAML2Utils { } } + public static String getSecureIdentifier() { + return idGenerator.generateIdentifier(); + } + + private static SecureRandomIdentifierGenerator idGenerator; + private static DocumentBuilder builder; static { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); @@ -46,6 +56,11 @@ public class SAML2Utils { // TODO Auto-generated catch block e.printStackTrace(); } + try { + idGenerator = new SecureRandomIdentifierGenerator(); + } catch(NoSuchAlgorithmException e) { + e.printStackTrace(); + } } public static Document asDOMDocument(XMLObject object) throws IOException, diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/SAMLSignatureValidator.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/SAMLSignatureValidator.java index df0fec001..db1241e6f 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/SAMLSignatureValidator.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/SAMLSignatureValidator.java @@ -6,15 +6,14 @@ import org.opensaml.security.SAMLSignatureProfileValidator; import org.opensaml.xml.validation.ValidationException; import at.gv.egovernment.moa.id.MOAIDException; -import at.gv.egovernment.moa.id.protocols.pvp2x.SAMLRequestNotSignedException; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.SAMLRequestNotSignedException; public class SAMLSignatureValidator implements ISAMLValidator { public void validateRequest(RequestAbstractType request) throws MOAIDException { if (request.getSignature() == null) { - throw new SAMLRequestNotSignedException("NOT SIGNED", - new Object[] {}); + throw new SAMLRequestNotSignedException(); } try { @@ -22,15 +21,14 @@ public class SAMLSignatureValidator implements ISAMLValidator { sigValidator.validate(request.getSignature()); } catch (ValidationException e) { e.printStackTrace(); - throw new MOAIDException("SIGNATURE VALIDATOR", new Object[] {}); + throw new SAMLRequestNotSignedException(e); } } public static void validateSignable(SignableSAMLObject signableObject) throws MOAIDException { if (signableObject.getSignature() == null) { - throw new SAMLRequestNotSignedException("NOT SIGNED", - new Object[] {}); + throw new SAMLRequestNotSignedException(); } try { @@ -38,7 +36,7 @@ public class SAMLSignatureValidator implements ISAMLValidator { sigValidator.validate(signableObject.getSignature()); } catch (ValidationException e) { e.printStackTrace(); - throw new MOAIDException("SIGNATURE VALIDATOR", new Object[] {}); + throw new SAMLRequestNotSignedException(e); } } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/EntityVerifier.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/EntityVerifier.java index 41e9b70cf..d3acf9351 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/EntityVerifier.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/EntityVerifier.java @@ -8,65 +8,63 @@ import org.opensaml.xml.signature.SignatureValidator; import org.opensaml.xml.validation.ValidationException; import at.gv.egovernment.moa.id.MOAIDException; -import at.gv.egovernment.moa.id.protocols.pvp2x.SAMLRequestNotSignedException; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NoCredentialsException; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.SAMLRequestNotSignedException; import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialProvider; +import at.gv.egovernment.moa.logging.Logger; public class EntityVerifier { public static void verify(EntityDescriptor entityDescriptor) throws MOAIDException { if (entityDescriptor.getSignature() == null) { - throw new SAMLRequestNotSignedException("NOT SIGNED", - new Object[] {}); + throw new SAMLRequestNotSignedException(); } try { SAMLSignatureProfileValidator sigValidator = new SAMLSignatureProfileValidator(); sigValidator.validate(entityDescriptor.getSignature()); } catch (ValidationException e) { - e.printStackTrace(); - throw new MOAIDException("SIGNATURE VALIDATOR", new Object[] {}); + Logger.error("Failed to validate Signature", e); + throw new SAMLRequestNotSignedException(e); } Credential credential = CredentialProvider.getSPTrustedCredential(entityDescriptor.getEntityID()); if(credential == null) { - throw new MOAIDException("NO CREDENTIALS FOR " + entityDescriptor.getEntityID(), new Object[] {}); + throw new NoCredentialsException(entityDescriptor.getEntityID()); } SignatureValidator sigValidator = new SignatureValidator(credential); try { sigValidator.validate(entityDescriptor.getSignature()); } catch (ValidationException e) { - // Indicates signature was not cryptographically valid, or possibly a processing error - e.printStackTrace(); - throw new MOAIDException("FAILED TO VERIFY SIGNATURE", new Object[] {}); + Logger.error("Failed to verfiy Signature", e); + throw new SAMLRequestNotSignedException(e); } } public static void verify(EntitiesDescriptor entityDescriptor) throws MOAIDException { if (entityDescriptor.getSignature() == null) { - throw new SAMLRequestNotSignedException("NOT SIGNED", - new Object[] {}); + throw new SAMLRequestNotSignedException(); } try { SAMLSignatureProfileValidator sigValidator = new SAMLSignatureProfileValidator(); sigValidator.validate(entityDescriptor.getSignature()); } catch (ValidationException e) { - e.printStackTrace(); - throw new MOAIDException("SIGNATURE VALIDATOR", new Object[] {}); + Logger.error("Failed to validate Signature", e); + throw new SAMLRequestNotSignedException(e); } - Credential credential = CredentialProvider.getTrustedCredential(); + Credential credential = CredentialProvider.getSPTrustedCredential(entityDescriptor.getName()); if(credential == null) { - throw new MOAIDException("NO CREDENTIALS FOR ", new Object[] {}); + throw new NoCredentialsException("moaID IDP"); } SignatureValidator sigValidator = new SignatureValidator(credential); try { sigValidator.validate(entityDescriptor.getSignature()); } catch (ValidationException e) { - // Indicates signature was not cryptographically valid, or possibly a processing error - e.printStackTrace(); - throw new MOAIDException("FAILED TO VERIFY SIGNATURE", new Object[] {}); + Logger.error("Failed to verfiy Signature", e); + throw new SAMLRequestNotSignedException(e); } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java new file mode 100644 index 000000000..8df418f9a --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java @@ -0,0 +1,67 @@ +package at.gv.egovernment.moa.id.protocols.pvp2x.verification; + +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.RequestAbstractType; +import org.opensaml.saml2.core.Response; +import org.opensaml.saml2.metadata.IDPSSODescriptor; +import org.opensaml.saml2.metadata.SPSSODescriptor; +import org.opensaml.security.MetadataCriteria; +import org.opensaml.security.SAMLSignatureProfileValidator; +import org.opensaml.xml.security.CriteriaSet; +import org.opensaml.xml.security.credential.UsageType; +import org.opensaml.xml.security.criteria.EntityIDCriteria; +import org.opensaml.xml.security.criteria.UsageCriteria; +import org.opensaml.xml.signature.SignatureTrustEngine; +import org.opensaml.xml.validation.ValidationException; + +public class SAMLVerificationEngine { + + public void verifyResponse(Response samlObj, SignatureTrustEngine sigTrustEngine ) throws org.opensaml.xml.security.SecurityException, Exception { + SAMLSignatureProfileValidator profileValidator = new SAMLSignatureProfileValidator(); + try { + profileValidator.validate(samlObj.getSignature()); + } catch (ValidationException e) { + // Indicates signature did not conform to SAML Signature profile + e.printStackTrace(); + } + + CriteriaSet criteriaSet = new CriteriaSet(); + criteriaSet.add( new EntityIDCriteria(samlObj.getIssuer().getValue()) ); + criteriaSet.add( new MetadataCriteria(SPSSODescriptor.DEFAULT_ELEMENT_NAME, SAMLConstants.SAML20P_NS) ); + criteriaSet.add( new UsageCriteria(UsageType.SIGNING) ); + + try { + if (!sigTrustEngine.validate(samlObj.getSignature(), criteriaSet)) { + throw new Exception("Signature was either invalid or signing key could not be established as trusted"); + } + } catch (SecurityException e) { + // Indicates processing error evaluating the signature + e.printStackTrace(); + } + } + + public void verifyRequest(RequestAbstractType samlObj, SignatureTrustEngine sigTrustEngine ) throws org.opensaml.xml.security.SecurityException, Exception { + SAMLSignatureProfileValidator profileValidator = new SAMLSignatureProfileValidator(); + try { + profileValidator.validate(samlObj.getSignature()); + } catch (ValidationException e) { + // Indicates signature did not conform to SAML Signature profile + e.printStackTrace(); + } + + CriteriaSet criteriaSet = new CriteriaSet(); + criteriaSet.add( new EntityIDCriteria(samlObj.getIssuer().getValue()) ); + criteriaSet.add( new MetadataCriteria(SPSSODescriptor.DEFAULT_ELEMENT_NAME, SAMLConstants.SAML20P_NS) ); + criteriaSet.add( new UsageCriteria(UsageType.SIGNING) ); + + try { + if (!sigTrustEngine.validate(samlObj.getSignature(), criteriaSet)) { + throw new Exception("Signature was either invalid or signing key could not be established as trusted"); + } + } catch (SecurityException e) { + // Indicates processing error evaluating the signature + e.printStackTrace(); + } + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerifierMOASP.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerifierMOASP.java index 37289a8e3..6dbaae0a1 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerifierMOASP.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerifierMOASP.java @@ -20,6 +20,8 @@ import eu.stork.vidp.messages.util.XMLUtil; public class SAMLVerifierMOASP implements ISAMLVerifier { + + //TODO: implement via metadata validator .... public void verifyRequest(RequestAbstractType request) throws MOAIDException { // validate Signature @@ -79,7 +81,7 @@ public class SAMLVerifierMOASP implements ISAMLVerifier { Logger.debug("Signing certificate of SAML response succesfully verified"); } else { - String msg = "SAML Response is not signed."; + String msg = "SAML Object is not signed."; throw new SecurityException(msg); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/ExceptionStoreImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/ExceptionStoreImpl.java new file mode 100644 index 000000000..5ea3be837 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/ExceptionStoreImpl.java @@ -0,0 +1,36 @@ +package at.gv.egovernment.moa.id.storage; + +import java.util.HashMap; +import java.util.Map; + +import at.gv.egovernment.moa.id.util.Random; + +public class ExceptionStoreImpl implements IExceptionStore { + + // Just a quick implementation + private static IExceptionStore store; + + public static IExceptionStore getStore() { + if(store == null) { + store = new ExceptionStoreImpl(); + } + return store; + } + + private Map<String, Throwable> exceptionStore = new HashMap<String, Throwable>(); + + public String storeException(Throwable e) { + String id = Random.nextRandom(); + exceptionStore.put(id, e); + return id; + } + + public Throwable fetchException(String id) { + return exceptionStore.get(id); + } + + public void removeException(String id) { + exceptionStore.remove(id); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/IExceptionStore.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/IExceptionStore.java new file mode 100644 index 000000000..5c51fff73 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/IExceptionStore.java @@ -0,0 +1,7 @@ +package at.gv.egovernment.moa.id.storage; + +public interface IExceptionStore { + public String storeException(Throwable e); + public Throwable fetchException(String id); + public void removeException(String id); +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/MandateBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/MandateBuilder.java new file mode 100644 index 000000000..b56a54c90 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/MandateBuilder.java @@ -0,0 +1,59 @@ +package at.gv.egovernment.moa.id.util; + +import java.util.Iterator; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; + +import org.w3c.dom.Element; +import org.w3._2000._09.xmldsig_.*; +import at.gv.e_government.reference.namespace.*; +import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; +import at.gv.e_government.reference.namespace.persondata._20020228_.AbstractPersonType; +import at.gv.e_government.reference.namespace.persondata._20020228_.IdentificationType; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.spss.MOAException; +import at.gv.egovernment.moa.util.Constants; + +@SuppressWarnings("unused") +public class MandateBuilder { + + public static final String MANDATE_DATE_OF_BIRTH_FORMAT = "yyyy-MM-dd"; + + public static Mandate buildMandate(Element mandate) { + + try { + JAXBContext jc = JAXBContext.newInstance("at.gv.e_government.reference.namespace.mandates._20040701_"); + + Unmarshaller u = jc.createUnmarshaller(); + Mandate mand = (Mandate) u.unmarshal(mandate); + return mand; + } catch (JAXBException e) { + Logger.error("Failed to parse Mandate", e); + } + return null; + } + + public static IdentificationType getWBPKIdentification(AbstractPersonType person) { + Iterator<IdentificationType> typesIt = person.getIdentification().iterator(); + while(typesIt.hasNext()) { + IdentificationType id = typesIt.next(); + if(id.getType().startsWith(Constants.URN_PREFIX_WBPK)) { + return id; + } + } + return null; + } + + public static IdentificationType getBPKIdentification(AbstractPersonType person) { + Iterator<IdentificationType> typesIt = person.getIdentification().iterator(); + while(typesIt.hasNext()) { + IdentificationType id = typesIt.next(); + if(id.getType().startsWith(Constants.URN_PREFIX_BPK)) { + return id; + } + } + return null; + } +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/ServletUtils.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/ServletUtils.java index 2ff9e5210..db6d7aa53 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/ServletUtils.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/ServletUtils.java @@ -31,6 +31,7 @@ import java.io.IOException; import java.io.OutputStream; import java.net.URLEncoder; +import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import at.gv.egovernment.moa.id.MOAIDException; @@ -145,5 +146,17 @@ public class ServletUtils { Logger.debug("Finished POST " + servletName); } -
+ + public static String getBaseUrl( HttpServletRequest request ) { + if ( ( request.getServerPort() == 80 ) || + ( request.getServerPort() == 443 ) ) + return request.getScheme() + "://" + + request.getServerName() + + request.getContextPath(); + else + return request.getScheme() + "://" + + request.getServerName() + ":" + request.getServerPort() + + request.getContextPath(); + } +
}
|