Search in sources :

Example 6 with VXResponse

use of org.apache.ranger.view.VXResponse in project ranger by apache.

the class RangerAuthSuccessHandler method onAuthenticationSuccess.

/*
     * (non-Javadoc)
     *
     * @see org.springframework.security.web.authentication.
     * SavedRequestAwareAuthenticationSuccessHandler
     * #onAuthenticationSuccess(javax.servlet.http.HttpServletRequest,
     * javax.servlet.http.HttpServletResponse,
     * org.springframework.security.core.Authentication)
     */
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
    RangerSessionFixationProtectionStrategy rangerSessionFixationProtectionStrategy = new RangerSessionFixationProtectionStrategy();
    rangerSessionFixationProtectionStrategy.onAuthentication(authentication, request, response);
    WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails();
    String remoteAddress = details != null ? details.getRemoteAddress() : "";
    String sessionId = details != null ? details.getSessionId() : "";
    boolean isValidUser = sessionMgr.isValidXAUser(authentication.getName());
    String rangerAuthenticationMethod = PropertiesUtil.getProperty("ranger.authentication.method", "NONE");
    if (!isValidUser && !"NONE".equalsIgnoreCase(rangerAuthenticationMethod)) {
        xUserMgr.createServiceConfigUser(authentication.getName());
        isValidUser = sessionMgr.isValidXAUser(authentication.getName());
    }
    response.setContentType("application/json;charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("X-Frame-Options", "DENY");
    VXResponse vXResponse = new VXResponse();
    if (!isValidUser) {
        sessionMgr.processFailureLogin(XXAuthSession.AUTH_STATUS_USER_NOT_FOUND, XXAuthSession.AUTH_TYPE_PASSWORD, authentication.getName(), remoteAddress, sessionId);
        authentication.setAuthenticated(false);
        vXResponse.setStatusCode(HttpServletResponse.SC_PRECONDITION_FAILED);
        vXResponse.setMsgDesc("Auth Succeeded but user is not synced yet for " + authentication.getName());
        response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED);
        response.getWriter().write(jsonUtil.writeObjectAsString(vXResponse));
        // response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        logger.info("Auth Succeeded but user is not synced yet for " + authentication.getName());
    } else {
        String ajaxRequestHeader = request.getHeader("X-Requested-With");
        if (logger.isDebugEnabled()) {
            logger.debug("commence() X-Requested-With=" + ajaxRequestHeader);
        }
        if (ajaxRequestHeader != null && "XMLHttpRequest".equalsIgnoreCase(ajaxRequestHeader)) {
            // if (logger.isDebugEnabled()) {
            // logger.debug("Forwarding AJAX login request success to "
            // + ajaxLoginSuccessPage + " for user "
            // + authentication.getName());
            // }
            // request.getRequestDispatcher(ajaxLoginSuccessPage).forward(request,
            // response);
            String jsonResp = "";
            try {
                vXResponse.setStatusCode(HttpServletResponse.SC_OK);
                vXResponse.setMsgDesc("Login Successful");
                response.setStatus(HttpServletResponse.SC_OK);
                jsonResp = jsonUtil.writeObjectAsString(vXResponse);
                response.getWriter().write(jsonResp);
            } catch (IOException e) {
                logger.info("Error while writing JSON in HttpServletResponse");
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Sending login success response : " + jsonResp);
            }
            clearAuthenticationAttributes(request);
        } else {
            String jsonResp = "";
            try {
                vXResponse.setStatusCode(HttpServletResponse.SC_OK);
                vXResponse.setMsgDesc("Login Successful");
                response.setStatus(HttpServletResponse.SC_OK);
                jsonResp = jsonUtil.writeObjectAsString(vXResponse);
                response.getWriter().write(jsonResp);
            } catch (IOException e) {
                logger.info("Error while writing JSON in HttpServletResponse");
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Sending login success response : " + jsonResp);
            }
        // super.onAuthenticationSuccess(request, response,
        // authentication);
        }
    }
}
Also used : VXResponse(org.apache.ranger.view.VXResponse) WebAuthenticationDetails(org.springframework.security.web.authentication.WebAuthenticationDetails) IOException(java.io.IOException)

