Search in sources :

Example 1 with UserSessionBase

use of org.apache.ranger.common.UserSessionBase in project ranger by apache.

the class ServiceDBStore method putMetaDataInfo.

public void putMetaDataInfo(RangerExportPolicyList rangerExportPolicyList) {
    Map<String, Object> metaDataInfo = new LinkedHashMap<String, Object>();
    UserSessionBase usb = ContextUtil.getCurrentUserSession();
    String userId = usb.getLoginId();
    metaDataInfo.put(HOSTNAME, LOCAL_HOSTNAME);
    metaDataInfo.put(USER_NAME, userId);
    metaDataInfo.put(TIMESTAMP, MiscUtil.getUTCDateForLocalDate(new Date()));
    metaDataInfo.put(RANGER_VERSION, RangerVersionInfo.getVersion());
    rangerExportPolicyList.setMetaDataInfo(metaDataInfo);
}
Also used : VXString(org.apache.ranger.view.VXString) Date(java.util.Date) LinkedHashMap(java.util.LinkedHashMap) UserSessionBase(org.apache.ranger.common.UserSessionBase)

Example 2 with UserSessionBase

use of org.apache.ranger.common.UserSessionBase in project ranger by apache.

the class ServiceDBStore method deleteServiceDef.

public void deleteServiceDef(Long serviceDefId, Boolean forceDelete) throws Exception {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> ServiceDBStore.deleteServiceDef(" + serviceDefId + ", " + forceDelete + ")");
    }
    bizUtil.blockAuditorRoleUser();
    UserSessionBase session = ContextUtil.getCurrentUserSession();
    if (session == null) {
        throw restErrorUtil.createRESTException("UserSession cannot be null, only Admin can update service-def", MessageEnums.OPER_NO_PERMISSION);
    }
    if (!session.isKeyAdmin() && !session.isUserAdmin()) {
        throw restErrorUtil.createRESTException("User is not allowed to update service-def, only Admin can update service-def", MessageEnums.OPER_NO_PERMISSION);
    }
    RangerServiceDef serviceDef = getServiceDef(serviceDefId);
    if (serviceDef == null) {
        throw restErrorUtil.createRESTException("No Service Definiton found for Id: " + serviceDefId, MessageEnums.DATA_NOT_FOUND);
    }
    List<XXService> serviceList = daoMgr.getXXService().findByServiceDefId(serviceDefId);
    if (!forceDelete) {
        if (CollectionUtils.isNotEmpty(serviceList)) {
            throw restErrorUtil.createRESTException("Services exists under given service definition, can't delete Service-Def: " + serviceDef.getName(), MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
        }
    }
    XXDataMaskTypeDefDao dataMaskDao = daoMgr.getXXDataMaskTypeDef();
    List<XXDataMaskTypeDef> dataMaskDefs = dataMaskDao.findByServiceDefId(serviceDefId);
    for (XXDataMaskTypeDef dataMaskDef : dataMaskDefs) {
        dataMaskDao.remove(dataMaskDef);
    }
    List<XXAccessTypeDef> accTypeDefs = daoMgr.getXXAccessTypeDef().findByServiceDefId(serviceDefId);
    for (XXAccessTypeDef accessType : accTypeDefs) {
        deleteXXAccessTypeDef(accessType);
    }
    XXContextEnricherDefDao xContextEnricherDao = daoMgr.getXXContextEnricherDef();
    List<XXContextEnricherDef> contextEnrichers = xContextEnricherDao.findByServiceDefId(serviceDefId);
    for (XXContextEnricherDef context : contextEnrichers) {
        xContextEnricherDao.remove(context);
    }
    XXEnumDefDao enumDefDao = daoMgr.getXXEnumDef();
    List<XXEnumDef> enumDefList = enumDefDao.findByServiceDefId(serviceDefId);
    for (XXEnumDef enumDef : enumDefList) {
        List<XXEnumElementDef> enumEleDefList = daoMgr.getXXEnumElementDef().findByEnumDefId(enumDef.getId());
        for (XXEnumElementDef eleDef : enumEleDefList) {
            daoMgr.getXXEnumElementDef().remove(eleDef);
        }
        enumDefDao.remove(enumDef);
    }
    XXPolicyConditionDefDao policyCondDao = daoMgr.getXXPolicyConditionDef();
    List<XXPolicyConditionDef> policyCondList = policyCondDao.findByServiceDefId(serviceDefId);
    for (XXPolicyConditionDef policyCond : policyCondList) {
        List<XXPolicyItemCondition> policyItemCondList = daoMgr.getXXPolicyItemCondition().findByPolicyConditionDefId(policyCond.getId());
        for (XXPolicyItemCondition policyItemCond : policyItemCondList) {
            daoMgr.getXXPolicyItemCondition().remove(policyItemCond);
        }
        policyCondDao.remove(policyCond);
    }
    List<XXResourceDef> resDefList = daoMgr.getXXResourceDef().findByServiceDefId(serviceDefId);
    for (XXResourceDef resDef : resDefList) {
        deleteXXResourceDef(resDef);
    }
    XXServiceConfigDefDao configDefDao = daoMgr.getXXServiceConfigDef();
    List<XXServiceConfigDef> configDefList = configDefDao.findByServiceDefId(serviceDefId);
    for (XXServiceConfigDef configDef : configDefList) {
        configDefDao.remove(configDef);
    }
    if (CollectionUtils.isNotEmpty(serviceList)) {
        for (XXService service : serviceList) {
            deleteService(service.getId());
        }
    }
    Long version = serviceDef.getVersion();
    if (version == null) {
        version = Long.valueOf(1);
        LOG.info("Found Version Value: `null`, so setting value of version to 1, While updating object, version should not be null.");
    } else {
        version = Long.valueOf(version.longValue() + 1);
    }
    serviceDef.setVersion(version);
    serviceDefService.delete(serviceDef);
    LOG.info("ServiceDefinition has been deleted successfully. Service-Def Name: " + serviceDef.getName());
    dataHistService.createObjectDataHistory(serviceDef, RangerDataHistService.ACTION_DELETE);
    postDelete(serviceDef);
    if (LOG.isDebugEnabled()) {
        LOG.debug("<== ServiceDBStore.deleteServiceDef(" + serviceDefId + ", " + forceDelete + ")");
    }
}
Also used : XXDataMaskTypeDefDao(org.apache.ranger.db.XXDataMaskTypeDefDao) XXPolicyConditionDefDao(org.apache.ranger.db.XXPolicyConditionDefDao) XXPolicyItemCondition(org.apache.ranger.entity.XXPolicyItemCondition) UserSessionBase(org.apache.ranger.common.UserSessionBase) XXDataMaskTypeDef(org.apache.ranger.entity.XXDataMaskTypeDef) XXEnumDefDao(org.apache.ranger.db.XXEnumDefDao) XXPolicyConditionDef(org.apache.ranger.entity.XXPolicyConditionDef) XXAccessTypeDef(org.apache.ranger.entity.XXAccessTypeDef) XXServiceConfigDef(org.apache.ranger.entity.XXServiceConfigDef) XXResourceDef(org.apache.ranger.entity.XXResourceDef) XXEnumElementDef(org.apache.ranger.entity.XXEnumElementDef) RangerServiceDef(org.apache.ranger.plugin.model.RangerServiceDef) XXEnumDef(org.apache.ranger.entity.XXEnumDef) XXService(org.apache.ranger.entity.XXService) XXServiceConfigDefDao(org.apache.ranger.db.XXServiceConfigDefDao) XXContextEnricherDef(org.apache.ranger.entity.XXContextEnricherDef) XXContextEnricherDefDao(org.apache.ranger.db.XXContextEnricherDefDao)

