diff options
Diffstat (limited to 'id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls')
12 files changed, 821 insertions, 1040 deletions
diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java index c38bbc68f..a1f2c6558 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java @@ -23,9 +23,6 @@ package at.gv.egovernment.moa.id.moduls; import java.io.IOException; -import java.io.PrintWriter; -import java.lang.reflect.InvocationTargetException; -import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; @@ -37,190 +34,484 @@ import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.apache.velocity.VelocityContext; -import org.joda.time.DateTime; -import org.opensaml.common.impl.SecureRandomIdentifierGenerator; -import org.opensaml.common.xml.SAMLConstants; -import org.opensaml.saml2.core.AuthnContextClassRef; -import org.opensaml.saml2.core.AuthnContextComparisonTypeEnumeration; -import org.opensaml.saml2.core.AuthnRequest; -import org.opensaml.saml2.core.Issuer; +import org.apache.commons.lang.StringEscapeUtils; import org.opensaml.saml2.core.LogoutRequest; import org.opensaml.saml2.core.LogoutResponse; -import org.opensaml.saml2.core.NameID; -import org.opensaml.saml2.core.NameIDPolicy; -import org.opensaml.saml2.core.NameIDType; -import org.opensaml.saml2.core.RequestedAuthnContext; import org.opensaml.saml2.core.StatusCode; -import org.opensaml.saml2.metadata.EntityDescriptor; import org.opensaml.saml2.metadata.SingleLogoutService; -import org.opensaml.saml2.metadata.SingleSignOnService; -import org.opensaml.saml2.metadata.provider.MetadataProviderException; -import org.opensaml.ws.message.encoder.MessageEncodingException; import org.opensaml.ws.soap.common.SOAPException; import org.opensaml.xml.XMLObject; import org.opensaml.xml.security.SecurityException; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger; -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.auth.builder.LoginFormBuilder; -import at.gv.egovernment.moa.id.auth.builder.SendAssertionFormBuilder; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.data.AuthenticationSessionExtensions; -import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; -import at.gv.egovernment.moa.id.auth.exception.BuildException; import at.gv.egovernment.moa.id.auth.exception.InvalidProtocolRequestException; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.auth.frontend.builder.DefaultGUIFormBuilderConfiguration; +import at.gv.egovernment.moa.id.auth.frontend.builder.IGUIFormBuilder; +import at.gv.egovernment.moa.id.auth.frontend.exception.GUIBuildException; +import at.gv.egovernment.moa.id.auth.modules.SingleSignOnConsentsModuleImpl; import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; import at.gv.egovernment.moa.id.auth.modules.registration.ModuleRegistration; +import at.gv.egovernment.moa.id.commons.MOAIDAuthConstants; +import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; +import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; +import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; import at.gv.egovernment.moa.id.commons.db.dao.session.InterfederationSessionStore; import at.gv.egovernment.moa.id.commons.db.dao.session.OASessionStore; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.commons.utils.MOAIDMessageProvider; import at.gv.egovernment.moa.id.data.SLOInformationContainer; import at.gv.egovernment.moa.id.data.SLOInformationImpl; import at.gv.egovernment.moa.id.process.ExecutionContextImpl; import at.gv.egovernment.moa.id.process.ProcessEngine; import at.gv.egovernment.moa.id.process.ProcessExecutionException; import at.gv.egovernment.moa.id.process.api.ExecutionContext; -import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; import at.gv.egovernment.moa.id.protocols.pvp2x.PVPTargetConfiguration; -import at.gv.egovernment.moa.id.protocols.pvp2x.binding.IEncoder; -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.builder.SingleLogOutBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.config.PVPConfiguration; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.MOASAMLSOAPClient; -import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; -import at.gv.egovernment.moa.id.protocols.pvp2x.verification.SAMLVerificationEngine; +import at.gv.egovernment.moa.id.protocols.pvp2x.verification.SAMLVerificationEngineSP; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.TrustEngineFactory; -import at.gv.egovernment.moa.id.storage.AssertionStorage; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; -import at.gv.egovernment.moa.id.util.MOAIDMessageProvider; -import at.gv.egovernment.moa.id.util.PVPtoSTORKMapper; +import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.storage.ITransactionStorage; import at.gv.egovernment.moa.id.util.ParamValidatorUtils; import at.gv.egovernment.moa.id.util.Random; +import at.gv.egovernment.moa.id.util.legacy.LegacyHelper; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; +@Service("MOAID_AuthenticationManager") public class AuthenticationManager extends MOAIDAuthConstants { - private static final AuthenticationManager INSTANCE = new AuthenticationManager(); public static final String MOA_SESSION = "MoaAuthenticationSession"; public static final String MOA_AUTHENTICATED = "MoaAuthenticated"; public static final int SLOTIMEOUT = 30 * 1000; //30 sec - @Autowired - private ProcessEngine processEngine; - - private AuthenticationManager() { + @Autowired private ProcessEngine processEngine; + @Autowired private SSOManager ssoManager; + @Autowired private IRequestStorage requestStoreage; + @Autowired private ITransactionStorage transactionStorage; + @Autowired private IAuthenticationSessionStoreage authenticatedSessionStore; + @Autowired private MOAReversionLogger revisionsLogger; + @Autowired protected AuthConfiguration authConfig; + @Autowired private SingleLogOutBuilder sloBuilder; + @Autowired private SAMLVerificationEngineSP samlVerificationEngine; + @Autowired private IGUIFormBuilder guiBuilder; + + public void performSingleLogOut(HttpServletRequest httpReq, + HttpServletResponse httpResp, AuthenticationSession session, PVPTargetConfiguration pvpReq) throws MOAIDException { + performSingleLogOut(httpReq, httpResp, session, pvpReq, null); + } - public static AuthenticationManager getInstance() { - return INSTANCE; + public void performSingleLogOut(HttpServletRequest httpReq, + HttpServletResponse httpResp, AuthenticationSession session, String authURL) throws MOAIDException { + performSingleLogOut(httpReq, httpResp, session, null, authURL); + } + public void performOnlyIDPLogOut(HttpServletRequest request, + HttpServletResponse response, String moaSessionID) { + Logger.info("Remove active user-session"); + + if(moaSessionID == null) { + moaSessionID = (String) request.getParameter(PARAM_SESSIONID); + } + + if(moaSessionID == null) { + Logger.info("NO MOA Session to logout"); + return; + } + + AuthenticationSession authSession; + try { + authSession = authenticatedSessionStore.getSession(moaSessionID); + + if(authSession == null) { + Logger.info("NO MOA Authentication data for ID " + moaSessionID); + return; + } + + authSession.setAuthenticated(false); + //HTTPSessionUtils.setHTTPSessionString(session, MOA_SESSION, null); // remove moa session from HTTP Session + + //log Session_Destroy to reversionslog + AuthenticationSessionExtensions sessionExtensions = authenticatedSessionStore.getAuthenticationSessionExtensions(moaSessionID); + revisionsLogger.logEvent(MOAIDEventConstants.SESSION_DESTROYED, sessionExtensions.getUniqueSessionId()); + + authenticatedSessionStore.destroySession(moaSessionID); + + //session.invalidate(); + + } catch (MOADatabaseException e) { + Logger.info("NO MOA Authentication data for ID " + moaSessionID); + return; + } + + } + + /** - * Checks if this request can authenticate a MOA Session + * Authenticates the authentication request {pendingReq}, which is actually processed + * + * @param httpReq HttpServletRequest + * @param httpResp HttpServletResponse + * @param protocolRequest Authentication request which is actually in process + * + * @return Return already authenticated MOASession if exists, otherwise return null + * @throws MOADatabaseException + * @throws MOAIDException + * @throws IOException + * @throws ServletException * - * @param request - * @param response - * @return */ - public boolean tryPerformAuthentication(HttpServletRequest request, - HttpServletResponse response) { + public AuthenticationSession doAuthentication(HttpServletRequest httpReq, + HttpServletResponse httpResp, RequestImpl pendingReq) throws MOADatabaseException, ServletException, IOException, MOAIDException { + + //generic authentication request validation + if (pendingReq.isPassiv() + && pendingReq.forceAuth()) { + // conflict! + throw new NoPassivAuthenticationException(); + } - String sessionID = (String) request.getParameter(PARAM_SESSIONID); - if (sessionID != null) { - Logger.debug("Find MOASession: " + sessionID); - AuthenticationSession authSession; - try { - authSession = AuthenticationSessionStoreage.getSession(sessionID); - - if (authSession != null) { - Logger.info("MOASession found! A: " - + authSession.isAuthenticated() + ", AU " - + authSession.isAuthenticatedUsed()); - if (authSession.isAuthenticated() - && !authSession.isAuthenticatedUsed()) { - authSession.setAuthenticatedUsed(true); - - AuthenticationSessionStoreage.storeSession(authSession); - - return true; // got authenticated - } - } + //get SSO cookie from http request + String ssoId = ssoManager.getSSOSessionID(httpReq); + + //check if interfederation IDP is requested + ssoManager.checkInterfederationIsRequested(httpReq, httpResp, pendingReq); + + //check if SSO session cookie is already used + if (ssoId != null) { + String correspondingMOASession = ssoManager.existsOldSSOSession(ssoId); - } catch (MOADatabaseException e) { - return false; - } catch (BuildException e) { + if (correspondingMOASession != null) { + Logger.warn("Request sends an old SSO Session ID("+ssoId+")! " + + "Invalidate the corresponding MOASession with ID="+ correspondingMOASession); + + revisionsLogger.logEvent(pendingReq.getOnlineApplicationConfiguration(), + pendingReq, MOAIDEventConstants.AUTHPROCESS_SSO_INVALID); + + authenticatedSessionStore.destroySession(correspondingMOASession); + ssoManager.deleteSSOSessionID(httpReq, httpResp); + } + } + + //check if SSO Session is valid + boolean isValidSSOSession = ssoManager.isValidSSOSession(ssoId, pendingReq); + + // check if Service-Provider allows SSO sessions + IOAAuthParameters oaParam = pendingReq.getOnlineApplicationConfiguration(); + boolean useSSOOA = oaParam.useSSO() || oaParam.isInderfederationIDP(); + + revisionsLogger.logEvent(oaParam, + pendingReq, MOAIDEventConstants.AUTHPROCESS_SERVICEPROVIDER, pendingReq.getOAURL()); + + //if a legacy request is used SSO should not be allowed in case of mandate authentication + boolean isUseMandateRequested = LegacyHelper.isUseMandateRequested(httpReq); + + //check if SSO is allowed for the actually executed request + //INFO: Actually, useMandate disables SSO functionality!!!!! + boolean isSSOAllowed = (useSSOOA && !isUseMandateRequested); + pendingReq.setNeedSingleSignOnFunctionality(isSSOAllowed); + + //get MOASession from SSO-Cookie if SSO is allowed + AuthenticationSession moaSession = null; + if (isValidSSOSession && isSSOAllowed) { + String moasessionID = ssoManager.getMOASession(ssoId); + moaSession = authenticatedSessionStore.getSession(moasessionID); + + if (moaSession == null) + Logger.info("No MOASession FOUND with provided SSO-Cookie."); + + else { + Logger.debug("Found authenticated MOASession with provided SSO-Cookie."); + revisionsLogger.logEvent(oaParam, pendingReq, MOAIDEventConstants.AUTHPROCESS_SSO); + + } + } + + //check if session is already authenticated + boolean isSessionAuthenticated = tryPerformAuthentication((RequestImpl) pendingReq, moaSession); + + //force new authentication authentication process + if (pendingReq.forceAuth()) { + startAuthenticationProcess(httpReq, httpResp, pendingReq); + return null; + + //perform SSO-Consents evaluation if it it required + } else if (isSessionAuthenticated && oaParam.useSSOQuestion()) { + sendSingleSignOnConsentsEvaluation(httpReq, httpResp, pendingReq); + return null; + + } else if (pendingReq.isPassiv()) { + if (isSessionAuthenticated) { + // Passive authentication ok! + revisionsLogger.logEvent(oaParam, pendingReq, MOAIDEventConstants.AUTHPROCESS_FINISHED); + return moaSession; + + } else { + throw new NoPassivAuthenticationException(); + + } + } else { + if (isSessionAuthenticated) { + // Is authenticated .. proceed + revisionsLogger.logEvent(oaParam, + pendingReq, MOAIDEventConstants.AUTHPROCESS_FINISHED); + return moaSession; + + } else { + // Start authentication! + startAuthenticationProcess(httpReq, httpResp, pendingReq); + return null; + } + } + } + + /** + * Checks if a authenticated MOASession already exists and if {protocolRequest} is authenticated + * + * @param protocolRequest Authentication request which is actually in process + * @param moaSession MOASession with authentication information or null if no active MOASession exists + * + * @return true if session is already authenticated, otherwise false + * @throws MOAIDException + */ + private boolean tryPerformAuthentication(RequestImpl protocolRequest, AuthenticationSession moaSession) { + + //if no MOASession exist -> authentication is required + if (moaSession == null) { + return false; + + } else { + //if MOASession is Found but not authenticated --> authentication is required + if (!moaSession.isAuthenticated()) { return false; } + + //if MOASession is already authenticated and protocol-request is authenticated + // --> no authentication is required any more + else if (moaSession.isAuthenticated() && protocolRequest.isAuthenticated()) { + return true; + + // if MOASession is authenticated and SSO is allowed --> authenticate pendingRequest + } else if (!protocolRequest.isAuthenticated() + && moaSession.isAuthenticated() && protocolRequest.needSingleSignOnFunctionality()) { + Logger.debug("Found active MOASession and SSO is allowed --> pendingRequest is authenticted"); + protocolRequest.setAuthenticated(true); + protocolRequest.setMOASessionIdentifier(moaSession.getSessionID()); + return true; + + } + + // force authentication as backup solution + else { + Logger.warn("Authentication-required check find an unsuspected state --> force authentication"); + return false; + + } } - return false; } - public void performSingleLogOut(HttpServletRequest httpReq, - HttpServletResponse httpResp, AuthenticationSession session, PVPTargetConfiguration pvpReq) throws MOAIDException { - performSingleLogOut(httpReq, httpResp, session, pvpReq, null); + private void startAuthenticationProcess(HttpServletRequest httpReq, + HttpServletResponse httpResp, RequestImpl pendingReq) + throws ServletException, IOException, MOAIDException { + + Logger.info("Starting authentication ..."); + revisionsLogger.logEvent(pendingReq.getOnlineApplicationConfiguration(), + pendingReq, MOAIDEventConstants.AUTHPROCESS_START); + + //is legacy allowed + List<String> legacyallowed_prot = authConfig.getLegacyAllowedProtocols(); + boolean legacyallowed = legacyallowed_prot.contains(pendingReq.requestedModule()); + + //check legacy request parameter + boolean legacyparamavail = ParamValidatorUtils.areAllLegacyParametersAvailable(httpReq); + + //create MOASession object + AuthenticationSession moasession; + try { + moasession = authenticatedSessionStore.createSession(pendingReq); + pendingReq.setMOASessionIdentifier(moasession.getSessionID()); + + } catch (MOADatabaseException e1) { + Logger.error("Database Error! MOASession can not be created!"); + throw new MOAIDException("init.04", new Object[] {}); + + } + + //create authentication process execution context + ExecutionContext executionContext = new ExecutionContextImpl(); + + //set interfederation authentication flag + executionContext.put(MOAIDAuthConstants.PROCESSCONTEXT_PERFORM_INTERFEDERATION_AUTH, + MiscUtil.isNotEmpty( + pendingReq.getGenericData(RequestImpl.DATAID_INTERFEDERATIOIDP_URL, String.class))); + + //set legacy mode or BKU-selection flags + boolean leagacyMode = (legacyallowed && legacyparamavail); + executionContext.put(MOAIDAuthConstants.PROCESSCONTEXT_ISLEGACYREQUEST, leagacyMode); + executionContext.put(MOAIDAuthConstants.PROCESSCONTEXT_PERFORM_BKUSELECTION, !leagacyMode + && MiscUtil.isEmpty(pendingReq.getGenericData(RequestImpl.DATAID_INTERFEDERATIOIDP_URL, String.class))); + + //add leagcy parameters to context + if (leagacyMode) { + Enumeration<String> reqParamNames = httpReq.getParameterNames(); + while(reqParamNames.hasMoreElements()) { + String paramName = reqParamNames.nextElement(); + if (MiscUtil.isNotEmpty(paramName) && + MOAIDAuthConstants.LEGACYPARAMETERWHITELIST.contains(paramName)) + executionContext.put(paramName, + StringEscapeUtils.escapeHtml(httpReq.getParameter(paramName))); + + } + } + + //start process engine + startProcessEngine(pendingReq, executionContext); } - - public void performSingleLogOut(HttpServletRequest httpReq, - HttpServletResponse httpResp, AuthenticationSession session, String authURL) throws MOAIDException { - performSingleLogOut(httpReq, httpResp, session, null, authURL); + + private void sendSingleSignOnConsentsEvaluation(HttpServletRequest request, + HttpServletResponse response, RequestImpl pendingReq) + throws ServletException, IOException, MOAIDException { + + Logger.info("Start SSO user-consents evaluation ..."); + //set authenticated flag to false, because user consents is required + pendingReq.setAuthenticated(false); + + //create execution context + ExecutionContext executionContext = new ExecutionContextImpl(); + executionContext.put(SingleSignOnConsentsModuleImpl.PARAM_SSO_CONSENTS_EVALUATION, true); + + //start process engine + startProcessEngine(pendingReq, executionContext); + } + private void startProcessEngine(RequestImpl pendingReq, ExecutionContext executionContext) throws MOAIDException { + try { + //put pending-request ID on execurtionContext + executionContext.put(MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID, pendingReq.getRequestID()); + + // create process instance + String processDefinitionId = ModuleRegistration.getInstance().selectProcess(executionContext); + + if (processDefinitionId == null) { + Logger.warn("No suitable process found for SessionID " + pendingReq.getRequestID() ); + throw new MOAIDException("process.02",new Object[] { + pendingReq.getRequestID()}); + } + + String processInstanceId = processEngine.createProcessInstance(processDefinitionId, executionContext); + + // keep process instance id in protocol pending-request + pendingReq.setProcessInstanceId(processInstanceId); + + //store pending-request + requestStoreage.storePendingRequest(pendingReq); + + // start process + processEngine.start(pendingReq); + + } catch (ProcessExecutionException e) { + Throwable cause = e.getCause(); + if (cause != null && cause instanceof TaskExecutionException) { + Throwable taskCause = cause.getCause(); + if (taskCause != null && taskCause instanceof MOAIDException) { + MOAIDException moaTaskCause = (MOAIDException) taskCause; + Logger.warn(taskCause); + throw moaTaskCause; + + } + } + + throw new MOAIDException("process.01", new Object[] { pendingReq.getProcessInstanceId(), pendingReq.getRequestID() }, e); + } + } private void performSingleLogOut(HttpServletRequest httpReq, HttpServletResponse httpResp, AuthenticationSession session, PVPTargetConfiguration pvpReq, String authURL) throws MOAIDException { String pvpSLOIssuer = null; String inboundRelayState = null; + String uniqueSessionIdentifier = "notSet"; + String uniqueTransactionIdentifier = "notSet"; + + Logger.debug("Start technical Single LogOut process ... "); if (pvpReq != null) { MOARequest samlReq = (MOARequest) pvpReq.getRequest(); LogoutRequest logOutReq = (LogoutRequest) samlReq.getSamlRequest(); pvpSLOIssuer = logOutReq.getIssuer().getValue(); inboundRelayState = samlReq.getRelayState(); + uniqueSessionIdentifier = pvpReq.getUniqueSessionIdentifier(); + uniqueTransactionIdentifier = pvpReq.getUniqueTransactionIdentifier(); + } else { + AuthenticationSessionExtensions sessionExt; + try { + sessionExt = authenticatedSessionStore.getAuthenticationSessionExtensions(session.getSessionID()); + if (sessionExt != null) + uniqueSessionIdentifier = sessionExt.getUniqueSessionId(); + + } catch (MOADatabaseException e) { + Logger.error("Error during database communication. Can not evaluate 'uniqueSessionIdentifier'", e); + + } + uniqueTransactionIdentifier = Random.nextLongRandom(); + revisionsLogger.logEvent(uniqueSessionIdentifier, uniqueTransactionIdentifier, MOAIDEventConstants.AUTHPROCESS_IDP_SLO_REQUESTED); + } - SSOManager ssomanager = SSOManager.getInstance(); - //store active OAs to SLOContaine - List<OASessionStore> dbOAs = AuthenticationSessionStoreage.getAllActiveOAFromMOASession(session); - List<InterfederationSessionStore> dbIDPs = AuthenticationSessionStoreage.getAllActiveIDPsFromMOASession(session); - SLOInformationContainer sloContainer = new SLOInformationContainer(); + List<OASessionStore> dbOAs = authenticatedSessionStore.getAllActiveOAFromMOASession(session); + List<InterfederationSessionStore> dbIDPs = authenticatedSessionStore.getAllActiveIDPsFromMOASession(session); + SLOInformationContainer sloContainer = new SLOInformationContainer(); + sloContainer.setTransactionID(uniqueTransactionIdentifier); + sloContainer.setSessionID(uniqueSessionIdentifier); sloContainer.setSloRequest(pvpReq); - sloContainer.parseActiveIDPs(dbIDPs, pvpSLOIssuer); - sloContainer.parseActiveOAs(dbOAs, pvpSLOIssuer); - - //terminate MOASession - try { - AuthenticationSessionStoreage.destroySession(session.getSessionID()); - ssomanager.deleteSSOSessionID(httpReq, httpResp); + + sloBuilder.parseActiveIDPs(sloContainer, dbIDPs, pvpSLOIssuer); + sloBuilder.parseActiveOAs(sloContainer, dbOAs, pvpSLOIssuer); + Logger.debug("Active SSO Service-Provider: " + + " BackChannel:" + sloContainer.getActiveBackChannelOAs().size() + + " FrontChannel:" + sloContainer.getActiveFrontChannalOAs().size() + + " NO_SLO_Support:" + sloContainer.getSloFailedOAs().size()); + + //terminate MOASession + try { + authenticatedSessionStore.destroySession(session.getSessionID()); + ssoManager.deleteSSOSessionID(httpReq, httpResp); + revisionsLogger.logEvent(MOAIDEventConstants.SESSION_DESTROYED, uniqueSessionIdentifier); + + Logger.debug("Active SSO Session on IDP is remove."); + } catch (MOADatabaseException e) { Logger.warn("Delete MOASession FAILED."); sloContainer.putFailedOA(pvpReq.getAuthURL()); } - //start service provider back channel logout process + Logger.trace("Starting Service-Provider logout process ... "); + revisionsLogger.logEvent(uniqueSessionIdentifier, uniqueTransactionIdentifier, MOAIDEventConstants.AUTHPROCESS_SLO_STARTED); + //start service provider back channel logout process Iterator<String> nextOAInterator = sloContainer.getNextBackChannelOA(); while (nextOAInterator.hasNext()) { SLOInformationImpl sloDescr = sloContainer.getBackChannelOASessionDescripten(nextOAInterator.next()); - LogoutRequest sloReq = SingleLogOutBuilder.buildSLORequestMessage(sloDescr); + LogoutRequest sloReq = sloBuilder.buildSLORequestMessage(sloDescr); try { + Logger.trace("Send backchannel SLO Request to " + sloDescr.getSpEntityID()); List<XMLObject> soapResp = MOASAMLSOAPClient.send(sloDescr.getServiceURL(), sloReq); LogoutResponse sloResp = null; @@ -230,28 +521,27 @@ public class AuthenticationManager extends MOAIDAuthConstants { } if (sloResp == null) { - Logger.warn("Single LogOut for OA " + sloReq.getIssuer().getValue() + Logger.warn("Single LogOut for OA " + sloDescr.getSpEntityID() + " FAILED. NO LogOut response received."); - sloContainer.putFailedOA(sloReq.getIssuer().getValue()); + sloContainer.putFailedOA(sloDescr.getSpEntityID()); } else { - SAMLVerificationEngine engine = new SAMLVerificationEngine(); - engine.verifySLOResponse(sloResp, - TrustEngineFactory.getSignatureKnownKeysTrustEngine()); + samlVerificationEngine.verifySLOResponse(sloResp, + TrustEngineFactory.getSignatureKnownKeysTrustEngine(MOAMetadataProvider.getInstance())); } - SingleLogOutBuilder.checkStatusCode(sloContainer, sloResp); + sloBuilder.checkStatusCode(sloContainer, sloResp); } catch (SOAPException e) { - Logger.warn("Single LogOut for OA " + sloReq.getIssuer().getValue() + Logger.warn("Single LogOut for OA " + sloDescr.getSpEntityID() + " FAILED.", e); - sloContainer.putFailedOA(sloReq.getIssuer().getValue()); + sloContainer.putFailedOA(sloDescr.getSpEntityID()); } catch (SecurityException | InvalidProtocolRequestException e) { - Logger.warn("Single LogOut for OA " + sloReq.getIssuer().getValue() + Logger.warn("Single LogOut for OA " + sloDescr.getSpEntityID() + " FAILED.", e); - sloContainer.putFailedOA(sloReq.getIssuer().getValue()); + sloContainer.putFailedOA(sloDescr.getSpEntityID()); } } @@ -264,9 +554,11 @@ public class AuthenticationManager extends MOAIDAuthConstants { Collection<Entry<String, SLOInformationImpl>> sloDescr = sloContainer.getFrontChannelOASessionDescriptions(); List<String> sloReqList = new ArrayList<String>(); for (Entry<String, SLOInformationImpl> el : sloDescr) { - LogoutRequest sloReq = SingleLogOutBuilder.buildSLORequestMessage(el.getValue()); + Logger.trace("Build frontChannel SLO Request for " + el.getValue().getSpEntityID()); + + LogoutRequest sloReq = sloBuilder.buildSLORequestMessage(el.getValue()); try { - sloReqList.add(SingleLogOutBuilder.getFrontChannelSLOMessageURL(el.getValue().getServiceURL(), el.getValue().getBinding(), + sloReqList.add(sloBuilder.getFrontChannelSLOMessageURL(el.getValue().getServiceURL(), el.getValue().getBinding(), sloReq, httpReq, httpResp, relayState)); } catch (Exception e) { @@ -276,7 +568,8 @@ public class AuthenticationManager extends MOAIDAuthConstants { } } - AssertionStorage.getInstance().put(relayState, sloContainer); + //put SLO process-information into transaction storage + transactionStorage.put(relayState, sloContainer); if (MiscUtil.isEmpty(authURL)) authURL = pvpReq.getAuthURL(); @@ -285,49 +578,82 @@ public class AuthenticationManager extends MOAIDAuthConstants { + "/idpSingleLogout" + "?restart=" + relayState; - VelocityContext context = new VelocityContext(); - context.put("redirectURLs", sloReqList); - context.put("timeoutURL", timeOutURL); - context.put("timeout", SLOTIMEOUT); - ssomanager.printSingleLogOutInfo(context, httpResp); + DefaultGUIFormBuilderConfiguration config = new DefaultGUIFormBuilderConfiguration( + authURL, + DefaultGUIFormBuilderConfiguration.VIEW_SINGLELOGOUT, + null); + config.putCustomParameter("redirectURLs", sloReqList); + config.putCustomParameter("timeoutURL", timeOutURL); + config.putCustomParameter("timeout", SLOTIMEOUT); + + guiBuilder.build(httpResp, config, "Single-LogOut GUI"); + } else { if (pvpReq != null) { //send SLO response to SLO request issuer - SingleLogoutService sloService = SingleLogOutBuilder.getResponseSLODescriptor(pvpReq); - LogoutResponse message = SingleLogOutBuilder.buildSLOResponseMessage(sloService, pvpReq, sloContainer.getSloFailedOAs()); - SingleLogOutBuilder.sendFrontChannelSLOMessage(sloService, message, httpReq, httpResp, inboundRelayState); + SingleLogoutService sloService = sloBuilder.getResponseSLODescriptor(pvpReq); + LogoutResponse message = sloBuilder.buildSLOResponseMessage(sloService, pvpReq, sloContainer.getSloFailedOAs()); + sloBuilder.sendFrontChannelSLOMessage(sloService, message, httpReq, httpResp, inboundRelayState); } else { //print SLO information directly - VelocityContext context = new VelocityContext(); + DefaultGUIFormBuilderConfiguration config = new DefaultGUIFormBuilderConfiguration( + authURL, + DefaultGUIFormBuilderConfiguration.VIEW_SINGLELOGOUT, + null); + if (sloContainer.getSloFailedOAs() == null || - sloContainer.getSloFailedOAs().size() == 0) - context.put("successMsg", + sloContainer.getSloFailedOAs().size() == 0) { + revisionsLogger.logEvent(uniqueSessionIdentifier, uniqueTransactionIdentifier, MOAIDEventConstants.AUTHPROCESS_SLO_ALL_VALID); + config.putCustomParameter("successMsg", MOAIDMessageProvider.getInstance().getMessage("slo.00", null)); - else - context.put("errorMsg", + + } else { + revisionsLogger.logEvent(uniqueSessionIdentifier, uniqueTransactionIdentifier, MOAIDEventConstants.AUTHPROCESS_SLO_NOT_ALL_VALID); + config.putCustomParameter("errorMsg", MOAIDMessageProvider.getInstance().getMessage("slo.01", null)); - ssomanager.printSingleLogOutInfo(context, httpResp); + + } + guiBuilder.build(httpResp, config, "Single-LogOut GUI"); } } - + + } catch (GUIBuildException e) { + Logger.warn("Can not build GUI:'Single-LogOut'. Msg:" + e.getMessage()); + throw new MOAIDException("builder.09", new Object[]{e.getMessage()}, e); + } catch (MOADatabaseException e) { Logger.error("MOA AssertionDatabase ERROR", e); if (pvpReq != null) { - SingleLogoutService sloService = SingleLogOutBuilder.getResponseSLODescriptor(pvpReq); - LogoutResponse message = SingleLogOutBuilder.buildSLOErrorResponse(sloService, pvpReq, StatusCode.RESPONDER_URI); - SingleLogOutBuilder.sendFrontChannelSLOMessage(sloService, message, httpReq, httpResp, inboundRelayState); + SingleLogoutService sloService = sloBuilder.getResponseSLODescriptor(pvpReq); + LogoutResponse message = sloBuilder.buildSLOErrorResponse(sloService, pvpReq, StatusCode.RESPONDER_URI); + sloBuilder.sendFrontChannelSLOMessage(sloService, message, httpReq, httpResp, inboundRelayState); + + revisionsLogger.logEvent(uniqueSessionIdentifier, uniqueTransactionIdentifier, MOAIDEventConstants.AUTHPROCESS_SLO_NOT_ALL_VALID); }else { //print SLO information directly - VelocityContext context = new VelocityContext(); - context.put("errorMsg", + DefaultGUIFormBuilderConfiguration config = new DefaultGUIFormBuilderConfiguration( + authURL, + DefaultGUIFormBuilderConfiguration.VIEW_SINGLELOGOUT, + null); + + revisionsLogger.logEvent(uniqueSessionIdentifier, uniqueTransactionIdentifier, MOAIDEventConstants.AUTHPROCESS_SLO_NOT_ALL_VALID); + config.putCustomParameter("errorMsg", MOAIDMessageProvider.getInstance().getMessage("slo.01", null)); - ssomanager.printSingleLogOutInfo(context, httpResp); + + try { + guiBuilder.build(httpResp, config, "Single-LogOut GUI"); + + } catch (GUIBuildException e1) { + Logger.warn("Can not build GUI:'Single-LogOut'. Msg:" + e.getMessage()); + throw new MOAIDException("builder.09", new Object[]{e.getMessage()}, e); + + } } @@ -336,421 +662,4 @@ public class AuthenticationManager extends MOAIDAuthConstants { e.printStackTrace(); } } - - public void performOnlyIDPLogOut(HttpServletRequest request, - HttpServletResponse response, String moaSessionID) { - Logger.info("Logout"); - - if(moaSessionID == null) { - moaSessionID = (String) request.getParameter(PARAM_SESSIONID); - } - - if(moaSessionID == null) { - Logger.info("NO MOA Session to logout"); - return; - } - - AuthenticationSession authSession; - try { - authSession = AuthenticationSessionStoreage - .getSession(moaSessionID); - - if(authSession == null) { - Logger.info("NO MOA Authentication data for ID " + moaSessionID); - return; - } - - authSession.setAuthenticated(false); - //HTTPSessionUtils.setHTTPSessionString(session, MOA_SESSION, null); // remove moa session from HTTP Session - - //log Session_Destroy to reversionslog - AuthenticationSessionExtensions sessionExtensions = AuthenticationSessionStoreage.getAuthenticationSessionExtensions(moaSessionID); - MOAReversionLogger.getInstance().logEvent(MOAIDEventConstants.SESSION_DESTROYED, sessionExtensions.getUniqueSessionId()); - - AuthenticationSessionStoreage.destroySession(moaSessionID); - - //session.invalidate(); - - } catch (MOADatabaseException e) { - Logger.info("NO MOA Authentication data for ID " + moaSessionID); - return; - } - - } - - public void doAuthentication(HttpServletRequest request, - HttpServletResponse response, IRequest target) - throws ServletException, IOException, MOAIDException { - - Logger.info("Starting authentication ..."); - MOAReversionLogger.getInstance().logEvent(target.getOnlineApplicationConfiguration(), - target, MOAIDEventConstants.AUTHPROCESS_START); - - if (MiscUtil.isEmpty(target.getRequestedIDP())) { - perfomLocalAuthentication(request, response, target); - - } else { - Logger.info("Use IDP " + target.getRequestedIDP() + " for authentication ..."); - MOAReversionLogger.getInstance().logEvent(target.getOnlineApplicationConfiguration(), - target, MOAIDEventConstants.AUTHPROCESS_INTERFEDERATION); - buildPVP21AuthenticationRequest(request, response, target); - - } - } - - public void sendTransmitAssertionQuestion(HttpServletRequest request, - HttpServletResponse response, IRequest target, OAAuthParameter oaParam) - throws ServletException, IOException, MOAIDException { - - String form = SendAssertionFormBuilder.buildForm(target.requestedModule(), - target.requestedAction(), target.getRequestID(), oaParam, - target.getAuthURL()); - - MOAReversionLogger.getInstance().logEvent(target.getOnlineApplicationConfiguration(), - target, MOAIDEventConstants.AUTHPROCESS_SSO_ASK_USER_START); - - response.setContentType("text/html;charset=UTF-8"); - PrintWriter out = new PrintWriter(response.getOutputStream()); - out.print(form); - out.flush(); - } - - private void buildPVP21AuthenticationRequest(HttpServletRequest request, - HttpServletResponse response, IRequest target) - throws ServletException, IOException, MOAIDException { - - boolean requiredLocalAuthentication = true; - - Logger.debug("Build PVP 2.1 authentication request"); - - //get IDP metadata - - OAAuthParameter idp = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(target.getRequestedIDP()); - OAAuthParameter sp = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(target.getOAURL()); - - if (!idp.isInderfederationIDP() || !idp.isInboundSSOInterfederationAllowed()) { - Logger.info("Requested interfederation IDP " + target.getRequestedIDP() + " is not valid for interfederation."); - Logger.debug("isInderfederationIDP:" + String.valueOf(idp.isInderfederationIDP()) - + " isInboundSSOAllowed:" + String.valueOf(idp.isInboundSSOInterfederationAllowed())); - Logger.info("Switch to local authentication on this IDP ... "); - - perfomLocalAuthentication(request, response, target); - return; - - } - - try { - EntityDescriptor idpEntity = MOAMetadataProvider.getInstance(). - getEntityDescriptor(target.getRequestedIDP()); - - if (idpEntity != null ) { - - //fetch endpoint from IDP metadata - SingleSignOnService redirectEndpoint = null; - for (SingleSignOnService sss : - idpEntity.getIDPSSODescriptor(SAMLConstants.SAML20P_NS).getSingleSignOnServices()) { - - // use POST binding as default if it exists - //TODO: maybe use RedirectBinding as default - if (sss.getBinding().equals(SAMLConstants.SAML2_POST_BINDING_URI)) { - redirectEndpoint = sss; - - } else if ( sss.getBinding().equals(SAMLConstants.SAML2_REDIRECT_BINDING_URI) && - redirectEndpoint == null ) - redirectEndpoint = sss; - } - - if (redirectEndpoint != null) { - - AuthnRequest authReq = SAML2Utils - .createSAMLObject(AuthnRequest.class); - SecureRandomIdentifierGenerator gen = new SecureRandomIdentifierGenerator(); - authReq.setID(gen.generateIdentifier()); - - //send passive AuthnRequest - authReq.setIsPassive(idp.isPassivRequestUsedForInterfederation()); - - authReq.setAssertionConsumerServiceIndex(0); - authReq.setIssueInstant(new DateTime()); - Issuer issuer = SAML2Utils.createSAMLObject(Issuer.class); - String serviceURL = PVPConfiguration.getInstance().getIDPPublicPath().get(0); - issuer.setValue(serviceURL); - - issuer.setFormat(NameIDType.ENTITY); - authReq.setIssuer(issuer); - NameIDPolicy policy = SAML2Utils - .createSAMLObject(NameIDPolicy.class); - policy.setAllowCreate(true); - policy.setFormat(NameID.TRANSIENT); - authReq.setNameIDPolicy(policy); - - authReq.setDestination(redirectEndpoint.getLocation()); - - RequestedAuthnContext reqAuthContext = - SAML2Utils.createSAMLObject(RequestedAuthnContext.class); - - AuthnContextClassRef authnClassRef = - SAML2Utils.createSAMLObject(AuthnContextClassRef.class); - - //check if STORK protocol module is in ClassPath - Class<?> storkRequstTemplate = null; - Integer storkSecClass = null; - try { - storkRequstTemplate = Class.forName("at.gv.egovernment.moa.id.protocols.stork2.MOASTORKRequest"); - if (storkRequstTemplate != null && - storkRequstTemplate.isInstance(target)) { - Object storkAuthnRequest = target.getClass().getMethod("getStorkAuthnRequest", null).invoke(target, null); - storkSecClass = (Integer) storkAuthnRequest.getClass().getMethod("getQaa", null).invoke(storkAuthnRequest, null); - - } - - } catch (ClassNotFoundException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | java.lang.SecurityException ex) { - - - } - - if (sp != null && sp.isSTORKPVPGateway()) { - //use PVP SecClass instead of STORK QAA level - String secClass = null; - if (storkRequstTemplate != null && - storkRequstTemplate.isInstance(target)) { - - try { - secClass = PVPtoSTORKMapper.getInstance().mapToSecClass( - PVPConstants.STORK_QAA_PREFIX + String.valueOf(storkSecClass)); - - } catch (Exception e) { - Logger.warn("STORK-QAA level can not read from STORK request. Use default QAA 4", e); - - } - } - - if (MiscUtil.isNotEmpty(secClass)) - authnClassRef.setAuthnContextClassRef(secClass); - else - authnClassRef.setAuthnContextClassRef("http://www.ref.gv.at/ns/names/agiz/pvp/secclass/0-3"); - - } else { - if (storkRequstTemplate != null && - storkRequstTemplate.isInstance(target)) { - //use requested QAA level from STORK request - try { - authnClassRef.setAuthnContextClassRef( - PVPConstants.STORK_QAA_PREFIX + String.valueOf(storkSecClass)); - Logger.debug("Use STORK-QAA level " + authnClassRef.getAuthnContextClassRef() - + " from STORK request"); - - } catch (Exception e) { - Logger.warn("STORK-QAA level can not read from STORK request. Use default QAA 4", e); - - } - - } - - if (MiscUtil.isEmpty(authnClassRef.getAuthnContextClassRef())) - //TODO: switch to eIDAS QAA-levels - authnClassRef.setAuthnContextClassRef("http://www.stork.gov.eu/1.0/citizenQAALevel/4"); - - } - - reqAuthContext.setComparison(AuthnContextComparisonTypeEnumeration.MINIMUM); - reqAuthContext.getAuthnContextClassRefs().add(authnClassRef); - authReq.setRequestedAuthnContext(reqAuthContext); - - IEncoder binding = null; - if (redirectEndpoint.getBinding().equals( - SAMLConstants.SAML2_REDIRECT_BINDING_URI)) { - binding = new RedirectBinding(); - - } else if (redirectEndpoint.getBinding().equals( - SAMLConstants.SAML2_POST_BINDING_URI)) { - binding = new PostBinding(); - - } - - binding.encodeRequest(request, response, authReq, - redirectEndpoint.getLocation(), target.getRequestID()); - - //build and send request without an error - requiredLocalAuthentication = false; - - MOAReversionLogger.getInstance().logEvent(target.getOnlineApplicationConfiguration(), - target, MOAIDEventConstants.AUTHPROCESS_INTERFEDERATION_IDP, idpEntity.getEntityID()); - - - } else { - Logger.warn("Requested IDP " + target.getRequestedIDP() - + " does not support POST or Redirect Binding."); - - } - - } else { - Logger.warn("Requested IDP " + target.getRequestedIDP() - + " is not found in InterFederation configuration"); - - } - - } catch (MetadataProviderException e) { - Logger.error("IDP metadata error." , e); - - } catch (NoSuchAlgorithmException e) { - Logger.error("Build IDP authentication request FAILED.", e); - - } catch (MessageEncodingException e) { - Logger.error("Build IDP authentication request FAILED.", e); - - } catch (SecurityException e) { - Logger.error("Build IDP authentication request FAILED.", e); - - } - - if (requiredLocalAuthentication) { - Logger.info("Switch to local authentication on this IDP ... "); - if (idp.isPerformLocalAuthenticationOnInterfederationError()) - perfomLocalAuthentication(request, response, target); - - else - throw new AuthenticationException("auth.29", new String[]{target.getRequestedIDP()}); - } - } - - - private void perfomLocalAuthentication(HttpServletRequest request, - HttpServletResponse response, IRequest target) - throws ServletException, IOException, MOAIDException { - Logger.debug("Starting authentication on this IDP ..."); - - 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); - - List<String> legacyallowed_prot = AuthConfigurationProviderFactory.getInstance().getLegacyAllowedProtocols(); - - //is legacy allowed - boolean legacyallowed = legacyallowed_prot.contains(target.requestedModule()); - - //check legacy request parameter - boolean legacyparamavail = ParamValidatorUtils.areAllLegacyParametersAvailable(request); - - AuthenticationSession moasession; - try { - //check if an MOASession exists and if not create an new MOASession - //moasession = getORCreateMOASession(request); - moasession = AuthenticationSessionStoreage.createSession(target); - - } catch (MOADatabaseException e1) { - Logger.error("Database Error! MOASession can not be created!"); - throw new MOAIDException("init.04", new Object[] {}); - } - - try { - - if (legacyallowed && legacyparamavail) { - - // create execution context - ExecutionContext executionContext = new ExecutionContextImpl(); - executionContext.put(MOAIDAuthConstants.PARAM_SESSIONID, moasession.getSessionID()); - executionContext.put("pendingRequestID", target.getRequestID()); - - executionContext.put("isLegacyRequest", true); - - Enumeration<String> reqParamNames = request.getParameterNames(); - while(reqParamNames.hasMoreElements()) { - String paramName = reqParamNames.nextElement(); - if (MiscUtil.isNotEmpty(paramName)) - executionContext.put(paramName, request.getParameter(paramName)); - - } - - // create process instance - String processDefinitionId = ModuleRegistration.getInstance().selectProcess(executionContext); - - if (processDefinitionId == null) { - Logger.warn("No suitable process found for SessionID " + moasession.getSessionID() ); - throw new MOAIDException("process.02",new Object[] { - moasession.getSessionID()}); - } - - String processInstanceId = processEngine.createProcessInstance(processDefinitionId, executionContext); - - // keep process instance id in moa session - moasession.setProcessInstanceId(processInstanceId); - - // make sure moa session has been persisted before running the process - try { - AuthenticationSessionStoreage.storeSession(moasession); - } catch (MOADatabaseException e) { - Logger.error("Database Error! MOASession is not stored!"); - throw new MOAIDException("init.04", new Object[] { - moasession.getSessionID()}); - } - - // start process - processEngine.start(processInstanceId); - - } else { - MOAReversionLogger.getInstance().logEvent(target.getOnlineApplicationConfiguration(), - target, MOAIDEventConstants.AUTHPROCESS_BKUSELECTION_INIT); - - //load Parameters from OnlineApplicationConfiguration - OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance() - .getOnlineApplicationParameter(target.getOAURL()); - - if (oaParam == null) { - throw new AuthenticationException("auth.00", new Object[] { target.getOAURL() }); - } - - else { - - //check if an MOASession exists and if not create an new MOASession - //moasession = getORCreateMOASession(request); - - //set OnlineApplication configuration in Session - moasession.setOAURLRequested(target.getOAURL()); - moasession.setAction(target.requestedAction()); - moasession.setModul(target.requestedModule()); - } - - //Build authentication form - - - String publicURLPreFix = target.getAuthURL(); - if (publicURLPreFix.endsWith("/")) - publicURLPreFix = publicURLPreFix.substring(0, publicURLPreFix.length() - 1); - String loginForm = LoginFormBuilder.buildLoginForm(target.requestedModule(), - target.requestedAction(), oaParam, publicURLPreFix, moasession.getSessionID()); - - //store MOASession - try { - AuthenticationSessionStoreage.storeSession(moasession, target.getRequestID()); - } catch (MOADatabaseException e) { - Logger.error("Database Error! MOASession is not stored!"); - throw new MOAIDException("init.04", new Object[] { - moasession.getSessionID()}); - } - - //set MOAIDSession - //request.getSession().setAttribute(MOA_SESSION, moasession.getSessionID()); - - response.setContentType("text/html;charset=UTF-8"); - PrintWriter out = new PrintWriter(response.getOutputStream()); - out.print(loginForm); - out.flush(); - } - } catch (ProcessExecutionException e) { - Throwable cause = e.getCause(); - if (cause != null && cause instanceof TaskExecutionException) { - Throwable taskCause = cause.getCause(); - if (taskCause != null && taskCause instanceof MOAIDException) { - MOAIDException moaTaskCause = (MOAIDException) taskCause; - Logger.warn(taskCause); - throw moaTaskCause; - - } - } - - throw new MOAIDException("process.01", new Object[] { moasession.getProcessInstanceId(), moasession }, e); - } - } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IAction.java index fda92d71a..ae2771427 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IAction.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IAction.java @@ -25,9 +25,8 @@ package at.gv.egovernment.moa.id.moduls; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.data.AuthenticationData; +import at.gv.egovernment.moa.id.commons.api.IRequest; +import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.data.SLOInformationInterface; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IModulInfo.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IModulInfo.java index bdbb1b458..b9b161bb6 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IModulInfo.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IModulInfo.java @@ -25,22 +25,14 @@ package at.gv.egovernment.moa.id.moduls; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.commons.api.IRequest; + public interface IModulInfo { //public List<ServletInfo> getServlets(); public String getName(); public String getPath(); - - public IAction getAction(String action); - - public IRequest preProcess(HttpServletRequest request, - HttpServletResponse response, String action, String sessionID, String transactionID) - throws MOAIDException; - - public IAction canHandleRequest(HttpServletRequest request, - HttpServletResponse response); - + public boolean generateErrorMessage(Throwable e, HttpServletRequest request, HttpServletResponse response, IRequest protocolRequest) throws Throwable; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IRequest.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IRequest.java deleted file mode 100644 index 4ae271bbc..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IRequest.java +++ /dev/null @@ -1,61 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.moduls; - -import java.util.Date; -import java.util.List; - -import org.opensaml.saml2.core.Attribute; - -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOAResponse; - -public interface IRequest { - public String getOAURL(); - public boolean isPassiv(); - public boolean forceAuth(); - public boolean isSSOSupported(); - public String requestedModule(); - public String requestedAction(); - public void setModule(String module); - public void setAction(String action); - public String getTarget(); - public void setRequestID(String id); - public String getRequestID(); - public String getSessionIdentifier(); - public void setSessionIdentifier(String sessionIdentifier); - public String getRequestedIDP(); - public MOAResponse getInterfederationResponse(); - public List<Attribute> getRequestedAttributes(); - public IOAAuthParameters getOnlineApplicationConfiguration(); - - /** - * get the IDP URL PreFix, which was used for authentication request - * - * @return IDP URL PreFix <String>. The URL prefix always ends without / - */ - public String getAuthURL(); - public String getAuthURLWithOutSlash(); - - //public void setTarget(); -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/ServletType.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IRequestStorage.java index c8fbfb558..987d92e16 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/ServletType.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IRequestStorage.java @@ -1,4 +1,4 @@ -/******************************************************************************* +/* * Copyright 2014 Federal Chancellery Austria * MOA-ID has been developed in a cooperation between BRZ, the Federal * Chancellery Austria - ICT staff unit, and Graz University of Technology. @@ -19,9 +19,25 @@ * file for details on the various modules and licenses. * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ + */ package at.gv.egovernment.moa.id.moduls; -public enum ServletType { - UNAUTH, AUTH, NONE +import at.gv.egovernment.moa.id.commons.api.IRequest; +import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; +import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; + +/** + * @author tlenz + * + */ +public interface IRequestStorage { + + public IRequest getPendingRequest(String pendingReqID); + + public void storePendingRequest(IRequest pendingRequest) throws MOAIDException; + + public void removePendingRequest(String requestID); + + public String changePendingRequestID(IRequest pendingRequest) throws MOAIDException, MOADatabaseException; + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/ModulStorage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/ModulStorage.java deleted file mode 100644 index e65d77326..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/ModulStorage.java +++ /dev/null @@ -1,94 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.moduls; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.ServiceLoader; - -import at.gv.egovernment.moa.logging.Logger; - -public class ModulStorage { - -// private static final String[] modulClasses = new String[]{ -//// "at.gv.egovernment.moa.id.protocols.saml1.SAML1Protocol", -// "at.gv.egovernment.moa.id.protocols.pvp2x.PVP2XProtocol", -// "at.gv.egovernment.moa.id.protocols.stork2.STORKProtocol", -// "at.gv.egovernment.moa.id.protocols.oauth20.protocol.OAuth20Protocol" -// }; - - private static ServiceLoader<IModulInfo> protocolModuleLoader = - ServiceLoader.load(IModulInfo.class); - private static List<IModulInfo> registeredModules = new ArrayList<IModulInfo>(); - - - public static List<IModulInfo> getAllModules() { - return registeredModules; - } - - public static IModulInfo getModuleByPath(String modname) { - Iterator<IModulInfo> it = registeredModules.iterator(); - while (it.hasNext()) { - IModulInfo info = it.next(); - if (info.getPath().equals(modname)) { - return info; - } - } - return null; - } - - static { - Logger.info("Loading protocol modules:"); - if (protocolModuleLoader != null ) { - Iterator<IModulInfo> moduleLoaderInterator = protocolModuleLoader.iterator(); - while (moduleLoaderInterator.hasNext()) { - try { - IModulInfo modul = moduleLoaderInterator.next(); - Logger.info("Loading Modul Information: " + modul.getName()); - registeredModules.add(modul); - - } catch(Throwable e) { - Logger.error("Check configuration! " + "Some protocol modul" + - " is not a valid IModulInfo", e); - } - } - } - -// for(int i = 0; i < modulClasses.length; i++) { -// String modulClassName = modulClasses[i]; -// try { -// @SuppressWarnings("unchecked") -// Class<IModulInfo> moduleClass = (Class<IModulInfo>)Class.forName(modulClassName); -// IModulInfo module = moduleClass.newInstance(); -// Logger.info("Loading Modul Information: " + module.getName()); -// registeredModules.add(module); -// } catch(Throwable e) { -// Logger.error("Check configuration! " + modulClassName + -// " is not a valid IModulInfo", e); -// } -// } - Logger.info("Loading modules done"); - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/ModulUtils.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/ModulUtils.java deleted file mode 100644 index 99b7f4217..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/ModulUtils.java +++ /dev/null @@ -1,46 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.moduls; - -import at.gv.egovernment.moa.id.entrypoints.DispatcherServlet; - - -public class ModulUtils { - - public static final String UNAUTHDISPATCHER = "dispatcher"; - public static final String AUTHDISPATCHER = "dispatcher"; - - public static String buildUnauthURL(String modul, String action, String pendingRequestID) { - return UNAUTHDISPATCHER + "?" + - DispatcherServlet.PARAM_TARGET_MODULE + "=" + modul + "&" + - DispatcherServlet.PARAM_TARGET_ACTION + "=" + action + "&" + - DispatcherServlet.PARAM_TARGET_PENDINGREQUESTID + "=" + pendingRequestID; - } - - public static String buildAuthURL(String modul, String action, String pendingRequestID) { - return AUTHDISPATCHER + - "?" + DispatcherServlet.PARAM_TARGET_MODULE + "=" + modul + "&" + - DispatcherServlet.PARAM_TARGET_ACTION + "=" + action + "&" + - DispatcherServlet.PARAM_TARGET_PENDINGREQUESTID + "=" + pendingRequestID; - } -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/NoPassivAuthenticationException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/NoPassivAuthenticationException.java index 6551b88a3..f1db466e9 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/NoPassivAuthenticationException.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/NoPassivAuthenticationException.java @@ -22,7 +22,7 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.moduls; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; public class NoPassivAuthenticationException extends MOAIDException { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java index cdaade1bb..85e4dc99b 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java @@ -25,45 +25,80 @@ package at.gv.egovernment.moa.id.moduls; import java.io.Serializable; import java.net.MalformedURLException; import java.net.URL; +import java.util.Collection; +import java.util.HashMap; import java.util.List; +import java.util.Map; import javax.servlet.http.HttpServletRequest; -import org.opensaml.saml2.core.Attribute; - -import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; +import at.gv.egovernment.moa.id.advancedlogging.TransactionIDUtils; +import at.gv.egovernment.moa.id.commons.MOAIDConstants; +import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; +import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; +import at.gv.egovernment.moa.id.commons.api.IRequest; +import at.gv.egovernment.moa.id.commons.api.exceptions.ConfigurationException; +import at.gv.egovernment.moa.id.commons.api.exceptions.SessionDataStorageException; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOAResponse; import at.gv.egovernment.moa.id.util.HTTPUtils; +import at.gv.egovernment.moa.id.util.Random; import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.MiscUtil; public abstract class RequestImpl implements IRequest, Serializable{ - private static final long serialVersionUID = 1L; + public static final String DATAID_INTERFEDERATIOIDP_URL = "interIDPURL"; + public static final String DATAID_INTERFEDERATIOIDP_RESPONSE = "interIDPResponse"; + public static final String DATAID_REQUESTED_ATTRIBUTES = "requestedAttributes"; + public static final String DATAID_INTERFEDERATIOIDP_ENTITYID = "interIDPEntityID"; - private String oaURL; - private boolean passiv = false; - private boolean force = false; - private boolean ssosupport = false; + public static final String eIDAS_GENERIC_REQ_DATA_COUNTRY = "country"; + + private static final long serialVersionUID = 1L; + private String module = null; private String action = null; - private String target = null; + private String requestID; - private String sessionIdentifier; - private IOAAuthParameters OAConfiguration = null; + private String moaSessionIdentifier; + private String processInstanceId; + + private String uniqueTransactionIdentifer; + private String uniqueSessionIdentifer; + + private String oaURL; private String authURL = null; + + private IOAAuthParameters OAConfiguration = null; + + private boolean passiv = false; + private boolean force = false; + private boolean needSSO = false; + private boolean isAbortedByUser = false; + + //every request needs authentication by default + private boolean needAuthentication = true; - //MOA-ID interfederation - private String requestedIDP = null; - private MOAResponse response = null; + //every request is not authenticated by default + private boolean isAuthenticated = false; + + private Map<String, Object> genericDataStorage = new HashMap<String, Object>(); + /** * @throws ConfigurationException * */ - public RequestImpl(HttpServletRequest req) throws ConfigurationException { + public final void initialize(HttpServletRequest req) throws ConfigurationException { + //set requestID + requestID = Random.nextRandom(); + + //set unique transaction identifier for logging + uniqueTransactionIdentifer = Random.nextRandom(); + TransactionIDUtils.setTransactionId(uniqueTransactionIdentifer); + + + //check if End-Point is valid String authURLString = HTTPUtils.extractAuthURLFromRequest(req); URL authURL; try { @@ -122,15 +157,24 @@ public abstract class RequestImpl implements IRequest, Serializable{ this.authURL = resultURL.toExternalForm(); } - } + } + + //set unique session identifier + String uniqueID = (String) req.getAttribute(MOAIDConstants.UNIQUESESSIONIDENTIFIER); + if (MiscUtil.isNotEmpty(uniqueID)) + uniqueSessionIdentifer = uniqueID; + + else + Logger.warn("No unique session-identifier FOUND, but it should be allready set into request!?!"); + } /** * This method map the protocol specific requested attributes to PVP 2.1 attributes. * - * @return List of PVP 2.1 attributes with maps all protocol specific attributes + * @return List of PVP 2.1 attribute names with maps all protocol specific attributes */ - public abstract List<Attribute> getRequestedAttributes(); + public abstract Collection<String> getRequestedAttributes(); public void setOAURL(String value) { oaURL = value; @@ -156,83 +200,44 @@ public abstract class RequestImpl implements IRequest, Serializable{ this.force = force; } - public boolean isSSOSupported() { - return ssosupport; - } - - public String requestedModule() { - return module; - } - public String requestedAction() { return action; } - public void setSsosupport(boolean ssosupport) { - this.ssosupport = ssosupport; - } - - public void setModule(String module) { - this.module = module; - } - public void setAction(String action) { this.action = action; } - - public String getTarget() { - return target; - } - public void setTarget(String target) { - this.target = target; - } - - public void setRequestID(String id) { - this.requestID = id; - - } - - public String getRequestID() { - return requestID; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IRequest#getRequestedIDP() + /** + * @return the module */ - @Override - public String getRequestedIDP() { - return requestedIDP; + public String requestedModule() { + return module; } /** - * @param requestedIDP the requestedIDP to set + * @param module the module to set */ - public void setRequestedIDP(String requestedIDP) { - this.requestedIDP = requestedIDP; + public void setModule(String module) { + this.module = module; } - /** - * @return the response - */ - public MOAResponse getInterfederationResponse() { - return response; + public void setRequestID(String id) { + this.requestID = id; + } - /** - * @param response the response to set - */ - public void setInterfederationResponse(MOAResponse response) { - this.response = response; + public String getRequestID() { + return requestID; } - public String getSessionIdentifier() { - return this.sessionIdentifier; + public String getMOASessionIdentifier() { + return this.moaSessionIdentifier; } - public void setSessionIdentifier(String sessionIdentifier) { - this.sessionIdentifier = sessionIdentifier; + public void setMOASessionIdentifier(String moaSessionIdentifier) { + this.moaSessionIdentifier = moaSessionIdentifier; } @@ -246,6 +251,36 @@ public abstract class RequestImpl implements IRequest, Serializable{ } + public String getUniqueTransactionIdentifier() { + return this.uniqueTransactionIdentifer; + + } + + public String getUniqueSessionIdentifier() { + return this.uniqueSessionIdentifer; + + } + + public String getProcessInstanceId() { + return this.processInstanceId; + + } + + public void setUniqueTransactionIdentifier(String id) { + this.uniqueTransactionIdentifer = id; + + } + + public void setUniqueSessionIdentifier(String id) { + this.uniqueSessionIdentifer = id; + + } + + public void setProcessInstanceId(String id) { + this.processInstanceId = id; + + } + /** * @return the authURL */ @@ -261,11 +296,108 @@ public abstract class RequestImpl implements IRequest, Serializable{ } -// /** -// * @param authURL the authURL to set -// */ -// public void setAuthURL(String authURL) { -// this.authURL = authURL; -// } + /** + * @return the needAuthentication + */ + public boolean isNeedAuthentication() { + return needAuthentication; + } + + /** + * @param needAuthentication the needAuthentication to set + */ + public void setNeedAuthentication(boolean needAuthentication) { + this.needAuthentication = needAuthentication; + } + + /** + * @return the isAuthenticated + */ + public boolean isAuthenticated() { + return isAuthenticated; + } + + /** + * @param isAuthenticated the isAuthenticated to set + */ + public void setAuthenticated(boolean isAuthenticated) { + this.isAuthenticated = isAuthenticated; + } + + public boolean needSingleSignOnFunctionality() { + return needSSO; + } + public void setNeedSingleSignOnFunctionality(boolean needSSO) { + this.needSSO = needSSO; + + } + + public boolean isAbortedByUser() { + return this.isAbortedByUser; + } + + public void setAbortedByUser(boolean isAborted) { + this.isAbortedByUser = isAborted; + + } + + public Object getGenericData(String key) { + if (MiscUtil.isNotEmpty(key)) { + return genericDataStorage.get(key); + + } + + Logger.warn("Can not load generic request-data with key='null'"); + return null; + } + + public <T> T getGenericData(String key, final Class<T> clazz) { + if (MiscUtil.isNotEmpty(key)) { + Object data = genericDataStorage.get(key); + + if (data == null) + return null; + + try { + @SuppressWarnings("unchecked") + T test = (T) data; + return test; + + } catch (Exception e) { + Logger.warn("Generic request-data object can not be casted to requested type", e); + return null; + + } + + } + + Logger.warn("Can not load generic request-data with key='null'"); + return null; + + } + + public void setGenericDataToSession(String key, Object object) throws SessionDataStorageException { + if (MiscUtil.isEmpty(key)) { + Logger.warn("Generic request-data can not be stored with a 'null' key"); + throw new SessionDataStorageException("Generic request-data can not be stored with a 'null' key", null); + + } + + if (object != null) { + if (!Serializable.class.isInstance(object)) { + Logger.warn("Generic request-data can only store objects which implements the 'Seralizable' interface"); + throw new SessionDataStorageException("Generic request-data can only store objects which implements the 'Seralizable' interface", null); + + } + } + + if (genericDataStorage.containsKey(key)) + Logger.debug("Overwrite generic request-data with key:" + key); + else + Logger.trace("Add generic request-data with key:" + key + " to session."); + + genericDataStorage.put(key, object); + + } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestStorage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestStorage.java index f0b12431a..1b550881e 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestStorage.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestStorage.java @@ -22,39 +22,53 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.moduls; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + import at.gv.egovernment.moa.id.advancedlogging.TransactionIDUtils; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.commons.api.IRequest; +import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.storage.AssertionStorage; +import at.gv.egovernment.moa.id.process.dao.ProcessInstanceStoreDAO; +import at.gv.egovernment.moa.id.storage.ITransactionStorage; +import at.gv.egovernment.moa.id.util.Random; import at.gv.egovernment.moa.logging.Logger; -public class RequestStorage { +@Service("RequestStorage") +public class RequestStorage implements IRequestStorage{ - public static IRequest getPendingRequest(String pendingReqID) { + @Autowired ITransactionStorage transactionStorage; + @Autowired ProcessInstanceStoreDAO processInstanceStore; + + @Override + public IRequest getPendingRequest(String pendingReqID) { try { - AssertionStorage storage = AssertionStorage.getInstance(); - IRequest pendingRequest = storage.get(pendingReqID, IRequest.class); - + IRequest pendingRequest = transactionStorage.get(pendingReqID, IRequest.class); + if (pendingRequest == null) { + Logger.info("No PendingRequst found with pendingRequestID " + pendingReqID); + return null; + + } + //set transactionID and sessionID to Logger - TransactionIDUtils.setTransactionId(((IRequest)pendingRequest).getRequestID()); - TransactionIDUtils.setSessionId(((IRequest)pendingRequest).getSessionIdentifier()); + TransactionIDUtils.setTransactionId(pendingRequest.getUniqueTransactionIdentifier()); + TransactionIDUtils.setSessionId(pendingRequest.getUniqueSessionIdentifier()); return pendingRequest; - } catch (MOADatabaseException e) { + } catch (MOADatabaseException | NullPointerException e) { Logger.info("No PendingRequst found with pendingRequestID " + pendingReqID); return null; } } - public static void setPendingRequest(Object pendingRequest) throws MOAIDException { - try { - AssertionStorage storage = AssertionStorage.getInstance(); - + @Override + public void storePendingRequest(IRequest pendingRequest) throws MOAIDException { + try { if (pendingRequest instanceof IRequest) { - storage.put(((IRequest)pendingRequest).getRequestID(), pendingRequest); + transactionStorage.put(((IRequest)pendingRequest).getRequestID(), pendingRequest); } else { throw new MOAIDException("auth.20", null); @@ -69,12 +83,53 @@ public class RequestStorage { } - public static void removePendingRequest(String requestID) { + @Override + public void removePendingRequest(String requestID) { if (requestID != null) { - AssertionStorage storage = AssertionStorage.getInstance(); - storage.remove(requestID); + //remove process-management execution instance + try { + IRequest pendingReq = getPendingRequest(requestID); + + if (pendingReq != null && + pendingReq.getProcessInstanceId() != null) { + processInstanceStore.remove(pendingReq.getProcessInstanceId()); + + } + + } catch (MOADatabaseException e) { + Logger.warn("Removing process associated with pending-request:" + requestID + " FAILED.", e); + + } + + transactionStorage.remove(requestID); + + } + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.storage.IRequestStorage#changePendingRequestID(at.gv.egovernment.moa.id.moduls.IRequest) + */ + @Override + public String changePendingRequestID(IRequest pendingRequest) throws MOAIDException, MOADatabaseException { + + if (pendingRequest instanceof RequestImpl) { + String newRequestID = Random.nextRandom(); + String oldRequestID = pendingRequest.getRequestID(); + + Logger.debug("Change pendingRequestID from " + pendingRequest.getRequestID() + + " to " + newRequestID); + + ((RequestImpl)pendingRequest).setRequestID(newRequestID); + transactionStorage.changeKey(oldRequestID, newRequestID, pendingRequest); + + return newRequestID; + + } else { + Logger.error("PendingRequest object is not of type 'RequestImpl.class'"); + throw new MOAIDException("internal.00", null); } + } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/SSOManager.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/SSOManager.java index 2a618272f..bc7dd272b 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/SSOManager.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/SSOManager.java @@ -22,13 +22,6 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.moduls; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.StringWriter; -import java.net.URI; import java.util.Date; import java.util.List; @@ -36,56 +29,59 @@ import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.apache.velocity.VelocityContext; -import org.apache.velocity.app.VelocityEngine; import org.hibernate.Query; import org.hibernate.Session; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.data.AuthenticationSessionExtensions; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.commons.MOAIDAuthConstants; +import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; +import at.gv.egovernment.moa.id.commons.api.IRequest; +import at.gv.egovernment.moa.id.commons.api.exceptions.ConfigurationException; +import at.gv.egovernment.moa.id.commons.api.exceptions.SessionDataStorageException; import at.gv.egovernment.moa.id.commons.db.MOASessionDBUtils; import at.gv.egovernment.moa.id.commons.db.dao.session.AuthenticatedSessionStore; import at.gv.egovernment.moa.id.commons.db.dao.session.InterfederationSessionStore; import at.gv.egovernment.moa.id.commons.db.dao.session.OldSSOSessionIDStore; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; import at.gv.egovernment.moa.id.util.Random; -import at.gv.egovernment.moa.id.util.VelocityProvider; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; -public class SSOManager { - +@Service("MOAID_SSOManager") +public class SSOManager { private static final String HTMLTEMPLATESDIR = "htmlTemplates/"; private static final String HTMLTEMPLATEFULL = "slo_template.html"; + public static String CONTEXTPATH = "contextPath"; private static final String SSOCOOKIE = "MOA_ID_SSO"; private static final String SSOINTERFEDERATION = "MOA_INTERFEDERATION_SSO"; - private static final int DEFAULTSSOTIMEOUT = 15 * 60; // sec - private static final int INTERFEDERATIONCOOKIEMAXAGE = 5 * 60;// sec + + @Autowired private IAuthenticationSessionStoreage authenticatedSessionStore; + @Autowired protected AuthConfiguration authConfig; - private static SSOManager instance = null; - - public static SSOManager getInstance() { - if (instance == null) { - instance = new SSOManager(); - - } - - return instance; - } - + /** + * Check if interfederation IDP is requested via HTTP GET parameter or if interfederation cookie exists. + * Set the requested interfederation IDP as attribte of the {protocolRequest} + * + * @param httpReq HttpServletRequest + * @param httpResp HttpServletResponse + * @param protocolRequest Authentication request which is actually in process + * @throws SessionDataStorageException + * + **/ public void checkInterfederationIsRequested(HttpServletRequest httpReq, HttpServletResponse httpResp, - IRequest protocolRequest) { + IRequest protocolRequest) throws SessionDataStorageException { String interIDP = httpReq.getParameter(MOAIDAuthConstants.INTERFEDERATION_IDP); - if (MiscUtil.isNotEmpty(protocolRequest.getRequestedIDP())) { - Logger.debug("Protocolspecific preprocessing already set interfederation IDP " + protocolRequest.getRequestedIDP()); + String interfederationIDP = + protocolRequest.getGenericData(RequestImpl.DATAID_INTERFEDERATIOIDP_URL, String.class); + if (MiscUtil.isNotEmpty(interfederationIDP)) { + Logger.debug("Protocolspecific preprocessing already set interfederation IDP " + interfederationIDP); return; } @@ -95,14 +91,14 @@ public class SSOManager { RequestImpl moaReq = (RequestImpl) protocolRequest; if (MiscUtil.isNotEmpty(interIDP)) { Logger.info("Receive SSO request for interfederation IDP " + interIDP); - moaReq.setRequestedIDP(interIDP); + moaReq.setGenericDataToSession(RequestImpl.DATAID_INTERFEDERATIOIDP_URL, interIDP); } else { //check if IDP cookie is set String cookie = getValueFromCookie(httpReq, SSOINTERFEDERATION); if (MiscUtil.isNotEmpty(cookie)) { Logger.info("Receive SSO request for interfederated IDP from Cookie " + cookie); - moaReq.setRequestedIDP(cookie); + moaReq.setGenericDataToSession(RequestImpl.DATAID_INTERFEDERATIOIDP_URL, cookie); deleteCookie(httpReq, httpResp, SSOINTERFEDERATION); } @@ -120,7 +116,7 @@ public class SSOManager { } - public boolean isValidSSOSession(String ssoSessionID, IRequest protocolRequest) throws ConfigurationException { + public boolean isValidSSOSession(String ssoSessionID, IRequest protocolRequest) throws ConfigurationException, SessionDataStorageException { // search SSO Session if (ssoSessionID == null) { @@ -128,7 +124,7 @@ public class SSOManager { return false; } - AuthenticatedSessionStore storedSession = AuthenticationSessionStoreage.isValidSessionWithSSOID(ssoSessionID, null); + AuthenticatedSessionStore storedSession = authenticatedSessionStore.isValidSessionWithSSOID(ssoSessionID); if (storedSession == null) return false; @@ -137,25 +133,29 @@ public class SSOManager { //check if session is out of lifetime Date now = new Date(); - long maxSSOSessionTime = AuthConfigurationProviderFactory.getInstance().getSSOCreatedTimeOut() * 1000; + long maxSSOSessionTime = authConfig.getSSOCreatedTimeOut() * 1000; Date ssoSessionValidTo = new Date(storedSession.getCreated().getTime() + maxSSOSessionTime); if (now.after(ssoSessionValidTo)) { Logger.info("Found outdated SSO session information. Start reauthentication process ... "); return false; } - //check if request starts an interfederated SSO session + //check if stored SSO session is a federated SSO session if (protocolRequest != null && - protocolRequest instanceof RequestImpl && - storedSession.isInterfederatedSSOSession() && - !storedSession.isAuthenticated()) { - - if (MiscUtil.isEmpty(((RequestImpl) protocolRequest).getRequestedIDP())) { - InterfederationSessionStore selectedIDP = AuthenticationSessionStoreage.searchInterfederatedIDPFORSSOWithMOASession(storedSession.getSessionid()); + storedSession.isInterfederatedSSOSession()) { + //in case of federated SSO session, jump to federated IDP for authentication + + String interfederationIDP = + protocolRequest.getGenericData(RequestImpl.DATAID_INTERFEDERATIOIDP_URL, String.class); + + if (MiscUtil.isEmpty(interfederationIDP)) { + InterfederationSessionStore selectedIDP = authenticatedSessionStore.searchInterfederatedIDPFORSSOWithMOASession(storedSession.getSessionid()); if (selectedIDP != null) { //no local SSO session exist -> request interfederated IDP - ((RequestImpl) protocolRequest).setRequestedIDP(selectedIDP.getIdpurlprefix()); + Logger.info("SSO Session refer to federated IDP: " + selectedIDP.getIdpurlprefix()); + protocolRequest.setGenericDataToSession( + RequestImpl.DATAID_INTERFEDERATIOIDP_URL, selectedIDP.getIdpurlprefix()); } else { Logger.warn("MOASession is marked as interfederated SSO session but no interfederated IDP is found. Switch to local authentication ..."); @@ -174,16 +174,17 @@ public class SSOManager { } public String getMOASession(String ssoSessionID) { - return AuthenticationSessionStoreage.getMOASessionSSOID(ssoSessionID); + return authenticatedSessionStore.getMOASessionSSOID(ssoSessionID); } + //TODO: refactor for faster DB access public String getUniqueSessionIdentifier(String ssoSessionID) { try { if (MiscUtil.isNotEmpty(ssoSessionID)) { - String moaSessionID = AuthenticationSessionStoreage.getMOASessionSSOID(ssoSessionID); + String moaSessionID = authenticatedSessionStore.getMOASessionSSOID(ssoSessionID); if (MiscUtil.isNotEmpty(moaSessionID)) { - AuthenticationSessionExtensions extSessionInformation = AuthenticationSessionStoreage.getAuthenticationSessionExtensions(moaSessionID); + AuthenticationSessionExtensions extSessionInformation = authenticatedSessionStore.getAuthenticationSessionExtensions(moaSessionID); return extSessionInformation.getUniqueSessionId(); } @@ -253,14 +254,6 @@ public class SSOManager { } public void setSSOSessionID(HttpServletRequest httpReq, HttpServletResponse httpResp, String ssoId) { - int ssoTimeOut; - try { - ssoTimeOut = (int) AuthConfigurationProviderFactory.getInstance().getSSOCreatedTimeOut(); - - } catch (ConfigurationException e) { - Logger.info("SSO Timeout can not be loaded from MOA-ID configuration. Use default Timeout with " + DEFAULTSSOTIMEOUT); - ssoTimeOut = DEFAULTSSOTIMEOUT; - } setCookie(httpReq, httpResp, SSOCOOKIE, ssoId, -1); } @@ -285,12 +278,12 @@ public class SSOManager { if (MiscUtil.isNotEmpty(ssoSessionID)) { - AuthenticatedSessionStore storedSession = AuthenticationSessionStoreage.isValidSessionWithSSOID(ssoSessionID, null); + AuthenticatedSessionStore storedSession = authenticatedSessionStore.isValidSessionWithSSOID(ssoSessionID); if (storedSession == null) return false; - InterfederationSessionStore selectedIDP = AuthenticationSessionStoreage.searchInterfederatedIDPFORSSOWithMOASessionIDPID(storedSession.getSessionid(), entityID); + InterfederationSessionStore selectedIDP = authenticatedSessionStore.searchInterfederatedIDPFORSSOWithMOASessionIDPID(storedSession.getSessionid(), entityID); if (selectedIDP != null) { //no local SSO session exist -> request interfederated IDP @@ -309,68 +302,7 @@ public class SSOManager { return false; } - - public void printSingleLogOutInfo(VelocityContext context, HttpServletResponse httpResp) throws MOAIDException { - try { - Logger.trace("Initialize VelocityEngine..."); - - InputStream is = null; - String pathLocation = null; - try { - String rootconfigdir = AuthConfigurationProviderFactory.getInstance().getRootConfigFileDir(); - pathLocation = rootconfigdir + HTMLTEMPLATESDIR + HTMLTEMPLATEFULL; - File file = new File(new URI(pathLocation)); - is = new FileInputStream(file); - evaluateSLOTemplate(context, httpResp, is); - - } catch (Exception e) { - Logger.warn("SLO Template is not found in configuration directory (" + - pathLocation + "). Load template from project library ... "); - - try { - pathLocation = "resources/templates/" + HTMLTEMPLATEFULL; - is = Thread.currentThread() - .getContextClassLoader() - .getResourceAsStream(pathLocation); - evaluateSLOTemplate(context, httpResp, is); - - } catch (Exception e1) { - Logger.error("Single LogOut form can not created.", e); - throw new MOAIDException("Create Single LogOut information FAILED.", null, e); - } - - } finally { - if (is != null) - is.close(); - - } - - } catch (Exception e) { - Logger.error("Single LogOut form can not created.", e); - throw new MOAIDException("Create Single LogOut information FAILED.", null, e); - } - } - - private void evaluateSLOTemplate(VelocityContext context, HttpServletResponse httpResp, InputStream is) throws Exception { - - VelocityEngine engine = VelocityProvider.getClassPathVelocityEngine(); - - BufferedReader reader = new BufferedReader(new InputStreamReader(is )); - - //set default elements to velocity context - context.put("contextpath", AuthConfigurationProviderFactory.getInstance().getPublicURLPrefix()); - - StringWriter writer = new StringWriter(); - //velocityEngine.evaluate(context, writer, "SLO_Template", reader); - engine.evaluate(context, writer, "SLO Template", reader); - - - httpResp.setContentType("text/html;charset=UTF-8"); - httpResp.getOutputStream().write(writer.toString().getBytes("UTF-8")); - - } - private String getValueFromCookie(HttpServletRequest httpReq, String cookieName) { Cookie[] cookies = httpReq.getCookies(); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/ServletInfo.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/ServletInfo.java deleted file mode 100644 index 807f789ce..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/ServletInfo.java +++ /dev/null @@ -1,53 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.moduls; - -import javax.servlet.http.HttpServlet; - - -public class ServletInfo { - Class<? extends HttpServlet> servletClass; - String servletTarget; - ServletType type; - - public ServletInfo(Class<? extends HttpServlet> servletClass, - String servletTarget, ServletType type) { - super(); - this.servletClass = servletClass; - this.servletTarget = servletTarget; - this.type = type; - } - - public HttpServlet getServletInstance() - throws InstantiationException, IllegalAccessException { - return servletClass.newInstance(); - } - - public String getTarget() { - return servletTarget; - } - - public ServletType getType() { - return type; - } -} |