Example 7 with VXResponse

use of org.apache.ranger.view.VXResponse in project ranger by apache.

the class RangerAuthenticationEntryPoint method commence.

@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
    String ajaxRequestHeader = request.getHeader("X-Requested-With");
    response.setHeader("X-Frame-Options", "DENY");
    if (logger.isDebugEnabled()) {
        logger.debug("commence() X-Requested-With=" + ajaxRequestHeader);
    }
    String requestURL = (request.getRequestURL() != null) ? request.getRequestURL().toString() : "";
    String servletPath = PropertiesUtil.getProperty("ranger.servlet.mapping.url.pattern", "service");
    String reqServletPath = configUtil.getWebAppRootURL() + "/" + servletPath;
    if ("XMLHttpRequest".equals(ajaxRequestHeader)) {
        try {
            VXResponse vXResponse = new VXResponse();
            vXResponse.setStatusCode(SC_AUTHENTICATION_TIMEOUT);
            vXResponse.setMsgDesc("Session Timeout");
            response.setStatus(SC_AUTHENTICATION_TIMEOUT);
            response.getWriter().write(jsonUtil.writeObjectAsString(vXResponse));
        } catch (IOException e) {
            logger.info("Error while writing JSON in HttpServletResponse");
        }
        return;
    } else {
        try {
            VXResponse vXResponse = new VXResponse();
            vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED);
            vXResponse.setMsgDesc("Authentication Failed");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write(jsonUtil.writeObjectAsString(vXResponse));
        } catch (IOException e) {
            logger.info("Error while writing JSON in HttpServletResponse");
        }
    }
    if (ajaxRequestHeader != null && "XMLHttpRequest".equalsIgnoreCase(ajaxRequestHeader)) {
        if (logger.isDebugEnabled()) {
            logger.debug("commence() AJAX request. Authentication required. Returning " + ajaxReturnCode + ". URL=" + request.getRequestURI());
        }
        response.sendError(ajaxReturnCode, "");
    } else if (!(requestURL.startsWith(reqServletPath))) {
        if (requestURL.contains(RangerSSOAuthenticationFilter.LOCAL_LOGIN_URL)) {
            if (request.getSession() != null) {
                request.getSession().setAttribute("locallogin", "true");
                request.getServletContext().setAttribute(request.getSession().getId(), "locallogin");
            }
        }
        super.commence(request, response, authException);
    }
}
Also used : VXResponse(org.apache.ranger.view.VXResponse) IOException(java.io.IOException)

Example 8 with VXResponse

use of org.apache.ranger.view.VXResponse in project ranger by apache.

the class ServiceREST method validateConfig.

@POST
@Path("/services/validateConfig")
@Produces({ "application/json", "application/xml" })
@PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.VALIDATE_CONFIG + "\")")
public VXResponse validateConfig(RangerService service) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> ServiceREST.validateConfig(" + service + ")");
    }
    VXResponse ret = new VXResponse();
    RangerPerfTracer perf = null;
    try {
        if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
            perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.validateConfig(serviceName=" + service.getName() + ")");
        }
        ret = serviceMgr.validateConfig(service, svcStore);
    } catch (WebApplicationException excp) {
        throw excp;
    } catch (Throwable excp) {
        LOG.error("validateConfig(" + service + ") failed", excp);
        throw restErrorUtil.createRESTException(excp.getMessage());
    } finally {
        RangerPerfTracer.log(perf);
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("<== ServiceREST.validateConfig(" + service + "): " + ret);
    }
    return ret;
}
Also used : VXResponse(org.apache.ranger.view.VXResponse) WebApplicationException(javax.ws.rs.WebApplicationException) RangerPerfTracer(org.apache.ranger.plugin.util.RangerPerfTracer) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize)

Example 9 with VXResponse

use of org.apache.ranger.view.VXResponse in project ranger by apache.

the class ServiceREST method grantAccess.