Example 3 with UserSessionBase

use of org.apache.ranger.common.UserSessionBase in project ranger by apache.

the class ServiceDBStore method updateService.

@Override
public RangerService updateService(RangerService service, Map<String, Object> options) throws Exception {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> ServiceDBStore.updateService()");
    }
    XXService existing = daoMgr.getXXService().getById(service.getId());
    if (existing == null) {
        throw restErrorUtil.createRESTException("no service exists with ID=" + service.getId(), MessageEnums.DATA_NOT_FOUND);
    }
    String existingName = existing.getName();
    boolean renamed = !StringUtils.equalsIgnoreCase(service.getName(), existingName);
    if (renamed) {
        XXService newNameService = daoMgr.getXXService().findByName(service.getName());
        if (newNameService != null) {
            throw restErrorUtil.createRESTException("another service already exists with name '" + service.getName() + "'. ID=" + newNameService.getId(), MessageEnums.DATA_NOT_UPDATABLE);
        }
        long countOfTaggedResources = daoMgr.getXXServiceResource().countTaggedResourcesInServiceId(existing.getId());
        Boolean isForceRename = options != null && options.get(ServiceStore.OPTION_FORCE_RENAME) != null ? (Boolean) options.get(ServiceStore.OPTION_FORCE_RENAME) : Boolean.FALSE;
        if (countOfTaggedResources != 0L) {
            if (isForceRename) {
                LOG.warn("Forcing the renaming of service from " + existingName + " to " + service.getName() + " although it is associated with " + countOfTaggedResources + " service-resources!");
            } else {
                throw restErrorUtil.createRESTException("Service " + existingName + " cannot be renamed, as it has associated service-resources", MessageEnums.DATA_NOT_UPDATABLE);
            }
        }
    }
    Map<String, String> configs = service.getConfigs();
    Map<String, String> validConfigs = validateRequiredConfigParams(service, configs);
    if (validConfigs == null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("==> ConfigParams cannot be null, ServiceDBStore.createService(" + service + ")");
        }
        throw restErrorUtil.createRESTException("ConfigParams cannot be null.", MessageEnums.ERROR_CREATING_OBJECT);
    }
    boolean hasTagServiceValueChanged = false;
    Long existingTagServiceId = existing.getTagService();
    // null for old clients; empty string to remove existing association
    String newTagServiceName = service.getTagService();
    Long newTagServiceId = null;
    if (newTagServiceName == null) {
        // old client; don't update existing tagService
        if (existingTagServiceId != null) {
            newTagServiceName = getServiceName(existingTagServiceId);
            service.setTagService(newTagServiceName);
            LOG.info("ServiceDBStore.updateService(id=" + service.getId() + "; name=" + service.getName() + "): tagService is null; using existing tagService '" + newTagServiceName + "'");
        }
    }
    if (StringUtils.isNotBlank(newTagServiceName)) {
        RangerService tmp = getServiceByName(newTagServiceName);
        if (tmp == null || !EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_TAG_NAME.equals(tmp.getType())) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("ServiceDBStore.updateService() - " + newTagServiceName + " does not refer to a valid tag service.(" + service + ")");
            }
            throw restErrorUtil.createRESTException("Invalid tag service name " + newTagServiceName, MessageEnums.ERROR_CREATING_OBJECT);
        } else {
            newTagServiceId = tmp.getId();
        }
    }
    if (existingTagServiceId == null) {
        if (newTagServiceId != null) {
            hasTagServiceValueChanged = true;
        }
    } else if (!existingTagServiceId.equals(newTagServiceId)) {
        hasTagServiceValueChanged = true;
    }
    boolean hasIsEnabledChanged = !existing.getIsenabled().equals(service.getIsEnabled());
    List<XXTrxLog> trxLogList = svcService.getTransactionLog(service, existing, RangerServiceService.OPERATION_UPDATE_CONTEXT);
    if (populateExistingBaseFields) {
        svcServiceWithAssignedId.setPopulateExistingBaseFields(true);
        service = svcServiceWithAssignedId.update(service);
        svcServiceWithAssignedId.setPopulateExistingBaseFields(false);
    } else {
        service.setCreateTime(existing.getCreateTime());
        service.setGuid(existing.getGuid());
        service.setVersion(existing.getVersion());
        service = svcService.update(service);
        if (hasTagServiceValueChanged || hasIsEnabledChanged) {
            updatePolicyVersion(service, false);
        }
    }
    XXService xUpdService = daoMgr.getXXService().getById(service.getId());
    String oldPassword = null;
    List<XXServiceConfigMap> dbConfigMaps = daoMgr.getXXServiceConfigMap().findByServiceId(service.getId());
    for (XXServiceConfigMap dbConfigMap : dbConfigMaps) {
        if (StringUtils.equalsIgnoreCase(dbConfigMap.getConfigkey(), CONFIG_KEY_PASSWORD)) {
            oldPassword = dbConfigMap.getConfigvalue();
        }
        daoMgr.getXXServiceConfigMap().remove(dbConfigMap);
    }
    VXUser vXUser = null;
    XXServiceConfigMapDao xConfMapDao = daoMgr.getXXServiceConfigMap();
    for (Entry<String, String> configMap : validConfigs.entrySet()) {
        String configKey = configMap.getKey();
        String configValue = configMap.getValue();
        if (StringUtils.equalsIgnoreCase(configKey, "username")) {
            String userName = stringUtil.getValidUserName(configValue);
            XXUser xxUser = daoMgr.getXXUser().findByUserName(userName);
            if (xxUser != null) {
                vXUser = xUserService.populateViewBean(xxUser);
            } else {
                UserSessionBase usb = ContextUtil.getCurrentUserSession();
                if (usb != null && !usb.isUserAdmin()) {
                    throw restErrorUtil.createRESTException("User does not exist with given username: [" + userName + "] please use existing user", MessageEnums.OPER_NO_PERMISSION);
                }
                vXUser = xUserMgr.createServiceConfigUser(userName);
            }
        }
        if (StringUtils.equalsIgnoreCase(configKey, CONFIG_KEY_PASSWORD)) {
            if (StringUtils.equalsIgnoreCase(configValue, HIDDEN_PASSWORD_STR)) {
                String[] crypt_algo_array = null;
                if (configValue.contains(",")) {
                    crypt_algo_array = configValue.split(",");
                }
                if (oldPassword != null && oldPassword.contains(",")) {
                    String encryptKey = null;
                    String salt = null;
                    int iterationCount = 0;
                    crypt_algo_array = oldPassword.split(",");
                    String OLD_CRYPT_ALGO = crypt_algo_array[0];
                    encryptKey = crypt_algo_array[1];
                    salt = crypt_algo_array[2];
                    iterationCount = Integer.parseInt(crypt_algo_array[3]);
                    if (!OLD_CRYPT_ALGO.equalsIgnoreCase(CRYPT_ALGO)) {
                        String decryptedPwd = PasswordUtils.decryptPassword(oldPassword);
                        String paddingString = CRYPT_ALGO + "," + encryptKey + "," + salt + "," + iterationCount;
                        String encryptedPwd = PasswordUtils.encryptPassword(paddingString + "," + decryptedPwd);
                        String newDecryptedPwd = PasswordUtils.decryptPassword(paddingString + "," + encryptedPwd);
                        if (StringUtils.equals(newDecryptedPwd, decryptedPwd)) {
                            configValue = paddingString + "," + encryptedPwd;
                        }
                    } else {
                        configValue = oldPassword;
                    }
                } else {
                    configValue = oldPassword;
                }
            } else {
                String paddingString = CRYPT_ALGO + "," + ENCRYPT_KEY + "," + SALT + "," + ITERATION_COUNT;
                String encryptedPwd = PasswordUtils.encryptPassword(paddingString + "," + configValue);
                String decryptedPwd = PasswordUtils.decryptPassword(paddingString + "," + encryptedPwd);
                if (StringUtils.equals(decryptedPwd, configValue)) {
                    configValue = paddingString + "," + encryptedPwd;
                }
            }
        }
        XXServiceConfigMap xConfMap = new XXServiceConfigMap();
        xConfMap = (XXServiceConfigMap) rangerAuditFields.populateAuditFields(xConfMap, xUpdService);
        xConfMap.setServiceId(service.getId());
        xConfMap.setConfigkey(configKey);
        xConfMap.setConfigvalue(configValue);
        xConfMapDao.create(xConfMap);
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("vXUser:[" + vXUser + "]");
    }
    RangerService updService = svcService.getPopulatedViewObject(xUpdService);
    dataHistService.createObjectDataHistory(updService, RangerDataHistService.ACTION_UPDATE);
    bizUtil.createTrxLog(trxLogList);
    return updService;
}
Also used : XXUser(org.apache.ranger.entity.XXUser) VXString(org.apache.ranger.view.VXString) XXTrxLog(org.apache.ranger.entity.XXTrxLog) VXUser(org.apache.ranger.view.VXUser) XXServiceConfigMapDao(org.apache.ranger.db.XXServiceConfigMapDao) UserSessionBase(org.apache.ranger.common.UserSessionBase) XXServiceConfigMap(org.apache.ranger.entity.XXServiceConfigMap) RangerService(org.apache.ranger.plugin.model.RangerService) XXService(org.apache.ranger.entity.XXService)

