diff options
Diffstat (limited to 'id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls')
9 files changed, 781 insertions, 622 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..b6df5e5c6 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 @@ -24,8 +24,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; @@ -38,39 +36,21 @@ 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.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.modules.TaskExecutionException; @@ -78,93 +58,93 @@ import at.gv.egovernment.moa.id.auth.modules.registration.ModuleRegistration; 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.config.auth.AuthConfiguration; +import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; 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.TrustEngineFactory; -import at.gv.egovernment.moa.id.storage.AssertionStorage; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.storage.ITransactionStorage; import at.gv.egovernment.moa.id.util.MOAIDMessageProvider; -import at.gv.egovernment.moa.id.util.PVPtoSTORKMapper; 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; + @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; - private AuthenticationManager() { - } - - public static AuthenticationManager getInstance() { - return INSTANCE; + public AuthenticationManager() { + } - + /** - * Checks if this request can authenticate a MOA Session + * 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 MOASession exists * - * @param request - * @param response - * @return + * @return true if session is already authenticated, otherwise false + * @throws MOAIDException */ - public boolean tryPerformAuthentication(HttpServletRequest request, - HttpServletResponse response) { - - 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 - } - } + private boolean tryPerformAuthentication(RequestImpl protocolRequest, AuthenticationSession moaSession) { + + //if no MOASession exist -> authentication is required + if (moaSession == null) { + return false; - } catch (MOADatabaseException e) { - return false; - } catch (BuildException e) { + } 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, @@ -193,11 +173,9 @@ public class AuthenticationManager extends MOAIDAuthConstants { } - SSOManager ssomanager = SSOManager.getInstance(); - //store active OAs to SLOContaine - List<OASessionStore> dbOAs = AuthenticationSessionStoreage.getAllActiveOAFromMOASession(session); - List<InterfederationSessionStore> dbIDPs = AuthenticationSessionStoreage.getAllActiveIDPsFromMOASession(session); + List<OASessionStore> dbOAs = authenticatedSessionStore.getAllActiveOAFromMOASession(session); + List<InterfederationSessionStore> dbIDPs = authenticatedSessionStore.getAllActiveIDPsFromMOASession(session); SLOInformationContainer sloContainer = new SLOInformationContainer(); sloContainer.setSloRequest(pvpReq); sloContainer.parseActiveIDPs(dbIDPs, pvpSLOIssuer); @@ -205,8 +183,8 @@ public class AuthenticationManager extends MOAIDAuthConstants { //terminate MOASession try { - AuthenticationSessionStoreage.destroySession(session.getSessionID()); - ssomanager.deleteSSOSessionID(httpReq, httpResp); + authenticatedSessionStore.destroySession(session.getSessionID()); + ssoManager.deleteSSOSessionID(httpReq, httpResp); } catch (MOADatabaseException e) { Logger.warn("Delete MOASession FAILED."); @@ -276,7 +254,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(); @@ -289,7 +268,7 @@ public class AuthenticationManager extends MOAIDAuthConstants { context.put("redirectURLs", sloReqList); context.put("timeoutURL", timeOutURL); context.put("timeout", SLOTIMEOUT); - ssomanager.printSingleLogOutInfo(context, httpResp); + ssoManager.printSingleLogOutInfo(context, httpResp); } else { @@ -309,7 +288,7 @@ public class AuthenticationManager extends MOAIDAuthConstants { else context.put("errorMsg", MOAIDMessageProvider.getInstance().getMessage("slo.01", null)); - ssomanager.printSingleLogOutInfo(context, httpResp); + ssoManager.printSingleLogOutInfo(context, httpResp); } @@ -327,7 +306,7 @@ public class AuthenticationManager extends MOAIDAuthConstants { VelocityContext context = new VelocityContext(); context.put("errorMsg", MOAIDMessageProvider.getInstance().getMessage("slo.01", null)); - ssomanager.printSingleLogOutInfo(context, httpResp); + ssoManager.printSingleLogOutInfo(context, httpResp); } @@ -352,8 +331,7 @@ public class AuthenticationManager extends MOAIDAuthConstants { AuthenticationSession authSession; try { - authSession = AuthenticationSessionStoreage - .getSession(moaSessionID); + authSession = authenticatedSessionStore.getSession(moaSessionID); if(authSession == null) { Logger.info("NO MOA Authentication data for ID " + moaSessionID); @@ -364,10 +342,10 @@ public class AuthenticationManager extends MOAIDAuthConstants { //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()); + AuthenticationSessionExtensions sessionExtensions = authenticatedSessionStore.getAuthenticationSessionExtensions(moaSessionID); + revisionsLogger.logEvent(MOAIDEventConstants.SESSION_DESTROYED, sessionExtensions.getUniqueSessionId()); - AuthenticationSessionStoreage.destroySession(moaSessionID); + authenticatedSessionStore.destroySession(moaSessionID); //session.invalidate(); @@ -378,366 +356,209 @@ public class AuthenticationManager extends MOAIDAuthConstants { } - 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(); - } + /** + * 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 + * + */ + public AuthenticationSession doAuthentication(HttpServletRequest httpReq, + HttpServletResponse httpResp, RequestImpl pendingReq) throws MOADatabaseException, ServletException, IOException, MOAIDException { - private void buildPVP21AuthenticationRequest(HttpServletRequest request, - HttpServletResponse response, IRequest target) - throws ServletException, IOException, MOAIDException { - - boolean requiredLocalAuthentication = true; + //generic authentication request validation + if (pendingReq.isPassiv() + && pendingReq.forceAuth()) { + // conflict! + throw new NoPassivAuthenticationException(); + } + + //get SSO cookie from http request + String ssoId = ssoManager.getSSOSessionID(httpReq); - Logger.debug("Build PVP 2.1 authentication request"); - - //get IDP metadata + //check if interfederation IDP is requested + ssoManager.checkInterfederationIsRequested(httpReq, httpResp, pendingReq); - 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; - - } + //check SSO session + if (ssoId != null) { + String correspondingMOASession = ssoManager.existsOldSSOSession(ssoId); - try { - EntityDescriptor idpEntity = MOAMetadataProvider.getInstance(). - getEntityDescriptor(target.getRequestedIDP()); - - if (idpEntity != null ) { + if (correspondingMOASession != null) { + Logger.warn("Request sends an old SSO Session ID("+ssoId+")! " + + "Invalidate the corresponding MOASession with ID="+ correspondingMOASession); - //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"); + revisionsLogger.logEvent(pendingReq.getOnlineApplicationConfiguration(), + pendingReq, MOAIDEventConstants.AUTHPROCESS_SSO_INVALID); + authenticatedSessionStore.destroySession(correspondingMOASession); + ssoManager.deleteSSOSessionID(httpReq, httpResp); } + } + + // 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 Session is valid + boolean isValidSSOSession = ssoManager.isValidSSOSession(ssoId, pendingReq); + + //check if SSO is allowed for the actually executed request + boolean isSSOAllowed = (useSSOOA && !isUseMandateRequested); + pendingReq.setNeedSingleSignOnFunctionality(isSSOAllowed); - } 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); + //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 tryperform = tryPerformAuthentication((RequestImpl) pendingReq, moaSession); - if (requiredLocalAuthentication) { - Logger.info("Switch to local authentication on this IDP ... "); - if (idp.isPerformLocalAuthenticationOnInterfederationError()) - perfomLocalAuthentication(request, response, target); + //perfom SSO-Consents question if it it required + if (tryperform && isSSOAllowed && oaParam.useSSOQuestion()) { + sendTransmitAssertionQuestion(httpReq, httpResp, pendingReq, oaParam); + return null; - else - throw new AuthenticationException("auth.29", new String[]{target.getRequestedIDP()}); } + + //force new authentication authentication process + if (pendingReq.forceAuth()) { + startAuthenticationProcess(httpReq, httpResp, pendingReq); + return null; + + } else if (pendingReq.isPassiv()) { + if (tryperform) { + // Passive authentication ok! + revisionsLogger.logEvent(oaParam, + pendingReq, MOAIDEventConstants.AUTHPROCESS_FINISHED); + return moaSession; + + } else { + throw new NoPassivAuthenticationException(); + + } + } else { + if (tryperform) { + // Is authenticated .. proceed + revisionsLogger.logEvent(oaParam, + pendingReq, MOAIDEventConstants.AUTHPROCESS_FINISHED); + return moaSession; + + } else { + // Start authentication! + startAuthenticationProcess(httpReq, httpResp, pendingReq); + return null; + } + } } - private void perfomLocalAuthentication(HttpServletRequest request, - HttpServletResponse response, IRequest target) + private void startAuthenticationProcess(HttpServletRequest httpReq, + HttpServletResponse httpResp, RequestImpl pendingReq) 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); + + Logger.info("Starting authentication ..."); + revisionsLogger.logEvent(pendingReq.getOnlineApplicationConfiguration(), + pendingReq, MOAIDEventConstants.AUTHPROCESS_START); - List<String> legacyallowed_prot = AuthConfigurationProviderFactory.getInstance().getLegacyAllowedProtocols(); - - //is legacy allowed - boolean legacyallowed = legacyallowed_prot.contains(target.requestedModule()); + //is legacy allowed + List<String> legacyallowed_prot = authConfig.getLegacyAllowedProtocols(); + boolean legacyallowed = legacyallowed_prot.contains(pendingReq.requestedModule()); //check legacy request parameter - boolean legacyparamavail = ParamValidatorUtils.areAllLegacyParametersAvailable(request); + boolean legacyparamavail = ParamValidatorUtils.areAllLegacyParametersAvailable(httpReq); + //create MOASession object AuthenticationSession moasession; try { - //check if an MOASession exists and if not create an new MOASession - //moasession = getORCreateMOASession(request); - moasession = AuthenticationSessionStoreage.createSession(target); + moasession = authenticatedSessionStore.createSession(pendingReq); } catch (MOADatabaseException e1) { Logger.error("Database Error! MOASession can not be created!"); throw new MOAIDException("init.04", new Object[] {}); + } + //create authentication process execution context try { + // create execution context + ExecutionContext executionContext = new ExecutionContextImpl(); + executionContext.put(MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID, pendingReq.getRequestID()); + executionContext.put(MOAIDAuthConstants.PROCESSCONTEXT_INTERFEDERATION_ENTITYID, + MiscUtil.isNotEmpty( + pendingReq.getGenericData(RequestImpl.DATAID_INTERFEDERATIOIDP_URL, String.class))); - 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(); + boolean leagacyMode = (legacyallowed && legacyparamavail); + executionContext.put("isLegacyRequest", leagacyMode); + executionContext.put("performBKUSelection", 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)) - executionContext.put(paramName, request.getParameter(paramName)); + if (MiscUtil.isNotEmpty(paramName) && + MOAIDAuthConstants.LEGACYPARAMETERWHITELIST.contains(paramName)) + executionContext.put(paramName, httpReq.getParameter(paramName)); } - - // create process instance - String processDefinitionId = ModuleRegistration.getInstance().selectProcess(executionContext); + } + // 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()}); - } + 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); + String processInstanceId = processEngine.createProcessInstance(processDefinitionId, executionContext); - // keep process instance id in moa session - moasession.setProcessInstanceId(processInstanceId); + // keep process instance id in protocol pending-request + pendingReq.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()); + //store pending-request + requestStoreage.storePendingRequest(pendingReq); + + + // make sure moa session has been persisted before running the process + try { + authenticatedSessionStore.storeSession(moasession); - response.setContentType("text/html;charset=UTF-8"); - PrintWriter out = new PrintWriter(response.getOutputStream()); - out.print(loginForm); - out.flush(); + } 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); + } catch (ProcessExecutionException e) { Throwable cause = e.getCause(); if (cause != null && cause instanceof TaskExecutionException) { @@ -746,11 +567,36 @@ public class AuthenticationManager extends MOAIDAuthConstants { MOAIDException moaTaskCause = (MOAIDException) taskCause; Logger.warn(taskCause); throw moaTaskCause; - + } - } - - throw new MOAIDException("process.01", new Object[] { moasession.getProcessInstanceId(), moasession }, e); - } + } + + throw new MOAIDException("process.01", new Object[] { pendingReq.getProcessInstanceId(), moasession }, e); + } + } + + private void sendTransmitAssertionQuestion(HttpServletRequest request, + HttpServletResponse response, IRequest target, IOAAuthParameters oaParam) + throws ServletException, IOException, MOAIDException { + + //TODO: change to process management version!!!! + + //set authenticated flag to false, because user consents is required + target.setAuthenticated(false); + + +// String form = SendAssertionFormBuilder.buildForm(target.requestedModule(), +// target.requestedAction(), target.getRequestID(), oaParam, +// target.getAuthURL()); + + String form =null; + + revisionsLogger.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(); } } 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..7833e795e 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,7 @@ 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.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..79e52f6e1 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,12 @@ 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; 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 index 4ae271bbc..f5d381e42 100644 --- 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 @@ -22,32 +22,121 @@ *******************************************************************************/ 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.auth.exception.SessionDataStorageException; import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOAResponse; public interface IRequest { + + /** + * Indicates the module, which implements this authentication protocol. + * The class, which is referenced, had to implement the 'IModulInfo' interface. + * + * @return Full-qualified name of the class which implements this protocol + */ + public String requestedModule(); + + /** + * Indicates the protocol specific action, which should executed if the request is processed. + * The class, which is referenced, had to implement the 'IAction' interface. + * + * @return Full-qualified name of the class which implements the action + */ + public String requestedAction(); + + /** + * Unique identifier, which indicates the service provider. + * In case of SAML1 protocol, it is the OA http-GET parameter + * + * @return Unique identifier for the service provider + */ public String getOAURL(); + + /** + * Indicates the passive flag in authentication requests. + * If the passive flag is set, the identification and authentication process + * failed if no active SSO session is found. + * + * @return true, if the is passive flag is set in authentication request, otherwise false + */ public boolean isPassiv(); + + /** + * Indicates the force authentication flag in authentication request + * If this flag is set, a new identification and authentication process + * is carried out in any case. + * + * @return true, if the force authentication flag is set, otherwise false + */ 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(); + + + /** + * Returns a generic request-data object with is stored with a specific identifier + * + * @param key The specific identifier of the request-data object + * @return The request-data object or null if no data is found with this key + */ + public Object getGenericData(String key); + + /** + * Returns a generic request-data object with is stored with a specific identifier + * + * @param key The specific identifier of the request-data object + * @param clazz The class type which is stored with this key + * @return The request-data object or null if no data is found with this key + */ + public <T> T getGenericData(String key, final Class<T> clazz); + + /** + * Store a generic data-object to request with a specific identifier + * + * @param key Identifier for this data-object + * @param object Generic data-object which should be stored. This data-object had to be implement the 'java.io.Serializable' interface + * @throws SessionDataStorageException Error message if the data-object can not stored to generic request-data storage + */ + public void setGenericDataToSession(String key, Object object) throws SessionDataStorageException; + + /** + * Hold the identifier of this request object. + * This identifier can be used to load the request from request storage + * + * @return Request identifier + */ + public String getRequestID(); + + + /** + * Hold the identifier of the MOASession which is associated with this request + * + * @return MOASession identifier if a associated session exists, otherwise null + */ + public String getMOASessionIdentifier(); + + + /** + * Holds a unique transaction identifier, which could be used for looging + * This transaction identifier is unique for a single identification and authentication process + * + * @return Unique transaction identifier. + */ + public String getUniqueTransactionIdentifier(); + + /** + * Holds a unique session identifier, which could be used for logging + * This session identifier is unique for the full Single Sign-On session time + * + * @return Unique session identifier + */ + public String getUniqueSessionIdentifier(); + + + /** + * Hold the identifier if the process instance, which is associated with this request + * + * @return ProcessInstanceID if this request is associated with a authentication process, otherwise null + */ + public String getProcessInstanceId(); + /** * get the IDP URL PreFix, which was used for authentication request @@ -57,5 +146,33 @@ public interface IRequest { public String getAuthURL(); public String getAuthURLWithOutSlash(); - //public void setTarget(); + /** + * Indicates if this pending request needs authentication + * + * @return true if this request needs authentication, otherwise false + */ + public boolean isNeedAuthentication(); + + /** + * Indicates, if this pending request needs Single Sign-On (SSO) functionality + * + * @return true if this request needs SSO, otherwise false + */ + public boolean needSingleSignOnFunctionality(); + public void setNeedSingleSignOnFunctionality(boolean needSSO); + + /** + * Indicates, if this pending request is already authenticated + * + * @return true if this request is already authenticated, otherwise false + */ + public boolean isAuthenticated(); + public void setAuthenticated(boolean isAuthenticated); + + /** + * Get get Service-Provider configuration which is associated with this request. + * + * @return Service-Provider configuration + */ + public IOAAuthParameters getOnlineApplicationConfiguration(); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IRequestStorage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IRequestStorage.java new file mode 100644 index 000000000..6f46edce3 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IRequestStorage.java @@ -0,0 +1,41 @@ +/* + * 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.auth.exception.MOAIDException; + +/** + * @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; + +} 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 index 99b7f4217..13768a343 100644 --- 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 @@ -1,46 +1,46 @@ -/******************************************************************************* - * 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; - } -} +///******************************************************************************* +// * 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/RequestImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java index cdaade1bb..bba9f66ae 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,73 @@ package at.gv.egovernment.moa.id.moduls; import java.io.Serializable; import java.net.MalformedURLException; import java.net.URL; +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.advancedlogging.TransactionIDUtils; +import at.gv.egovernment.moa.id.auth.exception.SessionDataStorageException; +import at.gv.egovernment.moa.id.commons.MOAIDConstants; import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; 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"; - private String oaURL; - private boolean passiv = false; - private boolean force = false; - private boolean ssosupport = false; + 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; - //MOA-ID interfederation - private String requestedIDP = null; - private MOAResponse response = null; + private boolean needAuthentication = true; + private boolean isAuthenticated = false; + private boolean needSSO = false; + + + private Map<String, Object> genericDataStorage = new HashMap<String, Object>(); /** * @throws ConfigurationException * */ - public RequestImpl(HttpServletRequest req) throws ConfigurationException { + public RequestImpl(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,7 +150,16 @@ 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!?!"); + } /** @@ -156,83 +193,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 +244,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 +289,99 @@ 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 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..66ca42398 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,23 +22,32 @@ *******************************************************************************/ 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.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); //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; @@ -49,12 +58,11 @@ public class RequestStorage { } } - 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 +77,52 @@ 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 { + + if (pendingRequest instanceof RequestImpl) { + String newRequestID = Random.nextRandom(); + + Logger.debug("Change pendingRequestID from " + pendingRequest.getRequestID() + + " to " + newRequestID); + + ((RequestImpl)pendingRequest).setRequestID(newRequestID); + storePendingRequest(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..89d50425b 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 @@ -40,23 +40,27 @@ 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.auth.exception.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.config.auth.AuthConfiguration; +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; +@Service("MOAID_SSOManager") public class SSOManager { private static final String HTMLTEMPLATESDIR = "htmlTemplates/"; @@ -65,27 +69,29 @@ public class SSOManager { 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 +101,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 +126,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 +134,7 @@ public class SSOManager { return false; } - AuthenticatedSessionStore storedSession = AuthenticationSessionStoreage.isValidSessionWithSSOID(ssoSessionID, null); + AuthenticatedSessionStore storedSession = authenticatedSessionStore.isValidSessionWithSSOID(ssoSessionID); if (storedSession == null) return false; @@ -137,7 +143,7 @@ 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 ... "); @@ -150,12 +156,16 @@ public class SSOManager { storedSession.isInterfederatedSSOSession() && !storedSession.isAuthenticated()) { - if (MiscUtil.isEmpty(((RequestImpl) protocolRequest).getRequestedIDP())) { - InterfederationSessionStore selectedIDP = AuthenticationSessionStoreage.searchInterfederatedIDPFORSSOWithMOASession(storedSession.getSessionid()); + 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()); + 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 +184,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 +264,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 +288,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 @@ -317,7 +320,7 @@ public class SSOManager { InputStream is = null; String pathLocation = null; try { - String rootconfigdir = AuthConfigurationProviderFactory.getInstance().getRootConfigFileDir(); + String rootconfigdir = authConfig.getRootConfigFileDir(); pathLocation = rootconfigdir + HTMLTEMPLATESDIR + HTMLTEMPLATEFULL; File file = new File(new URI(pathLocation)); is = new FileInputStream(file); @@ -359,7 +362,7 @@ public class SSOManager { BufferedReader reader = new BufferedReader(new InputStreamReader(is )); //set default elements to velocity context - context.put("contextpath", AuthConfigurationProviderFactory.getInstance().getPublicURLPrefix()); + context.put("contextpath", authConfig.getPublicURLPrefix()); StringWriter writer = new StringWriter(); //velocityEngine.evaluate(context, writer, "SLO_Template", reader); |