@POST
@Path("/services/grant/{serviceName}")
@Produces({ "application/json", "application/xml" })
public RESTResponse grantAccess(@PathParam("serviceName") String serviceName, GrantRevokeRequest grantRequest, @Context HttpServletRequest request) throws Exception {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> ServiceREST.grantAccess(" + serviceName + ", " + grantRequest + ")");
    }
    RESTResponse ret = new RESTResponse();
    RangerPerfTracer perf = null;
    if (grantRequest != null) {
        if (serviceUtil.isValidateHttpsAuthentication(serviceName, request)) {
            try {
                if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
                    perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.grantAccess(serviceName=" + serviceName + ")");
                }
                validateGrantRevokeRequest(grantRequest);
                String userName = grantRequest.getGrantor();
                Set<String> userGroups = CollectionUtils.isNotEmpty(grantRequest.getGrantorGroups()) ? grantRequest.getGrantorGroups() : userMgr.getGroupsForUser(userName);
                RangerAccessResource resource = new RangerAccessResourceImpl(StringUtil.toStringObjectMap(grantRequest.getResource()));
                VXUser vxUser = xUserService.getXUserByUserName(userName);
                if (vxUser.getUserRoleList().contains(RangerConstants.ROLE_ADMIN_AUDITOR) || vxUser.getUserRoleList().contains(RangerConstants.ROLE_KEY_ADMIN_AUDITOR)) {
                    VXResponse vXResponse = new VXResponse();
                    vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED);
                    vXResponse.setMsgDesc("Operation" + " denied. LoggedInUser=" + vxUser.getId() + " ,isn't permitted to perform the action.");
                    throw restErrorUtil.generateRESTException(vXResponse);
                }
                boolean isAdmin = hasAdminAccess(serviceName, userName, userGroups, resource);
                if (!isAdmin) {
                    throw restErrorUtil.createGrantRevokeRESTException("User doesn't have necessary permission to grant access");
                }
                RangerPolicy policy = getExactMatchPolicyForResource(serviceName, resource, userName);
                if (policy != null) {
                    boolean policyUpdated = false;
                    policyUpdated = ServiceRESTUtil.processGrantRequest(policy, grantRequest);
                    if (policyUpdated) {
                        svcStore.updatePolicy(policy);
                    } else {
                        LOG.error("processGrantRequest processing failed");
                        throw new Exception("processGrantRequest processing failed");
                    }
                } else {
                    policy = new RangerPolicy();
                    policy.setService(serviceName);
                    // TODO: better policy name
                    policy.setName("grant-" + System.currentTimeMillis());
                    policy.setDescription("created by grant");
                    policy.setIsAuditEnabled(grantRequest.getEnableAudit());
                    policy.setCreatedBy(userName);
                    Map<String, RangerPolicyResource> policyResources = new HashMap<String, RangerPolicyResource>();
                    Set<String> resourceNames = resource.getKeys();
                    if (!CollectionUtils.isEmpty(resourceNames)) {
                        for (String resourceName : resourceNames) {
                            RangerPolicyResource policyResource = new RangerPolicyResource((String) resource.getValue(resourceName));
                            policyResource.setIsRecursive(grantRequest.getIsRecursive());
                            policyResources.put(resourceName, policyResource);
                        }
                    }
                    policy.setResources(policyResources);
                    RangerPolicyItem policyItem = new RangerPolicyItem();
                    policyItem.setDelegateAdmin(grantRequest.getDelegateAdmin());
                    policyItem.getUsers().addAll(grantRequest.getUsers());
                    policyItem.getGroups().addAll(grantRequest.getGroups());
                    for (String accessType : grantRequest.getAccessTypes()) {
                        policyItem.getAccesses().add(new RangerPolicyItemAccess(accessType, Boolean.TRUE));
                    }
                    policy.getPolicyItems().add(policyItem);
                    svcStore.createPolicy(policy);
                }
            } catch (WebApplicationException excp) {
                throw excp;
            } catch (Throwable excp) {
                LOG.error("grantAccess(" + serviceName + ", " + grantRequest + ") failed", excp);
                throw restErrorUtil.createRESTException(excp.getMessage());
            } finally {
                RangerPerfTracer.log(perf);
            }
            ret.setStatusCode(RESTResponse.STATUS_SUCCESS);
        }
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("<== ServiceREST.grantAccess(" + serviceName + ", " + grantRequest + "): " + ret);
    }
    return ret;
}
Also used : VXResponse(org.apache.ranger.view.VXResponse) WebApplicationException(javax.ws.rs.WebApplicationException) RangerPerfTracer(org.apache.ranger.plugin.util.RangerPerfTracer) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) RangerPolicyResource(org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource) VXString(org.apache.ranger.view.VXString) VXUser(org.apache.ranger.view.VXUser) RangerPolicyItem(org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem) WebApplicationException(javax.ws.rs.WebApplicationException) IOException(java.io.IOException) JsonSyntaxException(com.google.gson.JsonSyntaxException) RangerPolicy(org.apache.ranger.plugin.model.RangerPolicy) RangerAccessResourceImpl(org.apache.ranger.plugin.policyengine.RangerAccessResourceImpl) RESTResponse(org.apache.ranger.admin.client.datatype.RESTResponse) RangerPolicyItemAccess(org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemAccess) RangerAccessResource(org.apache.ranger.plugin.policyengine.RangerAccessResource) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces)

