2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.sdc.fe.servlets;
23 import org.onap.portalsdk.core.onboarding.exception.CipherUtilException;
24 import org.onap.portalsdk.core.onboarding.util.CipherUtil;
25 import org.onap.sdc.security.AuthenticationCookie;
26 import org.onap.sdc.security.RepresentationUtils;
27 import org.openecomp.sdc.common.impl.MutableHttpServletRequest;
28 import org.openecomp.sdc.common.log.wrappers.Logger;
29 import org.openecomp.sdc.fe.Constants;
30 import org.openecomp.sdc.fe.config.Configuration;
31 import org.openecomp.sdc.fe.config.ConfigurationManager;
32 import org.openecomp.sdc.fe.config.FeEcompErrorManager;
34 import javax.servlet.RequestDispatcher;
35 import javax.servlet.ServletException;
36 import javax.servlet.http.Cookie;
37 import javax.servlet.http.HttpServlet;
38 import javax.servlet.http.HttpServletRequest;
39 import javax.servlet.http.HttpServletResponse;
40 import javax.ws.rs.GET;
41 import javax.ws.rs.Path;
42 import javax.ws.rs.core.Context;
43 import java.io.IOException;
44 import java.util.Enumeration;
45 import java.util.List;
48 * Root resource (exposed at "/" path)
51 public class PortalServlet extends HttpServlet {
53 private static Logger log = Logger.getLogger(PortalServlet.class.getName());
54 private static final long serialVersionUID = 1L;
56 public static final String MISSING_HEADERS_MSG = "Missing Headers In Request";
57 private static final String AUTHORIZATION_ERROR_MSG = "Autherization error";
58 private static final String NEW_LINE = System.getProperty("line.separator");
62 * Entry point from ECOMP portal
67 public void doGet(@Context final HttpServletRequest request, @Context final HttpServletResponse response) {
69 addRequestHeadersUsingWebseal(request, response);
70 } catch (Exception e) {
71 FeEcompErrorManager.getInstance().logFePortalServletError("Portal Servlet");
72 log.error("Error during getting portal page", e);
77 * Building new HTTP request and setting headers for the request The request
78 * will dispatch to index.html
82 * @throws ServletException
85 private void addRequestHeadersUsingWebseal(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
87 response.setContentType("text/html");
89 // Create new request object to dispatch
90 MutableHttpServletRequest mutableRequest = new MutableHttpServletRequest(request);
92 // Get configuration object (reads data from configuration.yaml)
93 Configuration configuration = getConfiguration(request);
95 // Check if we got header from webseal
96 String userId = request.getHeader(Constants.WEBSEAL_USER_ID_HEADER);
97 String firstNameFromCookie = "";
98 String lastNameFromCookie = "";
100 // Authentication via ecomp portal
102 String userIdFromCookie = getUserIdFromCookie(request);
103 if (("").equals(userIdFromCookie)) {
104 // This is probably a webseal request, so missing header in request should be printed.
105 response.sendError(HttpServletResponse.SC_USE_PROXY, MISSING_HEADERS_MSG);
107 userId = userIdFromCookie;
108 } catch (Exception e) {
109 response.sendError(HttpServletResponse.SC_USE_PROXY, AUTHORIZATION_ERROR_MSG);
110 log.error("Error during adding request header", e);
114 // Replace webseal header with open source header
115 mutableRequest.putHeader(Constants.USER_ID, userId);
121 // Getting identification headers from configuration.yaml
122 // (identificationHeaderFields) and setting them to new request
124 List<List<String>> identificationHeaderFields = configuration.getIdentificationHeaderFields();
125 for (List<String> possibleHeadersToRecieve : identificationHeaderFields) {
126 String allowedHeaderToPass = possibleHeadersToRecieve.get(0);
127 setNewHeader(possibleHeadersToRecieve, allowedHeaderToPass, request, mutableRequest);
130 // Getting optional headers from configuration.yaml
131 // (optionalHeaderFields) and setting them to new request mutableRequest
132 List<List<String>> optionalHeaderFields = configuration.getOptionalHeaderFields();
133 for (List<String> possibleHeadersToRecieve : optionalHeaderFields) {
134 String allowedHeaderToPass = possibleHeadersToRecieve.get(0);
135 setNewHeader(possibleHeadersToRecieve, allowedHeaderToPass, request, mutableRequest);
138 // Print headers from original request for debug purposes
139 printHeaders(request);
141 // In case using webseal, validate all mandatory headers (identificationHeaderFields) are included in the new request (mutableRequest).
142 // Via ecomp portal do not need to check the headers.
143 boolean allHeadersExist = true;
144 if (null != request.getHeader(Constants.WEBSEAL_USER_ID_HEADER)) {
145 allHeadersExist = checkHeaders(mutableRequest);
148 if (allHeadersExist) {
149 addCookies(response, mutableRequest, getMandatoryHeaders(request));
150 addCookies(response, mutableRequest, getOptionalHeaders(request));
151 firstNameFromCookie = getValueFromCookie(request, Constants.HTTP_CSP_FIRSTNAME );
152 lastNameFromCookie = getValueFromCookie(request, Constants.HTTP_CSP_LASTNAME);
155 //addAuthCookie(response, userId, firstNameFromCookie, lastNameFromCookie);
156 RequestDispatcher rd = request.getRequestDispatcher("index.html");
157 rd.forward(mutableRequest, response);
159 response.sendError(HttpServletResponse.SC_USE_PROXY, MISSING_HEADERS_MSG);
163 boolean addAuthCookie(HttpServletResponse response, String userId, String firstName, String lastName) throws IOException {
164 boolean isBuildCookieCompleted = true;
165 AuthenticationCookie authenticationCookie = null;
166 Cookie authCookie = null;
167 Configuration.CookieConfig confCookie =
168 ConfigurationManager.getConfigurationManager().getConfiguration().getAuthCookie();
170 //create authentication and send it to encryption
172 String encryptedCookie = "";
174 authenticationCookie = new AuthenticationCookie(userId, firstName, lastName);
175 String cookieAsJson = RepresentationUtils.toRepresentation(authenticationCookie);
176 encryptedCookie = org.onap.sdc.security.CipherUtil.encryptPKC(cookieAsJson, confCookie.getSecurityKey());
177 } catch (Exception e) {
178 isBuildCookieCompleted=false;
179 log.error(" Cookie Encryption failed ", e);
182 authCookie = new Cookie(confCookie.getCookieName(), encryptedCookie);
183 authCookie.setPath(confCookie.getPath());
184 authCookie.setDomain(confCookie.getDomain());
185 authCookie.setHttpOnly(true);
187 // add generated cookie to response
188 if (isBuildCookieCompleted) {
189 response.addCookie(authCookie);
192 response.sendError(HttpServletResponse.SC_UNAUTHORIZED, AUTHORIZATION_ERROR_MSG);
197 * Print all request headers to the log
201 private void printHeaders(HttpServletRequest request) {
203 if (log.isDebugEnabled()) {
204 StringBuilder builder = new StringBuilder();
205 String sessionId = "";
206 if (request.getSession() != null) {
207 String id = request.getSession().getId();
213 builder.append("Receiving request with headers:" + NEW_LINE);
214 log.debug("{}", request.getHeaderNames());
215 @SuppressWarnings("unchecked")
216 Enumeration<String> headerNames = request.getHeaderNames();
217 if (headerNames != null) {
218 while (headerNames.hasMoreElements()) {
219 String headerName = headerNames.nextElement();
220 String headerValue = request.getHeader(headerName);
221 builder.append("session " + sessionId + " header: name = " + headerName + ", value = " + headerValue + NEW_LINE);
225 log.debug(builder.toString());
231 * Add cookies (that where set in the new request headers) in the response
232 * Using DefaultHTTPUtilities Object to prevent CRLF injection in HTTP headers.
238 private void addCookies(HttpServletResponse response, HttpServletRequest request, String[] headers) {
239 for (int i = 0; i < headers.length; i++) {
240 String currHeader = headers[i];
241 String headerValue = request.getHeader(currHeader);
242 if (headerValue != null) {
243 final Cookie cookie = new Cookie(currHeader, headerValue);
244 cookie.setSecure(true);
245 response.addCookie(cookie);
251 * Get mandatory headers (identificationHeaderFields) String array, and
252 * checks that each header exists in the new request
257 private boolean checkHeaders(HttpServletRequest request) {
258 String[] mandatoryHeaders = getMandatoryHeaders(request);
260 boolean allHeadersExist = true;
261 for (int i = 0; i < mandatoryHeaders.length; i++) {
262 String headerValue = request.getHeader(mandatoryHeaders[i]);
263 if (headerValue == null) {
264 allHeadersExist = false;
268 return allHeadersExist;
272 * Get mandatory headers (identificationHeaderFields) from
273 * configuration.yaml file and return String[]
278 private String[] getMandatoryHeaders(HttpServletRequest request) {
279 Configuration configuration = getConfiguration(request);
280 List<List<String>> identificationHeaderFields = configuration.getIdentificationHeaderFields();
281 String[] mandatoryHeaders = new String[identificationHeaderFields.size()];
282 for (int i = 0; i < identificationHeaderFields.size(); i++) {
283 mandatoryHeaders[i] = identificationHeaderFields.get(i).get(0);
285 return mandatoryHeaders;
289 * Get optional headers (optionalHeaderFields) from configuration.yaml file
290 * and return String[]
295 private String[] getOptionalHeaders(HttpServletRequest request) {
296 Configuration configuration = getConfiguration(request);
297 List<List<String>> optionalHeaderFields = configuration.getOptionalHeaderFields();
298 String[] optionalHeaders = new String[optionalHeaderFields.size()];
299 for (int i = 0; i < optionalHeaderFields.size(); i++) {
300 optionalHeaders[i] = optionalHeaderFields.get(i).get(0);
302 return optionalHeaders;
306 * Return Configuration object to read from configuration.yaml
309 * @return Configuration
311 private Configuration getConfiguration(HttpServletRequest request) {
312 ConfigurationManager configManager = (ConfigurationManager) request.getSession().getServletContext().getAttribute(org.openecomp.sdc.common.api.Constants.CONFIGURATION_MANAGER_ATTR);
313 return configManager.getConfiguration();
316 private boolean setNewHeader(List<String> possibleOldHeaders, String newHeaderToSet, HttpServletRequest oldRequest, MutableHttpServletRequest newRequest) {
317 boolean newHeaderIsSet = false;
318 for (int i = 0; i < possibleOldHeaders.size() && !newHeaderIsSet; i++) {
319 String headerValue = oldRequest.getHeader(possibleOldHeaders.get(i));
320 if (headerValue != null) {
321 newRequest.putHeader(newHeaderToSet, headerValue);
322 newHeaderIsSet = true;
325 return newHeaderIsSet;
328 private static String getUserIdFromCookie(HttpServletRequest request) throws CipherUtilException {
330 Cookie[] cookies = request.getCookies();
331 Cookie userIdcookie = null;
332 if (cookies != null) {
333 for (Cookie cookie : cookies) {
334 if (cookie.getName().equals(Constants.ECOMP_PORTAL_COOKIE)) {
335 userIdcookie = cookie;
339 if (userIdcookie != null) {
340 userId = CipherUtil.decrypt(userIdcookie.getValue());
345 private static String getValueFromCookie(HttpServletRequest request, String cookieName) {
347 Cookie[] cookies = request.getCookies();
348 Cookie valueFromCookie = null;
350 for (Cookie cookie : cookies) {
351 if (cookie.getName().endsWith(cookieName)) {
352 valueFromCookie = cookie;
355 if (valueFromCookie != null) {
356 value = valueFromCookie.getValue();