2  * ============LICENSE_START==========================================
 
   4  * ===================================================================
 
   5  * Copyright (C) 2017-2018 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============================================
 
  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.onap.portalapp.controller.sessionmgt.SessionCommunicationController;
 
  53 import org.onap.portalapp.portal.controller.BasicAuthenticationController;
 
  54 import org.onap.portalapp.portal.controller.ExternalAppsRestfulController;
 
  55 import org.onap.portalapp.portal.controller.SharedContextRestController;
 
  56 import org.onap.portalapp.portal.controller.WebAnalyticsExtAppController;
 
  57 import org.onap.portalapp.portal.domain.BasicAuthCredentials;
 
  58 import org.onap.portalapp.portal.domain.EPApp;
 
  59 import org.onap.portalapp.portal.domain.EPEndpoint;
 
  60 import org.onap.portalapp.portal.domain.EPUser;
 
  61 import org.onap.portalapp.portal.logging.aop.EPEELFLoggerAdvice;
 
  62 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
 
  63 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
 
  64 import org.onap.portalapp.portal.service.AppsCacheService;
 
  65 import org.onap.portalapp.portal.service.BasicAuthenticationCredentialService;
 
  66 import org.onap.portalapp.portal.service.ExternalAccessRolesService;
 
  67 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
 
  68 import org.onap.portalapp.portal.utils.EcompPortalUtils;
 
  69 import org.onap.portalapp.service.RemoteWebServiceCallService;
 
  70 import org.onap.portalapp.service.sessionmgt.ManageService;
 
  71 import org.onap.portalapp.util.EPUserUtils;
 
  72 import org.onap.portalsdk.core.controller.FusionBaseController;
 
  73 import org.onap.portalsdk.core.exception.UrlAccessRestrictedException;
 
  74 import org.onap.portalsdk.core.interceptor.ResourceInterceptor;
 
  75 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
 
  76 import org.onap.portalsdk.core.onboarding.listener.PortalTimeoutHandler;
 
  77 import org.onap.portalsdk.core.onboarding.util.CipherUtil;
 
  78 import org.onap.portalsdk.core.util.SystemProperties;
 
  79 import org.onap.portalsdk.core.util.SystemProperties.SecurityEventTypeEnum;
 
  80 import org.springframework.beans.factory.annotation.Autowired;
 
  81 import org.springframework.web.method.HandlerMethod;
 
  83 public class PortalResourceInterceptor extends ResourceInterceptor {
 
  85         private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PortalResourceInterceptor.class);
 
  88         private RemoteWebServiceCallService remoteWebServiceCallService;
 
  91         private ManageService manageService;
 
  94         AppsCacheService appCacheService;
 
  97         private EPEELFLoggerAdvice epAdvice;
 
 100         private BasicAuthenticationCredentialService basicAuthService;
 
 102         private ExternalAccessRolesService externalAccessRolesService;
 
 104         @SuppressWarnings("unchecked")
 
 106         public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
 
 109                 if (handler instanceof HandlerMethod) {
 
 110                         HandlerMethod method = (HandlerMethod) handler;
 
 113                          * These classes provide REST endpoints used by other application
 
 114                          * servers, NOT by an end user's browser.
 
 116                         if (method.getBean() instanceof FusionBaseController) {
 
 117                                 FusionBaseController controller = (FusionBaseController) method.getBean();
 
 118                                 if (!controller.isAccessible()) {
 
 120                                         // authorize portalApi requests by user role
 
 121                                         String requestURI = request.getRequestURI();
 
 122                                         if (requestURI != null) {
 
 123                                                 String[] uriArray = requestURI.split("/portalApi/");
 
 124                                                 if (uriArray.length > 1) {
 
 125                                                         String portalApiPath = uriArray[1];
 
 127                                                         Set<? extends String> roleFunctions = (Set<? extends String>) request.getSession()
 
 128                                                                         .getAttribute(SystemProperties
 
 129                                                                                         .getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME));
 
 130                                                         Set<? extends String> allRoleFunctions = (Set<? extends String>) request.getSession()
 
 131                                                                         .getAttribute(EPUserUtils.ALL_ROLE_FUNCTIONS);
 
 132                                                         // Defend against code error to avoid throwing NPE
 
 133                                                         if (roleFunctions == null || allRoleFunctions == null) {
 
 134                                                                 logger.error(EELFLoggerDelegate.errorLogger,
 
 135                                                                                 "preHandle: failed to get role functions attribute(s) from session!!");
 
 136                                                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInitializationError);
 
 139                                                         // check to see if roleFunctions of the user is in
 
 141                                                         // list of all role functions
 
 142                                                         // if not, ignore to prevent restricting every
 
 144                                                         // call; otherwise, if it is, then check for the
 
 146                                                         if (matchRoleFunctions(portalApiPath, allRoleFunctions)
 
 147                                                                         && !matchRoleFunctions(portalApiPath, roleFunctions)) {
 
 148                                                                 EPUser user = (EPUser) request.getSession().getAttribute(
 
 149                                                                                 SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
 
 150                                                                 logger.error(EELFLoggerDelegate.errorLogger,
 
 151                                                                                 "preHandle: User {} not authorized for path {} ", user.getOrgUserId(),
 
 153                                                                 EcompPortalUtils.setBadPermissions(user, response, portalApiPath);
 
 154                                                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError);
 
 163                         else if (method.getBean() instanceof BasicAuthenticationController) {
 
 164                                 return checkBasicAuth(request, response);
 
 166                         Object controllerObj = method.getBean();
 
 167                         if (controllerObj instanceof SessionCommunicationController
 
 168                                         || controllerObj instanceof SharedContextRestController
 
 169                                         || controllerObj instanceof ExternalAppsRestfulController) {
 
 170                                 // check user authentication for RESTful calls
 
 171                                 String secretKey = null;
 
 173                                         epAdvice.loadServletRequestBasedDefaults(request, SecurityEventTypeEnum.INCOMING_REST_MESSAGE);
 
 174                                         if (!remoteWebServiceCallService.verifyRESTCredential(secretKey, request.getHeader(EPCommonSystemProperties.UEB_KEY),
 
 175                                                         request.getHeader("username"), request.getHeader("password"))) {
 
 176                                                 throw new UrlAccessRestrictedException();
 
 178                                 } catch (Exception e) {
 
 179                                         logger.error(EELFLoggerDelegate.errorLogger, "preHandle: failed to authenticate RESTful service",
 
 181                                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError, e);
 
 182                                         throw new UrlAccessRestrictedException();
 
 186                         if (controllerObj instanceof WebAnalyticsExtAppController) {
 
 187                                 if (!remoteWebServiceCallService.verifyAppKeyCredential(request.getHeader(EPCommonSystemProperties.UEB_KEY))) {
 
 188                                         logger.error(EELFLoggerDelegate.errorLogger,
 
 189                                                         "preHandle: failed to verify app key for web analytics call");
 
 190                                         throw new UrlAccessRestrictedException();
 
 195                 handleSessionUpdates(request);
 
 200          * Sets the status code and sends a response. Factors code out of many
 
 204          *            HttpServletResponse
 
 206          *            HTTP status code like 404
 
 208          *            Message to send in a JSON error object
 
 210         private void sendErrorResponse(HttpServletResponse response, final int statusCode, final String message)
 
 212                 response.setStatus(statusCode);
 
 213                 response.setContentType("application/json");
 
 214                 response.getWriter().write("{\"error\":\"" + message + "\"}");
 
 215                 response.getWriter().flush();
 
 219          * Gets HTTP basic authentication information from the request and checks
 
 220          * whether those credentials are authorized for the request path.
 
 225          *            HttpServletResponse
 
 226          * @return True if the request is authorized, else false
 
 229         private boolean checkBasicAuth(HttpServletRequest request, HttpServletResponse response) throws Exception {
 
 230                 String uri = request.getRequestURI().toString();
 
 231                 uri = uri.substring(uri.indexOf("/", 1));
 
 233                 final String authHeader = request.getHeader(EPCommonSystemProperties.AUTHORIZATION);
 
 234                 final String uebkey = request.getHeader(EPCommonSystemProperties.UEB_KEY);
 
 236                 // Unauthorized access due to missing HTTP Authorization request header
 
 237                 if (authHeader == null) {
 
 238                         final String msg = "no authorization found";
 
 239                         logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
 
 240                         sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
 
 244                 String[] accountNamePassword = EcompPortalUtils.getUserNamePassword(authHeader);
 
 245                 if (accountNamePassword == null || accountNamePassword.length != 2) {
 
 246                         final String msg = "failed to get username and password from Atuhorization header";
 
 247                         logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
 
 248                         sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
 
 252                 if(uebkey !=null && !uebkey.isEmpty())
 
 254                         EPApp application = appCacheService.getAppFromUeb(uebkey,1);
 
 255                         if (application == null) {
 
 256                                 throw new Exception("Invalid uebkey!");
 
 259                                 final String appUsername = application.getUsername();
 
 260                                 final String dbDecryptedPwd = CipherUtil.decryptPKC(application.getAppPassword());
 
 261                                 if (appUsername.equals(accountNamePassword[0]) && dbDecryptedPwd.equals(accountNamePassword[1])) {
 
 268                 BasicAuthCredentials creds;
 
 270                         creds = basicAuthService.getBasicAuthCredentialByUsernameAndPassword(accountNamePassword[0],
 
 271                                         accountNamePassword[1]);
 
 272                 } catch (Exception e) {
 
 273                         logger.error(EELFLoggerDelegate.errorLogger, "checkBasicAuth failed to get credentials", e);
 
 274                         final String msg = "Failed while getting basic authentication credential: ";
 
 275                         sendErrorResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
 
 279                 // Unauthorized access due to invalid credentials (username and
 
 281                 if (creds == null || !creds.getUsername().equals(accountNamePassword[0])) {
 
 282                         final String msg = "Unauthorized: Access denied";
 
 283                         logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
 
 284                         sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
 
 288                 // Unauthorized access due to inactive account
 
 289                 if (creds.getIsActive().equals("N")) {
 
 290                         final String msg = "Unauthorized: The account is inactive";
 
 291                         logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
 
 292                         sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
 
 295                 boolean isAllowedEp = false;
 
 296                 for (EPEndpoint ep : creds.getEndpoints()) {
 
 297                         if (ep.getName().equals(uri)) {
 
 303                 // If user doesn't specify any endpoint, allow all endpoints for that
 
 305                 if (creds.getEndpoints().size() == 0)
 
 308                 // Unauthorized access due to the invalid endpoints
 
 310                         final String msg = "Unauthorized: Endpoint access denied";
 
 311                         logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
 
 312                         sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
 
 316                 // Made it to the end!
 
 320         @SuppressWarnings("unused")
 
 321         private String decrypted(String encrypted) throws Exception {
 
 323                 if (encrypted != null & encrypted.length() > 0) {
 
 325                                 result = CipherUtil.decryptPKC(encrypted, SystemProperties.getProperty(SystemProperties.Decryption_Key));
 
 326                         } catch (Exception e) {
 
 327                                 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e);
 
 334         private String encrypted(String decryptedPwd) throws Exception {
 
 336                 if (decryptedPwd != null & decryptedPwd.length() > 0) {
 
 338                                 result = CipherUtil.encryptPKC(decryptedPwd,
 
 339                                                 SystemProperties.getProperty(SystemProperties.Decryption_Key));
 
 340                         } catch (Exception e) {
 
 341                                 logger.error(EELFLoggerDelegate.errorLogger, "encryptedPassword() failed", e);
 
 348         private Boolean matchRoleFunctions(String portalApiPath, Set<? extends String> roleFunctions) {
 
 349                 String[] path = portalApiPath.split("/");
 
 350                 List<String> roleFunList = new ArrayList<>();
 
 351                 if (path.length > 1) {
 
 352                         roleFunList = roleFunctions.stream().filter(item -> item.startsWith(path[0])).collect(Collectors.toList());
 
 353                         if (roleFunList.size() >= 1) {
 
 354                                 for (String roleFunction : roleFunList) {
 
 355                                         String[] roleFunctionArray = roleFunction.split("/");
 
 357                                         if (roleFunctionArray.length == path.length) {
 
 358                                                 for (int i = 0; i < roleFunctionArray.length; i++) {
 
 360                                                                 if (!roleFunctionArray[i].equals("*")) {
 
 361                                                                         Pattern p = Pattern.compile(Pattern.quote(path[i]), Pattern.CASE_INSENSITIVE);
 
 362                                                                         Matcher m = p.matcher(roleFunctionArray[i]);
 
 374                         for (String roleFunction : roleFunctions) {
 
 375                                 if (portalApiPath.matches(roleFunction))
 
 382         protected void handleSessionUpdates(HttpServletRequest request) {
 
 383                 PortalTimeoutHandler.handleSessionUpdatesNative(request, null, null, null, null, manageService);