Example 10 with VXResponse

use of org.apache.ranger.view.VXResponse in project ranger by apache.

the class RangerBizUtil method hasPermission.

/**
 * return response object if users is having permission on given resource
 *
 * @param vXResource
 * @param permission
 * @return
 */
public VXResponse hasPermission(VXResource vXResource, int permission) {
    VXResponse vXResponse = new VXResponse();
    if (!enableResourceAccessControl) {
        logger.debug("Resource Access Control is disabled !!!");
        return vXResponse;
    }
    if (vXResource == null) {
        vXResponse.setStatusCode(VXResponse.STATUS_ERROR);
        vXResponse.setMsgDesc("Please provide valid policy.");
        return vXResponse;
    }
    String resourceNames = vXResource.getName();
    if (stringUtil.isEmpty(resourceNames)) {
        vXResponse.setStatusCode(VXResponse.STATUS_ERROR);
        vXResponse.setMsgDesc("Please provide valid policy.");
        return vXResponse;
    }
    if (isAdmin()) {
        return vXResponse;
    }
    Long xUserId = getXUserId();
    Long assetId = vXResource.getAssetId();
    List<XXResource> xResourceList = daoManager.getXXResource().findByAssetIdAndResourceStatus(assetId, AppConstants.STATUS_ENABLED);
    XXAsset xAsset = daoManager.getXXAsset().getById(assetId);
    int assetType = xAsset.getAssetType();
    vXResponse.setStatusCode(VXResponse.STATUS_ERROR);
    vXResponse.setMsgDesc("Permission Denied !");
    if (assetType == AppConstants.ASSET_HIVE) {
        String[] requestResNameList = resourceNames.split(",");
        if (stringUtil.isEmpty(vXResource.getUdfs())) {
            int reqTableType = vXResource.getTableType();
            int reqColumnType = vXResource.getColumnType();
            for (String resourceName : requestResNameList) {
                boolean matchFound = matchHivePolicy(resourceName, xResourceList, xUserId, permission, reqTableType, reqColumnType, false);
                if (!matchFound) {
                    vXResponse.setMsgDesc("You're not permitted to perform " + "the action for resource path : " + resourceName);
                    vXResponse.setStatusCode(VXResponse.STATUS_ERROR);
                    return vXResponse;
                }
            }
        } else {
            for (String resourceName : requestResNameList) {
                boolean matchFound = matchHivePolicy(resourceName, xResourceList, xUserId, permission);
                if (!matchFound) {
                    vXResponse.setMsgDesc("You're not permitted to perform " + "the action for resource path : " + resourceName);
                    vXResponse.setStatusCode(VXResponse.STATUS_ERROR);
                    return vXResponse;
                }
            }
        }
        vXResponse.setStatusCode(VXResponse.STATUS_SUCCESS);
        return vXResponse;
    } else if (assetType == AppConstants.ASSET_HBASE) {
        String[] requestResNameList = resourceNames.split(",");
        for (String resourceName : requestResNameList) {
            boolean matchFound = matchHbasePolicy(resourceName, xResourceList, vXResponse, xUserId, permission);
            if (!matchFound) {
                vXResponse.setMsgDesc("You're not permitted to perform " + "the action for resource path : " + resourceName);
                vXResponse.setStatusCode(VXResponse.STATUS_ERROR);
                return vXResponse;
            }
        }
        vXResponse.setStatusCode(VXResponse.STATUS_SUCCESS);
        return vXResponse;
    } else if (assetType == AppConstants.ASSET_HDFS) {
        String[] requestResNameList = resourceNames.split(",");
        for (String resourceName : requestResNameList) {
            boolean matchFound = matchHdfsPolicy(resourceName, xResourceList, xUserId, permission);
            if (!matchFound) {
                vXResponse.setMsgDesc("You're not permitted to perform " + "the action for resource path : " + resourceName);
                vXResponse.setStatusCode(VXResponse.STATUS_ERROR);
                return vXResponse;
            }
        }
        vXResponse.setStatusCode(VXResponse.STATUS_SUCCESS);
        return vXResponse;
    } else if (assetType == AppConstants.ASSET_KNOX) {
        String[] requestResNameList = resourceNames.split(",");
        for (String resourceName : requestResNameList) {
            boolean matchFound = matchKnoxPolicy(resourceName, xResourceList, xUserId, permission);
            if (!matchFound) {
                vXResponse.setMsgDesc("You're not permitted to perform " + "the action for resource path : " + resourceName);
                vXResponse.setStatusCode(VXResponse.STATUS_ERROR);
                return vXResponse;
            }
        }
        vXResponse.setStatusCode(VXResponse.STATUS_SUCCESS);
        return vXResponse;
    } else if (assetType == AppConstants.ASSET_STORM) {
        String[] requestResNameList = resourceNames.split(",");
        for (String resourceName : requestResNameList) {
            boolean matchFound = matchStormPolicy(resourceName, xResourceList, xUserId, permission);
            if (!matchFound) {
                vXResponse.setMsgDesc("You're not permitted to perform " + "the action for resource path : " + resourceName);
                vXResponse.setStatusCode(VXResponse.STATUS_ERROR);
                return vXResponse;
            }
        }
        vXResponse.setStatusCode(VXResponse.STATUS_SUCCESS);
        return vXResponse;
    }
    return vXResponse;
}
Also used : VXResponse(org.apache.ranger.view.VXResponse) XXResource(org.apache.ranger.entity.XXResource) XXAsset(org.apache.ranger.entity.XXAsset) VXString(org.apache.ranger.view.VXString)

Aggregations

VXResponse (org.apache.ranger.view.VXResponse)40 Test (org.junit.Test)13 ArrayList (java.util.ArrayList)12 WebApplicationException (javax.ws.rs.WebApplicationException)10 XXPortalUser (org.apache.ranger.entity.XXPortalUser)7 VXMessage (org.apache.ranger.view.VXMessage)7 VXString (org.apache.ranger.view.VXString)7 IOException (java.io.IOException)6 VXResource (org.apache.ranger.view.VXResource)6 Path (javax.ws.rs.Path)5 Produces (javax.ws.rs.Produces)5 RESTResponse (org.apache.ranger.admin.client.datatype.RESTResponse)5 UserSessionBase (org.apache.ranger.common.UserSessionBase)5 XXPortalUserDao (org.apache.ranger.db.XXPortalUserDao)5 XXResource (org.apache.ranger.entity.XXResource)5 POST (javax.ws.rs.POST)4 Response (javax.ws.rs.core.Response)3 RangerPerfTracer (org.apache.ranger.plugin.util.RangerPerfTracer)3 VXPasswordChange (org.apache.ranger.view.VXPasswordChange)3 VXPortalUser (org.apache.ranger.view.VXPortalUser)3