Example 4 with UserSessionBase

use of org.apache.ranger.common.UserSessionBase in project ranger by apache.

the class SessionMgr method processStandaloneSuccessLogin.

// non-WEB processing
public UserSessionBase processStandaloneSuccessLogin(int authType, String ipAddress) {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    String currentLoginId = authentication.getName();
    // Need to build the UserSession
    XXPortalUser gjUser = daoManager.getXXPortalUser().findByLoginId(currentLoginId);
    if (gjUser == null) {
        logger.error("Error getting user for loginId=" + currentLoginId, new Exception());
        return null;
    }
    XXAuthSession gjAuthSession = new XXAuthSession();
    gjAuthSession.setLoginId(currentLoginId);
    gjAuthSession.setUserId(gjUser.getId());
    gjAuthSession.setAuthTime(DateUtil.getUTCDate());
    gjAuthSession.setAuthStatus(XXAuthSession.AUTH_STATUS_SUCCESS);
    gjAuthSession.setAuthType(authType);
    gjAuthSession.setDeviceType(RangerCommonEnums.DEVICE_UNKNOWN);
    gjAuthSession.setExtSessionId(null);
    gjAuthSession.setRequestIP(ipAddress);
    gjAuthSession.setRequestUserAgent(null);
    gjAuthSession = storeAuthSession(gjAuthSession);
    UserSessionBase userSession = new UserSessionBase();
    userSession.setXXPortalUser(gjUser);
    userSession.setXXAuthSession(gjAuthSession);
    // create context with user-session and set in thread-local
    RangerSecurityContext context = new RangerSecurityContext();
    context.setUserSession(userSession);
    RangerContextHolder.setSecurityContext(context);
    resetUserSessionForProfiles(userSession);
    resetUserModulePermission(userSession);
    return userSession;
}
Also used : XXPortalUser(org.apache.ranger.entity.XXPortalUser) RangerSecurityContext(org.apache.ranger.security.context.RangerSecurityContext) Authentication(org.springframework.security.core.Authentication) XXAuthSession(org.apache.ranger.entity.XXAuthSession) UserSessionBase(org.apache.ranger.common.UserSessionBase)

