2  * ============LICENSE_START==========================================
 
   4  * ===================================================================
 
   5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 
   6  * ===================================================================
 
   8  * Unless otherwise specified, all software contained herein is licensed
 
   9  * under the Apache License, Version 2.0 (the "License");
 
  10  * you may not use this software except in compliance with the License.
 
  11  * You may obtain a copy of the License at
 
  13  *             http://www.apache.org/licenses/LICENSE-2.0
 
  15  * Unless required by applicable law or agreed to in writing, software
 
  16  * distributed under the License is distributed on an "AS IS" BASIS,
 
  17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
  18  * See the License for the specific language governing permissions and
 
  19  * limitations under the License.
 
  21  * Unless otherwise specified, all documentation contained herein is licensed
 
  22  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
 
  23  * you may not use this documentation except in compliance with the License.
 
  24  * You may obtain a copy of the License at
 
  26  *             https://creativecommons.org/licenses/by/4.0/
 
  28  * Unless required by applicable law or agreed to in writing, documentation
 
  29  * distributed under the License is distributed on an "AS IS" BASIS,
 
  30  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
  31  * See the License for the specific language governing permissions and
 
  32  * limitations under the License.
 
  34  * ============LICENSE_END============================================
 
  36  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
 
  38 package org.onap.portalapp.portal.interceptor;
 
  40 import java.nio.charset.Charset;
 
  41 import java.util.ArrayList;
 
  42 import java.util.Base64;
 
  43 import java.util.List;
 
  45 import java.util.regex.Matcher;
 
  46 import java.util.regex.Pattern;
 
  47 import java.util.stream.Collectors;
 
  49 import javax.servlet.http.HttpServletRequest;
 
  50 import javax.servlet.http.HttpServletResponse;
 
  52 import org.apache.commons.codec.binary.Hex;
 
  53 import org.onap.portalapp.controller.sessionmgt.SessionCommunicationController;
 
  54 import org.onap.portalapp.portal.controller.BasicAuthenticationController;
 
  55 import org.onap.portalapp.portal.controller.ExternalAppsRestfulController;
 
  56 import org.onap.portalapp.portal.controller.SharedContextRestController;
 
  57 import org.onap.portalapp.portal.controller.WebAnalyticsExtAppController;
 
  58 import org.onap.portalapp.portal.domain.BasicAuthCredentials;
 
  59 import org.onap.portalapp.portal.domain.EPEndpoint;
 
  60 import org.onap.portalapp.portal.domain.EPRole;
 
  61 import org.onap.portalapp.portal.domain.EPUser;
 
  62 import org.onap.portalapp.portal.logging.aop.EPEELFLoggerAdvice;
 
  63 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
 
  64 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
 
  65 import org.onap.portalapp.portal.service.BasicAuthenticationCredentialService;
 
  66 import org.onap.portalapp.portal.utils.EcompPortalUtils;
 
  67 import org.onap.portalapp.service.RemoteWebServiceCallService;
 
  68 import org.onap.portalapp.service.sessionmgt.ManageService;
 
  69 import org.onap.portalapp.util.EPUserUtils;
 
  70 import org.onap.portalsdk.core.controller.FusionBaseController;
 
  71 import org.onap.portalsdk.core.exception.UrlAccessRestrictedException;
 
  72 import org.onap.portalsdk.core.interceptor.ResourceInterceptor;
 
  73 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
 
  74 import org.onap.portalsdk.core.onboarding.listener.PortalTimeoutHandler;
 
  75 import org.onap.portalsdk.core.onboarding.util.CipherUtil;
 
  76 import org.onap.portalsdk.core.util.SystemProperties;
 
  77 import org.onap.portalsdk.core.util.SystemProperties.SecurityEventTypeEnum;
 
  78 import org.springframework.beans.factory.annotation.Autowired;
 
  79 import org.springframework.web.method.HandlerMethod;
 
  81 public class PortalResourceInterceptor extends ResourceInterceptor {
 
  82         private static final String APP_KEY = "uebkey";
 
  84         private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PortalResourceInterceptor.class);
 
  87         private RemoteWebServiceCallService remoteWebServiceCallService;
 
  90         private ManageService manageService;
 
  93         private EPEELFLoggerAdvice epAdvice;
 
  96         private BasicAuthenticationCredentialService basicAuthService;
 
  98         @SuppressWarnings("unchecked")
 
 100         public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
 
 103                 if (handler instanceof HandlerMethod) {
 
 104                         HandlerMethod method = (HandlerMethod) handler;
 
 107                          * These classes provide REST endpoints used by other application
 
 108                          * servers, NOT by an end user's browser.
 
 110                         if (method.getBean() instanceof FusionBaseController) {
 
 111                                 FusionBaseController controller = (FusionBaseController) method.getBean();
 
 112                                 if (!controller.isAccessible()) {
 
 114                                         // authorize portalApi requests by user role
 
 115                                         String requestURI = request.getRequestURI();
 
 116                                         if (requestURI != null) {
 
 117                                                 String[] uriArray = requestURI.split("/portalApi/");
 
 118                                                 if (uriArray.length > 1) {
 
 119                                                         String portalApiPath = uriArray[1];
 
 121                                                         Set<? extends String> roleFunctions = (Set<? extends String>) request.getSession()
 
 122                                                                         .getAttribute(SystemProperties
 
 123                                                                                         .getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME));
 
 124                                                         Set<? extends String> allRoleFunctions = (Set<? extends String>) request.getSession()
 
 125                                                                         .getAttribute(EPUserUtils.ALL_ROLE_FUNCTIONS);
 
 126                                                         // Defend against code error to avoid throwing NPE
 
 127                                                         if (roleFunctions == null || allRoleFunctions == null) {
 
 128                                                                 logger.error(EELFLoggerDelegate.errorLogger,
 
 129                                                                                 "preHandle: failed to get role functions attribute(s) from session!!");
 
 130                                                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInitializationError);
 
 133                                                         // check to see if roleFunctions of the user is in
 
 135                                                         // list of all role functions
 
 136                                                         // if not, ignore to prevent restricting every
 
 138                                                         // call; otherwise, if it is, then check for the
 
 140                                                         if (matchRoleFunctions(portalApiPath, allRoleFunctions)
 
 141                                                                         && !matchRoleFunctions(portalApiPath, roleFunctions)) {
 
 142                                                                 EPUser user = (EPUser) request.getSession().getAttribute(
 
 143                                                                                 SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
 
 144                                                                 logger.error(EELFLoggerDelegate.errorLogger,
 
 145                                                                                 "preHandle: User {} not authorized for path {} ", user.getOrgUserId(),
 
 147                                                                 EcompPortalUtils.setBadPermissions(user, response, portalApiPath);
 
 148                                                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError);
 
 157                         else if (method.getBean() instanceof BasicAuthenticationController) {
 
 158                                 return checkBasicAuth(request, response);
 
 160                         Object controllerObj = method.getBean();
 
 161                         if (controllerObj instanceof SessionCommunicationController
 
 162                                         || controllerObj instanceof SharedContextRestController
 
 163                                         || controllerObj instanceof ExternalAppsRestfulController) {
 
 164                                 // check user authentication for RESTful calls
 
 165                                 String secretKey = null;
 
 167                                         epAdvice.loadServletRequestBasedDefaults(request, SecurityEventTypeEnum.INCOMING_REST_MESSAGE);
 
 168                                         if (!remoteWebServiceCallService.verifyRESTCredential(secretKey, request.getHeader(APP_KEY),
 
 169                                                         request.getHeader("username"), request.getHeader("password"))) {
 
 170                                                 throw new UrlAccessRestrictedException();
 
 172                                 } catch (Exception e) {
 
 173                                         logger.error(EELFLoggerDelegate.errorLogger, "preHandle: failed to authenticate RESTful service",
 
 175                                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError, e);
 
 176                                         throw new UrlAccessRestrictedException();
 
 180                         if (controllerObj instanceof WebAnalyticsExtAppController) {
 
 181                                 if (!remoteWebServiceCallService.verifyAppKeyCredential(request.getHeader(APP_KEY))) {
 
 182                                         logger.error(EELFLoggerDelegate.errorLogger,
 
 183                                                         "preHandle: failed to verify app key for web analytics call");
 
 184                                         throw new UrlAccessRestrictedException();
 
 189                 handleSessionUpdates(request);
 
 194          * Sets the status code and sends a response. Factors code out of many
 
 198          *            HttpServletResponse
 
 200          *            HTTP status code like 404
 
 202          *            Message to send in a JSON error object
 
 204         private void sendErrorResponse(HttpServletResponse response, final int statusCode, final String message)
 
 206                 response.setStatus(statusCode);
 
 207                 response.setContentType("application/json");
 
 208                 response.getWriter().write("{\"error\":\"" + message + "\"}");
 
 209                 response.getWriter().flush();
 
 213          * Gets HTTP basic authentication information from the request and checks
 
 214          * whether those credentials are authorized for the request path.
 
 219          *            HttpServletResponse
 
 220          * @return True if the request is authorized, else false
 
 223         private boolean checkBasicAuth(HttpServletRequest request, HttpServletResponse response) throws Exception {
 
 224                 String uri = request.getRequestURI().toString();
 
 225                 uri = uri.substring(uri.indexOf("/", 1));
 
 227                 final String authHeader = request.getHeader("Authorization");
 
 229                 // Unauthorized access due to missing HTTP Authorization request header
 
 230                 if (authHeader == null) {
 
 231                         final String msg = "no authorization found";
 
 232                         logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
 
 233                         sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
 
 237                 String[] accountNamePassword = getUserNamePassword(authHeader);
 
 238                 if (accountNamePassword == null || accountNamePassword.length != 2) {
 
 239                         final String msg = "failed to get username and password from Atuhorization header";
 
 240                         logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
 
 241                         sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
 
 245                 BasicAuthCredentials creds;
 
 247                         creds = basicAuthService.getBasicAuthCredentialByUsernameAndPassword(accountNamePassword[0],
 
 248                                         accountNamePassword[1]);
 
 249                 } catch (Exception e) {
 
 250                         logger.error(EELFLoggerDelegate.errorLogger, "checkBasicAuth failed to get credentials", e);
 
 251                         final String msg = "Failed while getting basic authentication credential: ";
 
 252                         sendErrorResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
 
 256                 // Unauthorized access due to invalid credentials (username and
 
 258                 if (creds == null || !creds.getUsername().equals(accountNamePassword[0])) {
 
 259                         final String msg = "Unauthorized: Access denied";
 
 260                         logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
 
 261                         sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
 
 265                 // Unauthorized access due to inactive account
 
 266                 if (creds.getIsActive().equals("N")) {
 
 267                         final String msg = "Unauthorized: The account is inactive";
 
 268                         logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
 
 269                         sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
 
 272                 boolean isAllowedEp = false;
 
 273                 for (EPEndpoint ep : creds.getEndpoints()) {
 
 274                         if (ep.getName().equals(uri)) {
 
 280                 // If user doesn't specify any endpoint, allow all endpoints for that
 
 282                 if (creds.getEndpoints().size() == 0)
 
 285                 // Unauthorized access due to the invalid endpoints
 
 287                         final String msg = "Unauthorized: Endpoint access denied";
 
 288                         logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
 
 289                         sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
 
 293                 // Made it to the end!
 
 297         private String[] getUserNamePassword(String authValue) {
 
 298                 String base64Credentials = authValue.substring("Basic".length()).trim();
 
 299                 String credentials = new String(Base64.getDecoder().decode(base64Credentials), Charset.forName("UTF-8"));
 
 300                 final String[] values = credentials.split(":", 2);
 
 304         @SuppressWarnings("unused")
 
 305         private String decrypted(String encrypted) throws Exception {
 
 307                 if (encrypted != null & encrypted.length() > 0) {
 
 309                                 result = CipherUtil.decryptPKC(encrypted, SystemProperties.getProperty(SystemProperties.Decryption_Key));
 
 310                         } catch (Exception e) {
 
 311                                 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e);
 
 318         private String encrypted(String decryptedPwd) throws Exception {
 
 320                 if (decryptedPwd != null & decryptedPwd.length() > 0) {
 
 322                                 result = CipherUtil.encryptPKC(decryptedPwd,
 
 323                                                 SystemProperties.getProperty(SystemProperties.Decryption_Key));
 
 324                         } catch (Exception e) {
 
 325                                 logger.error(EELFLoggerDelegate.errorLogger, "encryptedPassword() failed", e);
 
 332         private Boolean matchRoleFunctions(String portalApiPath, Set<? extends String> roleFunctions) {
 
 333                 String[] path = portalApiPath.split("/");
 
 334                 List<String> roleFunList = new ArrayList<>();
 
 335                 if (path.length > 1) {
 
 336                         roleFunList = roleFunctions.stream().filter(item -> item.startsWith(path[0])).collect(Collectors.toList());
 
 337                         if (roleFunList.size() >= 1) {
 
 338                                 for (String roleFunction : roleFunList) {
 
 339                                         String[] roleFunctionArray = roleFunction.split("/");
 
 341                                         if (roleFunctionArray.length == path.length) {
 
 342                                                 for (int i = 0; i < roleFunctionArray.length; i++) {
 
 344                                                                 if (!roleFunctionArray[i].equals("*")) {
 
 345                                                                         Pattern p = Pattern.compile(Pattern.quote(path[i]), Pattern.CASE_INSENSITIVE);
 
 346                                                                         Matcher m = p.matcher(roleFunctionArray[i]);
 
 358                         for (String roleFunction : roleFunctions) {
 
 359                                 if (portalApiPath.matches(roleFunction))
 
 366         protected void handleSessionUpdates(HttpServletRequest request) {
 
 367                 PortalTimeoutHandler.handleSessionUpdatesNative(request, null, null, null, null, manageService);