fix backdoor issue when using portal
[aai/sparky-be.git] / sparkybe-onap-service / src / main / java / org / onap / aai / sparky / security / filter / LoginFilter.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017-2018 Amdocs
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *       http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21 package org.onap.aai.sparky.security.filter;
22
23 import java.io.IOException;
24
25 import javax.servlet.Filter;
26 import javax.servlet.FilterChain;
27 import javax.servlet.FilterConfig;
28 import javax.servlet.ServletException;
29 import javax.servlet.ServletRequest;
30 import javax.servlet.ServletResponse;
31 import javax.servlet.http.Cookie;
32 import javax.servlet.http.HttpServletRequest;
33 import javax.servlet.http.HttpServletResponse;
34 import javax.servlet.http.HttpSession;
35 import javax.ws.rs.core.HttpHeaders;
36
37 import org.onap.aai.cl.api.Logger;
38 import org.onap.aai.cl.eelf.LoggerFactory;
39 import org.onap.aai.sparky.logging.AaiUiMsgs;
40 import org.onap.aai.sparky.security.EcompSso;
41 import org.onap.aai.sparky.security.portal.config.PortalAuthenticationConfig;
42 import org.onap.portalsdk.core.onboarding.listener.PortalTimeoutHandler;
43 import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
44 import org.onap.portalsdk.core.onboarding.util.PortalApiProperties;
45 import org.onap.portalsdk.core.onboarding.util.SSOUtil;
46
47 /**
48  * This filter checks every request for proper ECOMP Portal single sign on initialization. The
49  * possible paths and actions:
50  * <OL>
51  * <LI>User starts at an app page via a bookmark. No ECOMP portal cookie is set. Redirect there to
52  * get one; then continue as below.
53  * <LI>User starts at ECOMP Portal and goes to app. Alternately, the user's session times out and
54  * the user hits refresh. The ECOMP Portal cookie is set, but there is no valid session. Create one
55  * and publish info.
56  * <LI>User has valid ECOMP Portal cookie and session. Reset the max idle in that session.
57  * </OL>
58  * <P>
59  * Notes:
60  * <UL>
61  * <LI>Portal Session should be up prior to App Session</LI>
62  * <LI>If App Session Expires or if EPService cookie is unavailable, we need to redirect to Portal.
63  * <LI>Method {@link #initiateSessionMgtHandler(HttpServletRequest)} should be called for Session
64  * management when the initial session is created
65  * <LI>While redirecting, the cookie "redirectUrl" should also be set so that Portal knows where to
66  * forward the request to once the Portal Session is created and EPService cookie is set.
67  * <LI>Method {@link #resetSessionMaxIdleTimeOut(HttpServletRequest)} should be called for every
68  * request to reset the MaxInactiveInterval to the right value.
69  * </UL>
70  * <P>
71  * This filter incorporates most features of the SDK application's SessionTimeoutInterceptor and
72  * SingleSignOnController classes
73  */
74 public class LoginFilter implements Filter {
75
76   private static final Logger LOG = LoggerFactory.getInstance().getLogger(LoginFilter.class);
77
78   @Override
79   public void init(FilterConfig filterConfig) throws ServletException {
80     // Validate that app has provided useful portal properties
81     if (PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL) == null) {
82       throw new ServletException("Failed to find URL in portal.properties");
83     }
84
85     PortalAuthenticationConfig appProperties;
86     try {
87       appProperties = PortalAuthenticationConfig.getInstance();
88     } catch (Exception ex) {
89       throw new ServletException("Failed to get properties", ex);
90     }
91
92     String restUser = appProperties.getUsername();
93     String restPassword = appProperties.getPassword();
94     if (restUser == null || restPassword == null) {
95       throw new ServletException("Failed to find user and/or password from properties");
96     }
97   }
98
99   @Override
100   public void destroy() {
101     // No resources to release
102   }
103
104   /*
105    * (non-Javadoc)
106    *
107    * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse,
108    * javax.servlet.FilterChain)
109    */
110   @Override
111   public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
112       throws ServletException, IOException {
113     HttpServletRequest request = (HttpServletRequest) req;
114     HttpServletResponse response = (HttpServletResponse) res;
115
116     // Choose authentication appropriate for the request.
117     final String restApiURI = request.getContextPath() + PortalApiConstants.API_PREFIX;
118     if (request.getRequestURI().startsWith(restApiURI)) {
119       // REST servlet checks credentials
120       LOG.debug(AaiUiMsgs.LOGIN_FILTER_DEBUG, "doFilter: delegating auth to REST servlet for request " + request.getRequestURI());
121       chain.doFilter(request, response);
122     } else {
123       // All other requests require ECOMP Portal authentication
124       if (EcompSso.validateEcompSso(request) == null) {
125         String redirectURL, logMessage;
126
127         // Redirect to Portal UI
128         redirectURL = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL);
129         logMessage = "Unauthorized login attempt.";
130
131         LOG.debug(AaiUiMsgs.LOGIN_FILTER_DEBUG,
132             logMessage +
133             " | Remote IP: " + request.getRemoteAddr() +
134             " | User agent: " + request.getHeader(HttpHeaders.USER_AGENT) +
135             " | Request URL: " + request.getRequestURL() +
136             " | Redirecting to: " + redirectURL);
137
138         response.sendRedirect(redirectURL);
139       } else {
140         HttpSession session = request.getSession(false);
141         response.addHeader("Cache-Control", "no-cache, no-store");
142         if (session == null) {
143           // New session
144           session = request.getSession(true);
145           LOG.debug(AaiUiMsgs.LOGIN_FILTER_DEBUG, "doFilter: created new session " + session.getId());
146           initiateSessionMgtHandler(request);
147         } else {
148           // Existing session
149           LOG.debug(AaiUiMsgs.LOGIN_FILTER_DEBUG, "doFilter: resetting idle in existing session " + session.getId());
150           resetSessionMaxIdleTimeOut(request);
151         }
152         // Pass request back down the filter chain
153         chain.doFilter(request, response);
154       }
155     }
156   }
157
158   /**
159    * Publishes information about the session.
160    *
161    * @param request
162    */
163   private void initiateSessionMgtHandler(HttpServletRequest request) {
164     String portalJSessionId = getPortalJSessionId(request);
165     String jSessionId = getJessionId(request);
166     storeMaxInactiveTime(request);
167     PortalTimeoutHandler.sessionCreated(portalJSessionId, jSessionId, request.getSession(false));
168   }
169
170   /**
171    * Gets the ECOMP Portal service cookie value.
172    *
173    * @param request
174    * @return Cookie value, or null if not found.
175    */
176   private String getPortalJSessionId(HttpServletRequest request) {
177     Cookie ep = EcompSso.getCookie(request, EcompSso.EP_SERVICE);
178     return ep == null ? null : ep.getValue();
179   }
180
181   /**
182    * Gets the container session ID.
183    *
184    * @param request
185    * @return Session ID, or null if no session.
186    */
187   private String getJessionId(HttpServletRequest request) {
188     HttpSession session = request.getSession();
189     return session == null ? null : session.getId();
190   }
191
192   /**
193    * Sets the global session's max idle time to the session's max inactive interval.
194    *
195    * @param request
196    */
197   private void storeMaxInactiveTime(HttpServletRequest request) {
198     HttpSession session = request.getSession(false);
199     if (session != null
200         && session.getAttribute(PortalApiConstants.GLOBAL_SESSION_MAX_IDLE_TIME) == null) {
201       session.setAttribute(PortalApiConstants.GLOBAL_SESSION_MAX_IDLE_TIME,
202           session.getMaxInactiveInterval());
203     }
204   }
205
206   /**
207    * Sets the session's max inactive interval.
208    *
209    * @param request
210    */
211   private void resetSessionMaxIdleTimeOut(HttpServletRequest request) {
212     try {
213       HttpSession session = request.getSession(false);
214       if (session != null) {
215         final Object maxIdleAttribute = session
216             .getAttribute(PortalApiConstants.GLOBAL_SESSION_MAX_IDLE_TIME);
217         if (maxIdleAttribute != null) {
218           session.setMaxInactiveInterval(Integer.parseInt(maxIdleAttribute.toString()));
219         }
220       }
221     } catch (Exception e) {
222       LOG.info(AaiUiMsgs.LOGIN_FILTER_INFO, "resetSessionMaxIdleTimeOut: failed to set session max inactive interval - " + e.getLocalizedMessage());
223     }
224   }
225
226 }