Example 5 with UserSessionBase

use of org.apache.ranger.common.UserSessionBase in project ranger by apache.

the class SessionMgr method getActiveSessionsOnServer.

public CopyOnWriteArrayList<UserSessionBase> getActiveSessionsOnServer() {
    CopyOnWriteArrayList<HttpSession> activeHttpUserSessions = RangerHttpSessionListener.getActiveSessionOnServer();
    CopyOnWriteArrayList<UserSessionBase> activeRangerUserSessions = new CopyOnWriteArrayList<UserSessionBase>();
    if (CollectionUtils.isEmpty(activeHttpUserSessions)) {
        return activeRangerUserSessions;
    }
    for (HttpSession httpSession : activeHttpUserSessions) {
        if (httpSession.getAttribute(RangerSecurityContextFormationFilter.AKA_SC_SESSION_KEY) == null) {
            continue;
        }
        RangerSecurityContext securityContext = (RangerSecurityContext) httpSession.getAttribute(RangerSecurityContextFormationFilter.AKA_SC_SESSION_KEY);
        if (securityContext.getUserSession() != null) {
            activeRangerUserSessions.add(securityContext.getUserSession());
        }
    }
    return activeRangerUserSessions;
}
Also used : RangerSecurityContext(org.apache.ranger.security.context.RangerSecurityContext) HttpSession(javax.servlet.http.HttpSession) UserSessionBase(org.apache.ranger.common.UserSessionBase) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList)

Aggregations

UserSessionBase (org.apache.ranger.common.UserSessionBase)69 RangerSecurityContext (org.apache.ranger.security.context.RangerSecurityContext)24 XXPortalUser (org.apache.ranger.entity.XXPortalUser)11 VXString (org.apache.ranger.view.VXString)11 XXUser (org.apache.ranger.entity.XXUser)8 ArrayList (java.util.ArrayList)6 XXPortalUserRole (org.apache.ranger.entity.XXPortalUserRole)6 XXService (org.apache.ranger.entity.XXService)5 VXResponse (org.apache.ranger.view.VXResponse)4 Test (org.junit.Test)4 Authentication (org.springframework.security.core.Authentication)4 HashSet (java.util.HashSet)3 HttpSession (javax.servlet.http.HttpSession)3 XXGroupUser (org.apache.ranger.entity.XXGroupUser)3 XXResource (org.apache.ranger.entity.XXResource)3 EntityManager (javax.persistence.EntityManager)2 CriteriaBuilder (javax.persistence.criteria.CriteriaBuilder)2 Predicate (javax.persistence.criteria.Predicate)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2