From 276a3daea12bce6a2af6c1dee55a99f28d394fff Mon Sep 17 00:00:00 2001
From: Alok Lal
Date: Thu, 11 Jun 2015 16:45:21 -0700
Subject: [PATCH 001/202] RANGER-550 Hive plugin: Add support for
allowed/denied auditing for metadata commands with filtering support from
hive.
Signed-off-by: Madhan Neethiraj
---
.../authorizer/RangerHiveAccessRequest.java | 2 +-
.../authorizer/RangerHiveAuditHandler.java | 32 ----
.../hive/authorizer/RangerHiveAuthorizer.java | 181 +++++++-----------
3 files changed, 71 insertions(+), 144 deletions(-)
diff --git a/hive-agent/src/main/java/org/apache/ranger/authorization/hive/authorizer/RangerHiveAccessRequest.java b/hive-agent/src/main/java/org/apache/ranger/authorization/hive/authorizer/RangerHiveAccessRequest.java
index 1f7ae4d5668..2ae41490735 100644
--- a/hive-agent/src/main/java/org/apache/ranger/authorization/hive/authorizer/RangerHiveAccessRequest.java
+++ b/hive-agent/src/main/java/org/apache/ranger/authorization/hive/authorizer/RangerHiveAccessRequest.java
@@ -81,7 +81,7 @@ public RangerHiveAccessRequest(RangerHiveResource resource,
}
public RangerHiveAccessRequest(RangerHiveResource resource, String user, Set groups, HiveAuthzContext context, HiveAuthzSessionContext sessionContext) {
- this(resource, user, groups, "OTHER", HiveAccessType.USE, context, sessionContext);
+ this(resource, user, groups, "METADATA OPERATION", HiveAccessType.USE, context, sessionContext);
}
public HiveAccessType getHiveAccessType() {
diff --git a/hive-agent/src/main/java/org/apache/ranger/authorization/hive/authorizer/RangerHiveAuditHandler.java b/hive-agent/src/main/java/org/apache/ranger/authorization/hive/authorizer/RangerHiveAuditHandler.java
index 2675a67a495..0f13577b0f9 100644
--- a/hive-agent/src/main/java/org/apache/ranger/authorization/hive/authorizer/RangerHiveAuditHandler.java
+++ b/hive-agent/src/main/java/org/apache/ranger/authorization/hive/authorizer/RangerHiveAuditHandler.java
@@ -150,38 +150,6 @@ public void processResults(Collection results) {
}
}
- public void logAuditEventForFiltering(RangerAccessResult result, HiveOperationType hiveOpType) {
-
- if(! result.getIsAudited()) {
- return;
- }
-
- RangerHiveAccessRequest request = (RangerHiveAccessRequest)result.getAccessRequest();
- RangerHiveResource resource = (RangerHiveResource)request.getResource();
- String resourcePath = resource.getObjectType().toString();
- String accessType = getAccessTypeForMetaOperation(hiveOpType);
-
- AuthzAuditEvent auditEvent = createAuditEvent(result, accessType, resourcePath);
-
- addAuthzAuditEvent(auditEvent);
- }
-
- String getAccessTypeForMetaOperation(HiveOperationType hiveOperationType) {
- String result;
- switch (hiveOperationType) {
- case SHOWDATABASES:
- result = "SHOW DATABASES";
- break;
- case SHOWTABLES:
- result = "SHOW TABLES";
- break;
- default:
- result = "OTHER METADATA OP";
- break;
- }
- return result;
- }
-
public void logAuditEventForDfs(String userName, String dfsCommand, boolean accessGranted, int repositoryType, String repositoryName) {
AuthzAuditEvent auditEvent = new AuthzAuditEvent();
diff --git a/hive-agent/src/main/java/org/apache/ranger/authorization/hive/authorizer/RangerHiveAuthorizer.java b/hive-agent/src/main/java/org/apache/ranger/authorization/hive/authorizer/RangerHiveAuthorizer.java
index 1df1af40559..9075b574f00 100644
--- a/hive-agent/src/main/java/org/apache/ranger/authorization/hive/authorizer/RangerHiveAuthorizer.java
+++ b/hive-agent/src/main/java/org/apache/ranger/authorization/hive/authorizer/RangerHiveAuthorizer.java
@@ -26,6 +26,7 @@
import java.util.Map;
import java.util.Set;
+import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -225,7 +226,18 @@ public void checkPrivileges(HiveOperationType hiveOpType,
List requests = new ArrayList();
- if(inputHObjs != null) {
+ if(CollectionUtils.isEmpty(inputHObjs)) {
+ // this should happen only for SHOWDATABASES
+ if (hiveOpType == HiveOperationType.SHOWDATABASES) {
+ RangerHiveResource resource = new RangerHiveResource(HiveObjectType.DATABASE, null);
+ RangerHiveAccessRequest request = new RangerHiveAccessRequest(resource, user, groups, hiveOpType.name(), HiveAccessType.USE, context, sessionContext);
+ requests.add(request);
+ } else {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("RangerHiveAuthorizer.checkPrivileges: Unexpected operation type[" + hiveOpType + "] received with empty input objects list!");
+ }
+ }
+ } else {
for(HivePrivilegeObject hiveObj : inputHObjs) {
RangerHiveResource resource = getHiveResource(hiveOpType, hiveObj);
@@ -283,76 +295,54 @@ public void checkPrivileges(HiveOperationType hiveOpType,
}
}
- if (isMetaDataOperation(hiveOpType)) {
- RangerHiveResource resource = getHiveResource(hiveOpType);
- RangerHiveAccessRequest request = new RangerHiveAccessRequest(resource, user, groups, context, sessionContext);
- RangerAccessResult result = hivePlugin.isAccessAllowed(request);
- if (result == null) {
- LOG.error("Internal error: null RangerAccessResult object received back from isAccessAllowed()!");
- throw new HiveAccessControlException(String.format("Permission denied: user [%s] does not have [%s] privilege",
- user, hiveOpType));
- } else if (!result.getIsAllowed()) {
- String path = resource.getAsString();
- throw new HiveAccessControlException(String.format("Permission denied: user [%s] does not have [%s] privilege on [%s]",
- user, hiveOpType.name(), path));
- } else {
- if (LOG.isDebugEnabled()) {
- LOG.debug(String.format("[%s] allowed on resource[%s]: request[%s], result[%s]", hiveOpType, resource, request, result));
+ for(RangerHiveAccessRequest request : requests) {
+ RangerHiveResource resource = (RangerHiveResource)request.getResource();
+ RangerAccessResult result = null;
+
+ if(resource.getObjectType() == HiveObjectType.COLUMN && StringUtils.contains(resource.getColumn(), COLUMN_SEP)) {
+ List colRequests = new ArrayList();
+
+ String[] columns = StringUtils.split(resource.getColumn(), COLUMN_SEP);
+
+ // in case of multiple columns, original request is not sent to the plugin; hence service-def will not be set
+ resource.setServiceDef(hivePlugin.getServiceDef());
+
+ for(String column : columns) {
+ if (column != null) {
+ column = column.trim();
+ }
+ if(StringUtils.isBlank(column)) {
+ continue;
+ }
+
+ RangerHiveResource colResource = new RangerHiveResource(HiveObjectType.COLUMN, resource.getDatabase(), resource.getTable(), column);
+
+ RangerHiveAccessRequest colRequest = request.copy();
+ colRequest.setResource(colResource);
+
+ colRequests.add(colRequest);
}
- if (result.getIsAudited()) {
- auditHandler.logAuditEventForFiltering(result, hiveOpType);
+
+ Collection colResults = hivePlugin.isAccessAllowed(colRequests, auditHandler);
+
+ if(colResults != null) {
+ for(RangerAccessResult colResult : colResults) {
+ result = colResult;
+
+ if(!result.getIsAllowed()) {
+ break;
+ }
+ }
}
+ } else {
+ result = hivePlugin.isAccessAllowed(request, auditHandler);
}
- } else {
- for(RangerHiveAccessRequest request : requests) {
- RangerHiveResource resource = (RangerHiveResource)request.getResource();
- RangerAccessResult result = null;
-
- if(resource.getObjectType() == HiveObjectType.COLUMN && StringUtils.contains(resource.getColumn(), COLUMN_SEP)) {
- List colRequests = new ArrayList();
-
- String[] columns = StringUtils.split(resource.getColumn(), COLUMN_SEP);
- // in case of multiple columns, original request is not sent to the plugin; hence service-def will not be set
- resource.setServiceDef(hivePlugin.getServiceDef());
-
- for(String column : columns) {
- if (column != null) {
- column = column.trim();
- }
- if(StringUtils.isBlank(column)) {
- continue;
- }
-
- RangerHiveResource colResource = new RangerHiveResource(HiveObjectType.COLUMN, resource.getDatabase(), resource.getTable(), column);
-
- RangerHiveAccessRequest colRequest = request.copy();
- colRequest.setResource(colResource);
-
- colRequests.add(colRequest);
- }
-
- Collection colResults = hivePlugin.isAccessAllowed(colRequests, auditHandler);
-
- if(colResults != null) {
- for(RangerAccessResult colResult : colResults) {
- result = colResult;
-
- if(!result.getIsAllowed()) {
- break;
- }
- }
- }
- } else {
- result = hivePlugin.isAccessAllowed(request, auditHandler);
- }
-
- if(result != null && !result.getIsAllowed()) {
- String path = resource.getAsString();
-
- throw new HiveAccessControlException(String.format("Permission denied: user [%s] does not have [%s] privilege on [%s]",
- user, request.getHiveAccessType().name(), path));
- }
+ if(result != null && !result.getIsAllowed()) {
+ String path = resource.getAsString();
+
+ throw new HiveAccessControlException(String.format("Permission denied: user [%s] does not have [%s] privilege on [%s]",
+ user, request.getHiveAccessType().name(), path));
}
}
} finally {
@@ -360,29 +350,6 @@ public void checkPrivileges(HiveOperationType hiveOpType,
}
}
- boolean isMetaDataOperation(HiveOperationType hiveOpType) {
- boolean result;
-
- switch (hiveOpType) {
- /*
- * Uncomment this part when hive bug is resolved.
- *
- case SHOWTABLES:
- result = true;
- break;
- *
- */
- case SHOWDATABASES: // we don't want to authorize for show databases either since any call with _any privilages runs into a problem.
- case SHOWTABLES: // currently does not work since we don't get the database name in the context to do this check correctly.
- case DESCDATABASE: // currently does not work since we don't get the database name in the context to do this check correctly.
- default:
- result = false;
- break;
- }
- return result;
- }
-
-
/**
* Check if user has privileges to do this action on these objects
* @param objs
@@ -456,38 +423,25 @@ public List filterListCmdObjects(List
} else if (!result.getIsAllowed()) {
if (!LOG.isDebugEnabled()) {
String path = resource.getAsString();
- LOG.debug(String.format("filterListCmdObjects: Permission denied: user [%s] does not have [%s] privilege on [%s]", user, request.getHiveAccessType().name(), path));
+ LOG.debug(String.format("filterListCmdObjects: Permission denied: user [%s] does not have [%s] privilege on [%s]. resource[%s], request[%s], result[%s]",
+ user, request.getHiveAccessType().name(), path, resource, request, result));
}
} else {
if (LOG.isDebugEnabled()) {
- LOG.debug(String.format("filterListCmdObjects: resource[%s]: allowed!: request[%s], result[%s]", resource, request, result));
+ LOG.debug(String.format("filterListCmdObjects: access allowed. resource[%s], request[%s], result[%s]", resource, request, result));
}
ret.add(privilegeObject);
}
}
}
}
+
if (LOG.isDebugEnabled()) {
- LOG.debug(String.format("filterListCmdObjects: number of output objects[%d]", ret == null ? 0: ret.size()));
- LOG.debug(String.format("<== filterListCmdObjects(%s, %s): %s", objs, context, ret));
+ int count = ret == null ? 0 : ret.size();
+ LOG.debug(String.format("<== filterListCmdObjects: count[%d], ret[%s]", count, ret));
}
-
return ret;
}
-
- RangerHiveResource getHiveResource(HiveOperationType hiveOperationType) {
- RangerHiveResource hiveResource;
- switch (hiveOperationType) {
- case SHOWDATABASES:
- case SHOWTABLES:
- // any database
- hiveResource = new RangerHiveResource(HiveObjectType.DATABASE, null);
- break;
- default:
- hiveResource = null;
- }
- return hiveResource;
- }
RangerHiveResource createHiveResource(HivePrivilegeObject privilegeObject) {
RangerHiveResource resource = null;
@@ -691,6 +645,10 @@ private HiveAccessType getAccessType(HivePrivilegeObject hiveObj, HiveOperationT
accessType = HiveAccessType.LOCK;
break;
+ /*
+ * SELECT access is done for many of these metadata operations since hive does not call back for filtering.
+ * Overtime these should move to _any/USE access (as hive adds support for filtering).
+ */
case QUERY:
case SHOW_TABLESTATUS:
case SHOW_CREATETABLE:
@@ -703,8 +661,11 @@ private HiveAccessType getAccessType(HivePrivilegeObject hiveObj, HiveOperationT
accessType = HiveAccessType.SELECT;
break;
+ // any access done for metadata access of actions that have support from hive for filtering
+ case SHOWDATABASES:
case SWITCHDATABASE:
case DESCDATABASE:
+ case SHOWTABLES:
accessType = HiveAccessType.USE;
break;
@@ -733,10 +694,8 @@ private HiveAccessType getAccessType(HivePrivilegeObject hiveObj, HiveOperationT
case RESET:
case SET:
case SHOWCONF:
- case SHOWDATABASES:
case SHOWFUNCTIONS:
case SHOWLOCKS:
- case SHOWTABLES:
case SHOW_COMPACTIONS:
case SHOW_GRANT:
case SHOW_ROLES:
From df753e85e02eedea75421d21942686a03813187c Mon Sep 17 00:00:00 2001
From: Alok Lal
Date: Fri, 12 Jun 2015 12:40:04 -0700
Subject: [PATCH 002/202] RANGER-549 updating the tests so it would have failed
without the fix that was checked in prior
Signed-off-by: Madhan Neethiraj
---
.../plugin/model/validation/TestRangerServiceValidator.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/agents-common/src/test/java/org/apache/ranger/plugin/model/validation/TestRangerServiceValidator.java b/agents-common/src/test/java/org/apache/ranger/plugin/model/validation/TestRangerServiceValidator.java
index 6c20f0d466d..4b0fdbf5cef 100644
--- a/agents-common/src/test/java/org/apache/ranger/plugin/model/validation/TestRangerServiceValidator.java
+++ b/agents-common/src/test/java/org/apache/ranger/plugin/model/validation/TestRangerServiceValidator.java
@@ -196,7 +196,7 @@ public void test_isValid_happyPath() throws Exception {
// if name is not null and it points to a service then it should match the id
when(service.getId()).thenReturn(7L);
RangerService existingService = mock(RangerService.class);
- when(existingService.getId()).thenReturn(7L);
+ when(existingService.getId()).thenReturn(new Long(7L));
when(_store.getService(7L)).thenReturn(existingService);
when(_store.getServiceByName("aName")).thenReturn(existingService);
assertTrue(_validator.isValid(service, Action.UPDATE, _failures));
From e4877418f5c8f2ea42bdb57c84b2cc70856b6770 Mon Sep 17 00:00:00 2001
From: Alok Lal
Date: Fri, 12 Jun 2015 19:09:13 -0700
Subject: [PATCH 003/202] RANGER-553 Default policy creation during service
creation should handle service defs with multiple hierarchies, e.g. hive,
properly
Signed-off-by: Madhan Neethiraj
---
.../org/apache/ranger/biz/ServiceDBStore.java | 69 ++++++++++---------
1 file changed, 38 insertions(+), 31 deletions(-)
diff --git a/security-admin/src/main/java/org/apache/ranger/biz/ServiceDBStore.java b/security-admin/src/main/java/org/apache/ranger/biz/ServiceDBStore.java
index d57f0be4843..ff04d3fc1b3 100644
--- a/security-admin/src/main/java/org/apache/ranger/biz/ServiceDBStore.java
+++ b/security-admin/src/main/java/org/apache/ranger/biz/ServiceDBStore.java
@@ -100,6 +100,7 @@
import org.apache.ranger.plugin.model.RangerServiceDef.RangerPolicyConditionDef;
import org.apache.ranger.plugin.model.RangerServiceDef.RangerResourceDef;
import org.apache.ranger.plugin.model.RangerServiceDef.RangerServiceConfigDef;
+import org.apache.ranger.plugin.model.validation.RangerServiceDefHelper;
import org.apache.ranger.plugin.store.EmbeddedServiceDefsUtil;
import org.apache.ranger.plugin.store.ServicePredicateUtil;
import org.apache.ranger.plugin.store.ServiceStore;
@@ -1065,7 +1066,7 @@ public RangerService createService(RangerService service) throws Exception {
bizUtil.createTrxLog(trxLogList);
if (createDefaultPolicy) {
- createDefaultPolicy(xCreatedService, vXUser);
+ createDefaultPolicies(xCreatedService, vXUser);
}
return createdService;
@@ -1669,9 +1670,20 @@ public ServicePolicies getServicePoliciesIfUpdated(String serviceName, Long last
return ret;
}
- private void createDefaultPolicy(XXService createdService, VXUser vXUser) throws Exception {
+ private void createDefaultPolicies(XXService createdService, VXUser vXUser) throws Exception {
+ // we need to create one policy for each resource hierarchy
+ RangerServiceDef serviceDef = getServiceDef(createdService.getType());
+ RangerServiceDefHelper serviceDefHelper = new RangerServiceDefHelper(serviceDef);
+ int i = 1;
+ for (List aHierarchy : serviceDefHelper.getResourceHierarchies()) {
+ createDefaultPolicy(createdService, vXUser, aHierarchy, i);
+ i++;
+ }
+ }
+
+ private void createDefaultPolicy(XXService createdService, VXUser vXUser, List resourceHierarchy, int num) throws Exception {
RangerPolicy policy = new RangerPolicy();
- String policyName=createdService.getName()+"-"+1+"-"+DateUtil.dateToString(DateUtil.getUTCDate(),"yyyyMMddHHmmss");
+ String policyName=createdService.getName()+"-"+num+"-"+DateUtil.dateToString(DateUtil.getUTCDate(),"yyyyMMddHHmmss");
policy.setIsEnabled(true);
policy.setVersion(1L);
@@ -1680,34 +1692,7 @@ private void createDefaultPolicy(XXService createdService, VXUser vXUser) throws
policy.setDescription("Default Policy for Service: " + createdService.getName());
policy.setIsAuditEnabled(true);
- Map resources = new HashMap();
- List resDefList = daoMgr.getXXResourceDef().findByServiceDefId(createdService.getType());
-
- for(XXResourceDef resDef : resDefList) {
- // for hive, 2 policies should be created: 1) database/table/column 2) database/udf
- // until we support multiple default policies creation - one for each resource hierarchy,
- // lets just skip udf in the resoure list
- if("udf".equalsIgnoreCase(resDef.getName())) {
- continue;
- }
-
- RangerPolicyResource polRes = new RangerPolicyResource();
- polRes.setIsExcludes(false);
- polRes.setIsRecursive(false);
-
- String value = "*";
- if("path".equalsIgnoreCase(resDef.getName())) {
- value = "/*";
- }
-
- if(resDef.getRecursivesupported()) {
- polRes.setIsRecursive(Boolean.TRUE);
- }
-
- polRes.setValue(value);
- resources.put(resDef.getName(), polRes);
- }
- policy.setResources(resources);
+ policy.setResources(createDefaultPolicyResource(resourceHierarchy));
if (vXUser != null) {
List policyItems = new ArrayList();
@@ -1742,6 +1727,28 @@ private void createDefaultPolicy(XXService createdService, VXUser vXUser) throws
policy = createPolicy(policy);
}
+ Map createDefaultPolicyResource(List resourceHierarchy) throws Exception {
+ Map resourceMap = new HashMap<>();
+
+ for (RangerResourceDef resourceDef : resourceHierarchy) {
+ RangerPolicyResource polRes = new RangerPolicyResource();
+ polRes.setIsExcludes(false);
+ polRes.setIsRecursive(false);
+
+ String value = "*";
+ if("path".equalsIgnoreCase(resourceDef.getName())) {
+ value = "/*";
+ }
+
+ if(resourceDef.getRecursiveSupported()) {
+ polRes.setIsRecursive(Boolean.TRUE);
+ }
+
+ polRes.setValue(value);
+ resourceMap.put(resourceDef.getName(), polRes);
+ }
+ return resourceMap;
+ }
private Map validateRequiredConfigParams(RangerService service, Map configs) {
if(LOG.isDebugEnabled()) {
From 157f0f8d7e6f2f244a3fe353eced1b9ad8dd5583 Mon Sep 17 00:00:00 2001
From: Velmurugan Periasamy
Date: Mon, 15 Jun 2015 19:41:56 -0400
Subject: [PATCH 004/202] RANGER-554: Pagination support in KMS Keys listing
page
Signed-off-by: sneethiraj
---
.../java/org/apache/ranger/biz/KmsKeyMgr.java | 52 +++++++++++++++----
.../java/org/apache/ranger/rest/XKeyREST.java | 3 +-
2 files changed, 42 insertions(+), 13 deletions(-)
diff --git a/security-admin/src/main/java/org/apache/ranger/biz/KmsKeyMgr.java b/security-admin/src/main/java/org/apache/ranger/biz/KmsKeyMgr.java
index 7854f4bf869..551ec2eabff 100755
--- a/security-admin/src/main/java/org/apache/ranger/biz/KmsKeyMgr.java
+++ b/security-admin/src/main/java/org/apache/ranger/biz/KmsKeyMgr.java
@@ -26,6 +26,7 @@
import java.net.URL;
import java.security.PrivilegedAction;
import java.util.ArrayList;
+import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -100,7 +101,7 @@ public class KmsKeyMgr {
RangerDaoManagerBase rangerDaoManagerBase;
@SuppressWarnings("unchecked")
- public VXKmsKeyList searchKeys(String repoName) throws Exception{
+ public VXKmsKeyList searchKeys(HttpServletRequest request, String repoName) throws Exception{
String providers[] = null;
try {
providers = getKMSURL(repoName);
@@ -147,6 +148,16 @@ public String run() {
Gson gson = new GsonBuilder().create();
logger.debug(" Search Key RESPONSE: [" + response + "]");
keys = gson.fromJson(response, List.class);
+ Collections.sort(keys);
+ VXKmsKeyList vxKmsKeyList2 = new VXKmsKeyList();
+ List vXKeys2 = new ArrayList();
+ for (String name : keys) {
+ VXKmsKey key = new VXKmsKey();
+ key.setName(name);
+ vXKeys2.add(key);
+ }
+ vxKmsKeyList2.setVXKeys(vXKeys2);
+ vxKmsKeyList = getFilteredKeyList(request, vxKmsKeyList2);
break;
} catch (Exception e) {
if (e instanceof UniformInterfaceException || i == providers.length - 1)
@@ -155,15 +166,35 @@ public String run() {
continue;
}
}
- if (keys != null && keys.size() > 0) {
- for (String name : keys) {
- VXKmsKey key = getKeyFromUri(connProvider, name, isKerberos, repoName);
- vXKeys.add(key);
+ //details
+ if (vxKmsKeyList != null && vxKmsKeyList.getVXKeys() != null && vxKmsKeyList.getVXKeys().size() > 0) {
+ List lstKMSKey = vxKmsKeyList.getVXKeys();
+ int startIndex=restErrorUtil.parseInt(
+ request.getParameter("startIndex"), 0,
+ "Invalid value for parameter startIndex",
+ MessageEnums.INVALID_INPUT_DATA, null, "startIndex");
+ startIndex = startIndex < 0 ? 0 : startIndex;
+
+ int pageSize=restErrorUtil.parseInt(
+ request.getParameter("pageSize"), 0,
+ "Invalid value for parameter pageSize",
+ MessageEnums.INVALID_INPUT_DATA, null, "pageSize");
+ pageSize = pageSize < 0 ? 0 : pageSize;
+
+ vxKmsKeyList.setResultSize(lstKMSKey.size());
+ vxKmsKeyList.setTotalCount(lstKMSKey.size());
+ if((startIndex+pageSize) <= lstKMSKey.size()){
+ lstKMSKey = lstKMSKey.subList(startIndex, (startIndex+pageSize));}
+ else{
+ startIndex = startIndex >= lstKMSKey.size() ? 0 : startIndex;
+ lstKMSKey = lstKMSKey.subList(startIndex, lstKMSKey.size());
}
- vxKmsKeyList.setResultSize(vXKeys.size());
- vxKmsKeyList.setTotalCount(vXKeys.size());
- vxKmsKeyList.setStartIndex(0);
- vxKmsKeyList.setPageSize(vXKeys.size());
+ for (VXKmsKey kmsKey : lstKMSKey) {
+ VXKmsKey key = getKeyFromUri(connProvider, kmsKey.getName(), isKerberos, repoName);
+ vXKeys.add(key);
+ }
+ vxKmsKeyList.setStartIndex(startIndex);
+ vxKmsKeyList.setPageSize(pageSize);
}
vxKmsKeyList.setVXKeys(vXKeys);
return vxKmsKeyList;
@@ -540,7 +571,7 @@ private synchronized Client getClient() {
public VXKmsKeyList getFilteredKeyList(HttpServletRequest request, VXKmsKeyList vXKmsKeyList){
List sortFields = new ArrayList();
sortFields.add(new SortField(KeySearchFilter.KEY_NAME, KeySearchFilter.KEY_NAME));
-
+
KeySearchFilter filter = getKeySearchFilter(request, sortFields);
Predicate pred = getPredicate(filter);
@@ -631,7 +662,6 @@ private KeySearchFilter extractCommonCriteriasForFilter(HttpServletRequest reque
String sortBy = restErrorUtil.validateString(request.getParameter(KeySearchFilter.SORT_BY),
StringUtil.VALIDATION_ALPHA, "Invalid value for parameter sortBy", MessageEnums.INVALID_INPUT_DATA,
null, KeySearchFilter.SORT_BY);
-
boolean sortSet = false;
if (!StringUtils.isEmpty(sortBy)) {
for (SortField sortField : sortFields) {
diff --git a/security-admin/src/main/java/org/apache/ranger/rest/XKeyREST.java b/security-admin/src/main/java/org/apache/ranger/rest/XKeyREST.java
index 7845b86c32b..1c0f9fc4a19 100755
--- a/security-admin/src/main/java/org/apache/ranger/rest/XKeyREST.java
+++ b/security-admin/src/main/java/org/apache/ranger/rest/XKeyREST.java
@@ -79,8 +79,7 @@ public class XKeyREST {
public VXKmsKeyList searchKeys(@Context HttpServletRequest request, @QueryParam("provider") String provider) {
VXKmsKeyList vxKmsKeyList = new VXKmsKeyList();
try{
- vxKmsKeyList = keyMgr.searchKeys(provider);
- vxKmsKeyList = keyMgr.getFilteredKeyList(request, vxKmsKeyList);
+ vxKmsKeyList = keyMgr.searchKeys(request, provider);
}catch(Exception e){
handleError(e);
}
From d650c91329c9bbc02f54977920b580320e293490 Mon Sep 17 00:00:00 2001
From: Velmurugan Periasamy
Date: Mon, 15 Jun 2015 18:43:14 -0400
Subject: [PATCH 005/202] RANGER-555: Fixed x_data_hist query for Oracle DB
Signed-off-by: sneethiraj
---
.../org/apache/ranger/db/XXDataHistDao.java | 20 +++++++++++++++++--
1 file changed, 18 insertions(+), 2 deletions(-)
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXDataHistDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXDataHistDao.java
index b9f91d4b34f..07db4586ced 100644
--- a/security-admin/src/main/java/org/apache/ranger/db/XXDataHistDao.java
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXDataHistDao.java
@@ -23,6 +23,8 @@
import javax.persistence.NoResultException;
import javax.persistence.Query;
+import org.apache.ranger.biz.RangerBizUtil;
+import org.apache.ranger.common.AppConstants;
import org.apache.ranger.common.db.BaseDao;
import org.apache.ranger.entity.XXDataHist;
@@ -52,8 +54,22 @@ public XXDataHist findObjByEventTimeClassTypeAndId(String eventTime, int classTy
return null;
}
try {
- String queryStr = "select obj.* from x_data_hist obj where obj.obj_class_type = "+classType
- + " and obj.obj_id = "+objId + " and obj.create_time <= '" + eventTime + "' ORDER BY obj.id DESC";
+
+ int dbFlavor = RangerBizUtil.getDBFlavor();
+
+ String queryStr = "";
+
+ if (dbFlavor == AppConstants.DB_FLAVOR_ORACLE) {
+ queryStr = "select obj.* from x_data_hist obj where obj.obj_class_type = " + classType
+ + " and obj.obj_id = " + objId
+ + " and to_date(obj.create_time, 'YYYY-MM-DD\"T\"HH24:MI:SS\"Z\"') <= to_date('" + eventTime
+ + "', 'YYYY-MM-DD\"T\"HH24:MI:SS\"Z\"') ORDER BY obj.id DESC";
+ } else {
+ queryStr = "select obj.* from x_data_hist obj where obj.obj_class_type = " + classType
+ + " and obj.obj_id = " + objId + " and obj.create_time <= '" + eventTime
+ + "' ORDER BY obj.id DESC";
+ }
+
Query jpaQuery = getEntityManager().createNativeQuery(queryStr, tClass).setMaxResults(1);
return (XXDataHist) jpaQuery.getSingleResult();
From 74522f331dfdfc47dd456f5233d19b78079f9bf1 Mon Sep 17 00:00:00 2001
From: rmani
Date: Tue, 16 Jun 2015 19:50:30 -0700
Subject: [PATCH 006/202] RANGER-557: Ranger Storm authorizer to be consistent
with default authorizer
---
.../authorizer/RangerStormAuthorizer.java | 62 +++++++++++--------
1 file changed, 35 insertions(+), 27 deletions(-)
diff --git a/storm-agent/src/main/java/org/apache/ranger/authorization/storm/authorizer/RangerStormAuthorizer.java b/storm-agent/src/main/java/org/apache/ranger/authorization/storm/authorizer/RangerStormAuthorizer.java
index b94988b7880..3687527f475 100644
--- a/storm-agent/src/main/java/org/apache/ranger/authorization/storm/authorizer/RangerStormAuthorizer.java
+++ b/storm-agent/src/main/java/org/apache/ranger/authorization/storm/authorizer/RangerStormAuthorizer.java
@@ -21,6 +21,7 @@
import java.security.Principal;
import java.util.Map;
+import java.util.Set;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.ranger.authorization.storm.StormRangerPlugin;
@@ -30,6 +31,8 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import com.google.common.collect.Sets;
+
import backtype.storm.Config;
import backtype.storm.security.auth.IAuthorizer;
import backtype.storm.security.auth.ReqContext;
@@ -39,7 +42,9 @@ public class RangerStormAuthorizer implements IAuthorizer {
private static final Logger LOG = LoggerFactory.getLogger(RangerStormAuthorizer.class);
static final StormRangerPlugin plugin = new StormRangerPlugin();
-
+
+ static final Set noAuthzOperations = Sets.newHashSet(new String[] { "getNimbusConf", "getClusterInfo" });
+
/**
* permit() method is invoked for each incoming Thrift request.
* @param context request context includes info about
@@ -53,7 +58,7 @@ public boolean permit(ReqContext aRequestContext, String aOperationName, Map aTo
boolean accessAllowed = false ;
boolean isAuditEnabled = false;
-
+
String topologyName = null ;
try {
@@ -76,39 +81,42 @@ public boolean permit(ReqContext aRequestContext, String aOperationName, Map aTo
LOG.debug("TOPOLOGY CONFIG MAP is passed as null.") ;
}
}
+
+ if(noAuthzOperations.contains(aOperationName)) {
+ accessAllowed = true;
+ } else {
+ String userName = null ;
+ String[] groups = null ;
- String userName = null ;
- String[] groups = null ;
-
- Principal user = aRequestContext.principal() ;
+ Principal user = aRequestContext.principal() ;
- if (user != null) {
- userName = user.getName() ;
- if (userName != null) {
- UserGroupInformation ugi = UserGroupInformation.createRemoteUser(userName) ;
- userName = ugi.getShortUserName() ;
- groups = ugi.getGroupNames() ;
- if (LOG.isDebugEnabled()) {
- LOG.debug("User found from principal [" + user.getName() + "] => user:[" + userName + "], groups:[" + StringUtil.toString(groups) + "]") ;
+ if (user != null) {
+ userName = user.getName() ;
+ if (userName != null) {
+ UserGroupInformation ugi = UserGroupInformation.createRemoteUser(userName) ;
+ userName = ugi.getShortUserName() ;
+ groups = ugi.getGroupNames() ;
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("User found from principal [" + user.getName() + "] => user:[" + userName + "], groups:[" + StringUtil.toString(groups) + "]") ;
+ }
}
-
}
- }
- if (userName != null) {
- String clientIp = (aRequestContext.remoteAddress() == null ? null : aRequestContext.remoteAddress().getHostAddress() ) ;
- RangerAccessRequest accessRequest = plugin.buildAccessRequest(userName, groups, clientIp, topologyName, aOperationName);
- RangerAccessResult result = plugin.isAccessAllowed(accessRequest);
- accessAllowed = result != null && result.getIsAllowed();
- isAuditEnabled = result != null && result.getIsAudited();
+ if (userName != null) {
+ String clientIp = (aRequestContext.remoteAddress() == null ? null : aRequestContext.remoteAddress().getHostAddress() ) ;
+ RangerAccessRequest accessRequest = plugin.buildAccessRequest(userName, groups, clientIp, topologyName, aOperationName);
+ RangerAccessResult result = plugin.isAccessAllowed(accessRequest);
+ accessAllowed = result != null && result.getIsAllowed();
+ isAuditEnabled = result != null && result.getIsAudited();
- if (LOG.isDebugEnabled()) {
- LOG.debug("User found from principal [" + userName + "], groups [" + StringUtil.toString(groups) + "]: verifying using [" + plugin.getClass().getName() + "], allowedFlag => [" + accessAllowed + "], Audit Enabled:" + isAuditEnabled);
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("User found from principal [" + userName + "], groups [" + StringUtil.toString(groups) + "]: verifying using [" + plugin.getClass().getName() + "], allowedFlag => [" + accessAllowed + "], Audit Enabled:" + isAuditEnabled);
+ }
+ }
+ else {
+ LOG.info("NULL User found from principal [" + user + "]: Skipping authorization; allowedFlag => [" + accessAllowed + "], Audit Enabled:" + isAuditEnabled);
}
- }
- else {
- LOG.info("NULL User found from principal [" + user + "]: Skipping authorization; allowedFlag => [" + accessAllowed + "], Audit Enabled:" + isAuditEnabled);
}
}
catch(Throwable t) {
From 5d3155313c29ad4ff0fa6d3bed2ad9afcf360fc1 Mon Sep 17 00:00:00 2001
From: Alok Lal
Date: Thu, 11 Jun 2015 11:45:06 -0700
Subject: [PATCH 007/202] RANGER-558 Hbase plugin: unless user has READ access
at any level access should be denied and audited.
Signed-off-by: Madhan Neethiraj
---
.../plugin/policyengine/RangerAccessRequest.java | 4 ++++
.../policyengine/RangerAccessRequestImpl.java | 10 +++++++++-
.../RangerDefaultPolicyEvaluator.java | 5 +++--
.../authorization/hbase/AuthorizationSession.java | 10 +++++++++-
.../hbase/RangerAuthorizationCoprocessor.java | 13 +++++++------
.../hbase/RangerAuthorizationCoprocessorBase.java | 13 +++++++++++++
6 files changed, 45 insertions(+), 10 deletions(-)
diff --git a/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerAccessRequest.java b/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerAccessRequest.java
index 82a18fc9e42..63a7f5a618b 100644
--- a/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerAccessRequest.java
+++ b/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerAccessRequest.java
@@ -49,4 +49,8 @@ public interface RangerAccessRequest {
String getSessionId();
Map getContext();
+
+ ResourceMatchingScope getResourceMatchingScope();
+
+ enum ResourceMatchingScope {SELF, SELF_OR_DESCENDANTS}
}
diff --git a/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerAccessRequestImpl.java b/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerAccessRequestImpl.java
index e1326eac270..fe50ca6de2b 100644
--- a/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerAccessRequestImpl.java
+++ b/agents-common/src/main/java/org/apache/ranger/plugin/policyengine/RangerAccessRequestImpl.java
@@ -44,6 +44,7 @@ public class RangerAccessRequestImpl implements RangerAccessRequest {
private boolean isAccessTypeAny = false;
private boolean isAccessTypeDelegatedAdmin = false;
+ private ResourceMatchingScope resourceMatchingScope = ResourceMatchingScope.SELF;
public RangerAccessRequestImpl() {
this(null, null, null, null);
@@ -120,6 +121,11 @@ public Map getContext() {
return context;
}
+ @Override
+ public ResourceMatchingScope getResourceMatchingScope() {
+ return resourceMatchingScope;
+ }
+
@Override
public boolean isAccessTypeAny() {
return isAccessTypeAny;
@@ -176,6 +182,8 @@ public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
+ public void setResourceMatchingScope(ResourceMatchingScope scope) { this.resourceMatchingScope = scope; }
+
public void setContext(Map context) {
this.context = (context == null) ? new HashMap() : context;
}
@@ -210,7 +218,7 @@ public StringBuilder toString(StringBuilder sb) {
sb.append("action={").append(action).append("} ");
sb.append("requestData={").append(requestData).append("} ");
sb.append("sessionId={").append(sessionId).append("} ");
-
+ sb.append("resourceMatchingScope={").append(resourceMatchingScope).append("} ");
sb.append("context={");
if(context != null) {
diff --git a/agents-common/src/main/java/org/apache/ranger/plugin/policyevaluator/RangerDefaultPolicyEvaluator.java b/agents-common/src/main/java/org/apache/ranger/plugin/policyevaluator/RangerDefaultPolicyEvaluator.java
index 030cd87e806..9f60b7bfe76 100644
--- a/agents-common/src/main/java/org/apache/ranger/plugin/policyevaluator/RangerDefaultPolicyEvaluator.java
+++ b/agents-common/src/main/java/org/apache/ranger/plugin/policyevaluator/RangerDefaultPolicyEvaluator.java
@@ -108,6 +108,7 @@ public void evaluate(RangerAccessRequest request, RangerAccessResult result) {
boolean matchResult = false;
boolean isHeadMatchAttempted = false;
boolean headMatchResult = false;
+ final boolean attemptHeadMatch = request.isAccessTypeAny() || request.getResourceMatchingScope() == RangerAccessRequest.ResourceMatchingScope.SELF_OR_DESCENDANTS;
if (!result.getIsAuditedDetermined()) {
// Need to match request.resource first. If it matches (or head matches), then only more progress can be made
@@ -118,7 +119,7 @@ public void evaluate(RangerAccessRequest request, RangerAccessResult result) {
// Try head match only if match was not found and ANY access was requested
if (!matchResult) {
- if (request.isAccessTypeAny() && !isHeadMatchAttempted) {
+ if (attemptHeadMatch && !isHeadMatchAttempted) {
headMatchResult = matchResourceHead(request.getResource());
isHeadMatchAttempted = true;
}
@@ -142,7 +143,7 @@ public void evaluate(RangerAccessRequest request, RangerAccessResult result) {
// Try Head Match only if no match was found so far AND a head match was not attempted as part of evaluating
// Audit requirement
if (!matchResult) {
- if (request.isAccessTypeAny() && !isHeadMatchAttempted) {
+ if (attemptHeadMatch && !isHeadMatchAttempted) {
headMatchResult = matchResourceHead(request.getResource());
isHeadMatchAttempted = true;
}
diff --git a/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/AuthorizationSession.java b/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/AuthorizationSession.java
index 006629b9971..fdf1527a04f 100644
--- a/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/AuthorizationSession.java
+++ b/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/AuthorizationSession.java
@@ -58,7 +58,8 @@ public class AuthorizationSession {
// Passing a null handler to policy engine would suppress audit logging.
HbaseAuditHandler _auditHandler = null;
boolean _superUser = false; // is this session for a super user?
-
+ private RangerAccessRequest.ResourceMatchingScope _resourceMatchingScope = RangerAccessRequest.ResourceMatchingScope.SELF;
+
// internal state per-authorization
RangerAccessRequest _request;
RangerAccessResult _result;
@@ -169,6 +170,7 @@ AuthorizationSession buildRequest() {
request.setAction(_operation);
request.setRequestData(_otherInformation);
request.setClientIPAddress(_remoteAddress);
+ request.setResourceMatchingScope(_resourceMatchingScope);
_request = request;
if (LOG.isDebugEnabled()) {
@@ -311,6 +313,7 @@ String requestToString() {
.add("table", _table)
.add("column", _column)
.add("column-family", _columnFamily)
+ .add("resource-matching-scope", _resourceMatchingScope)
.toString();
}
@@ -370,4 +373,9 @@ RangerAccessResult buildResult(boolean allowed, boolean audited, String reason)
}
return result;
}
+
+ AuthorizationSession resourceMatchingScope(RangerAccessRequest.ResourceMatchingScope scope) {
+ _resourceMatchingScope = scope;
+ return this;
+ }
}
diff --git a/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/RangerAuthorizationCoprocessor.java b/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/RangerAuthorizationCoprocessor.java
index e64c5af086a..8762bf5c292 100644
--- a/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/RangerAuthorizationCoprocessor.java
+++ b/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/RangerAuthorizationCoprocessor.java
@@ -97,8 +97,8 @@
import org.apache.ranger.authorization.hadoop.constants.RangerHadoopConstants;
import org.apache.ranger.authorization.utils.StringUtil;
import org.apache.ranger.plugin.audit.RangerDefaultAuditHandler;
+import org.apache.ranger.plugin.policyengine.RangerAccessRequest;
import org.apache.ranger.plugin.policyengine.RangerAccessResultProcessor;
-import org.apache.ranger.plugin.policyengine.RangerPolicyEngine;
import org.apache.ranger.plugin.service.RangerBasePlugin;
import org.apache.ranger.plugin.util.GrantRevokeRequest;
@@ -408,7 +408,8 @@ ColumnFamilyAccessResult evaluateAccess(String operation, Action action, final R
if (LOG.isDebugEnabled()) {
LOG.debug("evaluateAccess: no family level access [" + family + "]. Checking if has partial access (of any type)...");
}
- session.access(RangerPolicyEngine.ANY_ACCESS)
+
+ session.resourceMatchingScope(RangerAccessRequest.ResourceMatchingScope.SELF_OR_DESCENDANTS)
.buildRequest()
.authorize();
auditEvent = auditHandler.getAndDiscardMostRecentEvent(); // capture it only for failure
@@ -421,17 +422,17 @@ ColumnFamilyAccessResult evaluateAccess(String operation, Action action, final R
familesAccessIndeterminate.add(family);
} else {
if (LOG.isDebugEnabled()) {
- LOG.debug("evaluateAccess: has no access of any (of any type) in family [" + family + "]");
+ LOG.debug("evaluateAccess: has no access of ["+ access + "] type in family [" + family + "]");
}
familesAccessDenied.add(family);
- denialReason = String.format("Insufficient permissions for user ‘%s',action: %s, tableName:%s, family:%s, no columns found.", user.getName(), operation, table, family);
+ denialReason = String.format("Insufficient permissions for user ‘%s',action: %s, tableName:%s, family:%s.", user.getName(), operation, table, family);
if (auditEvent != null && deniedEvent == null) { // we need to capture just one denial event
LOG.debug("evaluateAccess: Setting denied access audit event with last auth failure audit event.");
deniedEvent = auditEvent;
}
}
- // Restore the access back
- session.access(access);
+ // Restore the headMatch setting
+ session.resourceMatchingScope(RangerAccessRequest.ResourceMatchingScope.SELF);
}
} else {
LOG.debug("evaluateAccess: columns collection not empty. Skipping Family level check, will do finer level access check.");
diff --git a/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/RangerAuthorizationCoprocessorBase.java b/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/RangerAuthorizationCoprocessorBase.java
index 31f9e2264da..9a5bf05a3f1 100644
--- a/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/RangerAuthorizationCoprocessorBase.java
+++ b/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/RangerAuthorizationCoprocessorBase.java
@@ -21,6 +21,8 @@
import java.io.IOException;
import java.util.List;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellScanner;
import org.apache.hadoop.hbase.CoprocessorEnvironment;
@@ -60,6 +62,8 @@
public abstract class RangerAuthorizationCoprocessorBase extends BaseRegionObserver
implements MasterObserver, RegionServerObserver, BulkLoadObserver {
+ private static final Log LOG = LogFactory.getLog(RangerAuthorizationCoprocessorBase.class.getName());
+
@Override
public void preMergeCommit(
ObserverContext ctx,
@@ -227,10 +231,19 @@ public void postReplicateLogEntries(final ObserverContext ctx, List tableNamesList, List descriptors) throws IOException {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug(String.format("==> postGetTableDescriptors(count(tableNamesList)=%s, count(descriptors)=%s)", tableNamesList == null ? 0 : tableNamesList.size(),
+ descriptors == null ? 0 : descriptors.size()));
+ }
+
}
@Override
public void preGetTableDescriptors(ObserverContext ctx, List tableNamesList, List descriptors, String regex) throws IOException {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug(String.format("==> postGetTableDescriptors(count(tableNamesList)=%s, count(descriptors)=%s, regex=%s)", tableNamesList == null ? 0 : tableNamesList.size(),
+ descriptors == null ? 0 : descriptors.size(), regex));
+ }
}
public void preGetTableNames(ObserverContext ctx, List descriptors, String regex) throws IOException {
From 60ae01301f43394a6f53580f8927cb15b7911b2d Mon Sep 17 00:00:00 2001
From: Gautam Borad
Date: Thu, 18 Jun 2015 22:25:06 +0530
Subject: [PATCH 008/202] RANGER-559 : Fix ID preservation for MSSQL
---
security-admin/scripts/db_setup.py | 12 ++-
.../org/apache/ranger/biz/ServiceDBStore.java | 14 +++
.../org/apache/ranger/common/db/BaseDao.java | 34 ++++++++
.../ranger/solr/SolrAccessAuditsService.java | 9 ++
.../main/webapp/WEB-INF/db_patch.log4j.xml | 87 +++++++++++++++++++
.../apache/ranger/biz/TestServiceDBStore.java | 26 +++---
6 files changed, 168 insertions(+), 14 deletions(-)
create mode 100644 security-admin/src/main/webapp/WEB-INF/db_patch.log4j.xml
diff --git a/security-admin/scripts/db_setup.py b/security-admin/scripts/db_setup.py
index 67f2a43c9f4..35f4dc93991 100644
--- a/security-admin/scripts/db_setup.py
+++ b/security-admin/scripts/db_setup.py
@@ -327,6 +327,7 @@ def execute_java_patches(self, xa_db_host, db_user, db_password, db_name):
version = ""
className = ""
app_home = os.path.join(RANGER_ADMIN_HOME,"ews","webapp")
+ ranger_log = os.path.join(RANGER_ADMIN_HOME,"ews","logs")
javaFiles = os.path.join(app_home,"WEB-INF","classes","org","apache","ranger","patch")
if not os.path.exists(javaFiles):
@@ -366,7 +367,7 @@ def execute_java_patches(self, xa_db_host, db_user, db_password, db_name):
path = os.path.join("%s","WEB-INF","classes","conf:%s","WEB-INF","classes","lib","*:%s","WEB-INF",":%s","META-INF",":%s","WEB-INF","lib","*:%s","WEB-INF","classes",":%s","WEB-INF","classes","META-INF:%s" )%(app_home ,app_home ,app_home, app_home, app_home, app_home ,app_home ,self.SQL_CONNECTOR_JAR)
elif os_name == "WINDOWS":
path = os.path.join("%s","WEB-INF","classes","conf;%s","WEB-INF","classes","lib","*;%s","WEB-INF",";%s","META-INF",";%s","WEB-INF","lib","*;%s","WEB-INF","classes",";%s","WEB-INF","classes","META-INF;%s" )%(app_home ,app_home ,app_home, app_home, app_home, app_home ,app_home ,self.SQL_CONNECTOR_JAR)
- get_cmd = "%s -cp %s org.apache.ranger.patch.%s"%(self.JAVA_BIN,path,className)
+ get_cmd = "%s -Dlogdir=%s -Dlog4j.configuration=db_patch.log4j.xml -cp %s org.apache.ranger.patch.%s"%(self.JAVA_BIN,ranger_log,path,className)
if os_name == "LINUX":
ret = subprocess.call(shlex.split(get_cmd))
elif os_name == "WINDOWS":
@@ -591,6 +592,7 @@ def execute_java_patches(self, xa_db_host, db_user, db_password, db_name):
version = ""
className = ""
app_home = os.path.join(RANGER_ADMIN_HOME,"ews","webapp")
+ ranger_log = os.path.join(RANGER_ADMIN_HOME,"ews","logs")
javaFiles = os.path.join(app_home,"WEB-INF","classes","org","apache","ranger","patch")
if not os.path.exists(javaFiles):
@@ -630,7 +632,7 @@ def execute_java_patches(self, xa_db_host, db_user, db_password, db_name):
path = os.path.join("%s","WEB-INF","classes","conf:%s","WEB-INF","classes","lib","*:%s","WEB-INF",":%s","META-INF",":%s","WEB-INF","lib","*:%s","WEB-INF","classes",":%s","WEB-INF","classes","META-INF:%s" )%(app_home ,app_home ,app_home, app_home, app_home, app_home ,app_home ,self.SQL_CONNECTOR_JAR)
elif os_name == "WINDOWS":
path = os.path.join("%s","WEB-INF","classes","conf;%s","WEB-INF","classes","lib","*;%s","WEB-INF",";%s","META-INF",";%s","WEB-INF","lib","*;%s","WEB-INF","classes",";%s","WEB-INF","classes","META-INF;%s" )%(app_home ,app_home ,app_home, app_home, app_home, app_home ,app_home ,self.SQL_CONNECTOR_JAR)
- get_cmd = "%s -cp %s org.apache.ranger.patch.%s"%(self.JAVA_BIN,path,className)
+ get_cmd = "%s -Dlogdir=%s -Dlog4j.configuration=db_patch.log4j.xml -cp %s org.apache.ranger.patch.%s"%(self.JAVA_BIN,ranger_log,path,className)
if os_name == "LINUX":
ret = subprocess.call(shlex.split(get_cmd))
elif os_name == "WINDOWS":
@@ -838,6 +840,7 @@ def execute_java_patches(self, xa_db_host, db_user, db_password, db_name):
version = ""
className = ""
app_home = os.path.join(RANGER_ADMIN_HOME,"ews","webapp")
+ ranger_log = os.path.join(RANGER_ADMIN_HOME,"ews","logs")
javaFiles = os.path.join(app_home,"WEB-INF","classes","org","apache","ranger","patch")
if not os.path.exists(javaFiles):
@@ -877,7 +880,7 @@ def execute_java_patches(self, xa_db_host, db_user, db_password, db_name):
path = os.path.join("%s","WEB-INF","classes","conf:%s","WEB-INF","classes","lib","*:%s","WEB-INF",":%s","META-INF",":%s","WEB-INF","lib","*:%s","WEB-INF","classes",":%s","WEB-INF","classes","META-INF:%s")%(app_home ,app_home ,app_home, app_home, app_home, app_home ,app_home ,self.SQL_CONNECTOR_JAR)
elif os_name == "WINDOWS":
path = os.path.join("%s","WEB-INF","classes","conf;%s","WEB-INF","classes","lib","*;%s","WEB-INF",";%s","META-INF",";%s","WEB-INF","lib","*;%s","WEB-INF","classes",";%s","WEB-INF","classes","META-INF;%s")%(app_home ,app_home ,app_home, app_home, app_home, app_home ,app_home ,self.SQL_CONNECTOR_JAR)
- get_cmd = "%s -cp %s org.apache.ranger.patch.%s"%(self.JAVA_BIN,path,className)
+ get_cmd = "%s -Dlogdir=%s -Dlog4j.configuration=db_patch.log4j.xml -cp %s org.apache.ranger.patch.%s"%(self.JAVA_BIN,ranger_log,path,className)
if os_name == "LINUX":
ret = subprocess.call(shlex.split(get_cmd))
elif os_name == "WINDOWS":
@@ -1073,6 +1076,7 @@ def execute_java_patches(self, xa_db_host, db_user, db_password, db_name):
version = ""
className = ""
app_home = os.path.join(RANGER_ADMIN_HOME,"ews","webapp")
+ ranger_log = os.path.join(RANGER_ADMIN_HOME,"ews","logs")
javaFiles = os.path.join(app_home,"WEB-INF","classes","org","apache","ranger","patch")
if not os.path.exists(javaFiles):
@@ -1112,7 +1116,7 @@ def execute_java_patches(self, xa_db_host, db_user, db_password, db_name):
path = os.path.join("%s","WEB-INF","classes","conf:%s","WEB-INF","classes","lib","*:%s","WEB-INF",":%s","META-INF",":%s","WEB-INF","lib","*:%s","WEB-INF","classes",":%s","WEB-INF","classes","META-INF:%s" )%(app_home ,app_home ,app_home, app_home, app_home, app_home ,app_home ,self.SQL_CONNECTOR_JAR)
elif os_name == "WINDOWS":
path = os.path.join("%s","WEB-INF","classes","conf;%s","WEB-INF","classes","lib","*;%s","WEB-INF",";%s","META-INF",";%s","WEB-INF","lib","*;%s","WEB-INF","classes",";%s","WEB-INF","classes","META-INF;%s" )%(app_home ,app_home ,app_home, app_home, app_home, app_home ,app_home ,self.SQL_CONNECTOR_JAR)
- get_cmd = "%s -cp %s org.apache.ranger.patch.%s"%(self.JAVA_BIN,path,className)
+ get_cmd = "%s -Dlogdir=%s -Dlog4j.configuration=db_patch.log4j.xml -cp %s org.apache.ranger.patch.%s"%(self.JAVA_BIN,ranger_log,path,className)
if os_name == "LINUX":
ret = subprocess.call(shlex.split(get_cmd))
elif os_name == "WINDOWS":
diff --git a/security-admin/src/main/java/org/apache/ranger/biz/ServiceDBStore.java b/security-admin/src/main/java/org/apache/ranger/biz/ServiceDBStore.java
index ff04d3fc1b3..326cae0052e 100644
--- a/security-admin/src/main/java/org/apache/ranger/biz/ServiceDBStore.java
+++ b/security-admin/src/main/java/org/apache/ranger/biz/ServiceDBStore.java
@@ -262,9 +262,13 @@ public RangerServiceDef createServiceDef(RangerServiceDef serviceDef) throws Exc
if (populateExistingBaseFields) {
svcDefServiceWithAssignedId.setPopulateExistingBaseFields(true);
+ daoMgr.getXXServiceDef().setIdentityInsert(true);
+
svcDefServiceWithAssignedId.create(serviceDef);
+
svcDefServiceWithAssignedId.setPopulateExistingBaseFields(false);
daoMgr.getXXServiceDef().updateSequence();
+ daoMgr.getXXServiceDef().setIdentityInsert(false);
} else {
// following fields will be auto populated
serviceDef.setId(null);
@@ -1009,7 +1013,12 @@ public RangerService createService(RangerService service) throws Exception {
if (populateExistingBaseFields) {
svcServiceWithAssignedId.setPopulateExistingBaseFields(true);
+ daoMgr.getXXService().setIdentityInsert(true);
+
service = svcServiceWithAssignedId.create(service);
+
+ daoMgr.getXXService().setIdentityInsert(false);
+ daoMgr.getXXService().updateSequence();
svcServiceWithAssignedId.setPopulateExistingBaseFields(false);
createDefaultPolicy = false;
} else {
@@ -1359,7 +1368,12 @@ public RangerPolicy createPolicy(RangerPolicy policy) throws Exception {
if(populateExistingBaseFields) {
assignedIdPolicyService.setPopulateExistingBaseFields(true);
+ daoMgr.getXXPolicy().setIdentityInsert(true);
+
policy = assignedIdPolicyService.create(policy);
+
+ daoMgr.getXXPolicy().setIdentityInsert(false);
+ daoMgr.getXXPolicy().updateSequence();
assignedIdPolicyService.setPopulateExistingBaseFields(false);
} else {
policy = policyService.create(policy);
diff --git a/security-admin/src/main/java/org/apache/ranger/common/db/BaseDao.java b/security-admin/src/main/java/org/apache/ranger/common/db/BaseDao.java
index bfa4c4018bb..aaa4fa59e31 100644
--- a/security-admin/src/main/java/org/apache/ranger/common/db/BaseDao.java
+++ b/security-admin/src/main/java/org/apache/ranger/common/db/BaseDao.java
@@ -23,12 +23,15 @@
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
+import java.sql.Connection;
+import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;
+import javax.persistence.Table;
import javax.persistence.TypedQuery;
import org.apache.log4j.Logger;
@@ -231,4 +234,35 @@ public void updateSequence(String seqName, long nextValue) {
}
+ public void setIdentityInsert(boolean identityInsert) {
+ if (RangerBizUtil.getDBFlavor() != AppConstants.DB_FLAVOR_SQLSERVER) {
+ logger.debug("Ignoring BaseDao.setIdentityInsert(). This should be executed if DB flavor is sqlserver.");
+ return;
+ }
+
+ EntityManager entityMgr = getEntityManager();
+
+ String identityInsertStr;
+ if (identityInsert) {
+ identityInsertStr = "ON";
+ } else {
+ identityInsertStr = "OFF";
+ }
+
+ Table table = tClass.getAnnotation(Table.class);
+
+ if(table == null) {
+ throw new NullPointerException("Required annotation `Table` not found");
+ }
+
+ String tableName = table.name();
+
+ Connection conn = entityMgr.unwrap(Connection.class);
+ try {
+ conn.createStatement().execute("SET IDENTITY_INSERT " + tableName + " " + identityInsertStr);
+ } catch (SQLException e) {
+ logger.error("Error while settion identity_insert " + identityInsertStr, e);
+ }
+ }
+
}
diff --git a/security-admin/src/main/java/org/apache/ranger/solr/SolrAccessAuditsService.java b/security-admin/src/main/java/org/apache/ranger/solr/SolrAccessAuditsService.java
index ad198227145..5fc45d256e2 100644
--- a/security-admin/src/main/java/org/apache/ranger/solr/SolrAccessAuditsService.java
+++ b/security-admin/src/main/java/org/apache/ranger/solr/SolrAccessAuditsService.java
@@ -32,6 +32,8 @@
import org.apache.ranger.common.SearchField.DATA_TYPE;
import org.apache.ranger.common.SearchField.SEARCH_TYPE;
import org.apache.ranger.common.SortField.SORT_ORDER;
+import org.apache.ranger.db.RangerDaoManager;
+import org.apache.ranger.entity.XXServiceDef;
import org.apache.ranger.view.VXAccessAudit;
import org.apache.ranger.view.VXAccessAuditList;
import org.apache.ranger.view.VXLong;
@@ -60,6 +62,9 @@ public class SolrAccessAuditsService {
@Autowired
StringUtil stringUtil;
+ @Autowired
+ RangerDaoManager daoManager;
+
public List sortFields = new ArrayList();
public List searchFields = new ArrayList();
@@ -221,6 +226,10 @@ private VXAccessAudit populateViewBean(SolrDocument doc) {
value = doc.getFieldValue("repoType");
if (value != null) {
accessAudit.setRepoType(solrUtil.toInt(value));
+ XXServiceDef xServiceDef = daoManager.getXXServiceDef().getById((long) accessAudit.getRepoType());
+ if (xServiceDef != null) {
+ accessAudit.setServiceType(xServiceDef.getName());
+ }
}
value = doc.getFieldValue("resType");
if (value != null) {
diff --git a/security-admin/src/main/webapp/WEB-INF/db_patch.log4j.xml b/security-admin/src/main/webapp/WEB-INF/db_patch.log4j.xml
new file mode 100644
index 00000000000..1aafb071e14
--- /dev/null
+++ b/security-admin/src/main/webapp/WEB-INF/db_patch.log4j.xml
@@ -0,0 +1,87 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/security-admin/src/test/java/org/apache/ranger/biz/TestServiceDBStore.java b/security-admin/src/test/java/org/apache/ranger/biz/TestServiceDBStore.java
index 6f95a8a7e94..e13b862aaac 100644
--- a/security-admin/src/test/java/org/apache/ranger/biz/TestServiceDBStore.java
+++ b/security-admin/src/test/java/org/apache/ranger/biz/TestServiceDBStore.java
@@ -1160,13 +1160,17 @@ public void test18getPaginatedServiceDefs() throws Exception {
@Test
public void test19createService() throws Exception {
- XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class);
+ XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class);
XXServiceConfigMapDao xServiceConfigMapDao = Mockito
.mock(XXServiceConfigMapDao.class);
XXUserDao xUserDao = Mockito.mock(XXUserDao.class);
XXServiceConfigDefDao xServiceConfigDefDao = Mockito
.mock(XXServiceConfigDefDao.class);
XXService xService = Mockito.mock(XXService.class);
+ XXService xService2 = new XXService();
+ xService2.setId(1L);
+ xService2.setName("Test");
+ xService2.setType(1L);
XXUser xUser = Mockito.mock(XXUser.class);
RangerService rangerService = rangerService();
@@ -1183,8 +1187,7 @@ public void test19createService() throws Exception {
Mockito.when(xServiceConfigDefDao.findByServiceDefName(userName))
.thenReturn(svcConfDefList);
- Mockito.when(svcServiceWithAssignedId.create(rangerService))
- .thenReturn(rangerService);
+ Mockito.when(svcService.create(rangerService)).thenReturn(rangerService);
Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao);
Mockito.when(xServiceDao.getById(rangerService.getId())).thenReturn(
@@ -1207,18 +1210,21 @@ public void test19createService() throws Exception {
Mockito.when(svcService.getPopulatedViewObject(xService)).thenReturn(
rangerService);
- serviceDBStore.setPopulateExistingBaseFields(true);
+ Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao);
+ Mockito.when(xServiceDao.getById(Mockito.anyLong())).thenReturn(xService2);
Mockito.when(
rangerAuditFields.populateAuditFields(
Mockito.isA(XXServiceConfigMap.class),
Mockito.isA(XXService.class))).thenReturn(xConfMap);
-
- RangerService dbRangerService = serviceDBStore
- .createService(rangerService);
- serviceDBStore.setPopulateExistingBaseFields(false);
- Assert.assertNotNull(dbRangerService);
- Mockito.verify(daoManager).getXXService();
+
+ RangerServiceDef ran = new RangerServiceDef();
+ ran.setName("Test");
+ Mockito.when(serviceDefService.read(1L)).thenReturn(ran);
+
+ serviceDBStore.createService(rangerService);
+
+ Mockito.verify(daoManager, Mockito.atLeast(1)).getXXService();
Mockito.verify(daoManager).getXXServiceConfigMap();
}
From 19aa95ec7df94e543a6533bcf992c0e7d09ce620 Mon Sep 17 00:00:00 2001
From: Gautam Borad
Date: Fri, 19 Jun 2015 18:33:59 -0400
Subject: [PATCH 009/202] RANGER-562: Policy migration updated to ignore
incorrect permission type and continue with migration
Signed-off-by: Madhan Neethiraj
---
.../ranger/patch/PatchMigration_J10002.java | 28 ++++++++++++++++++-
1 file changed, 27 insertions(+), 1 deletion(-)
diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchMigration_J10002.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchMigration_J10002.java
index 1747324e900..44306d83c97 100644
--- a/security-admin/src/main/java/org/apache/ranger/patch/PatchMigration_J10002.java
+++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchMigration_J10002.java
@@ -20,10 +20,13 @@
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
+import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
+import java.util.Set;
+import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.ranger.biz.RangerBizUtil;
@@ -91,6 +94,15 @@ public class PatchMigration_J10002 extends BaseLoader {
private static int policyCounter = 0;
private static int serviceCounter = 0;
+ static Set unsupportedLegacyPermTypes = new HashSet();
+
+ static {
+ unsupportedLegacyPermTypes.add("Unknown");
+ unsupportedLegacyPermTypes.add("Reset");
+ unsupportedLegacyPermTypes.add("Obfuscate");
+ unsupportedLegacyPermTypes.add("Mask");
+ }
+
public static void main(String[] args) {
logger.info("main()");
try {
@@ -451,6 +463,10 @@ private List getPolicyItemListForRes(XXResource xRes, XXServic
}
String accessType = ServiceUtil.toAccessType(permMap.getPermType());
+ if(StringUtils.isBlank(accessType) || unsupportedLegacyPermTypes.contains(accessType)) {
+ logger.info(accessType + ": is not a valid access-type, ignoring accesstype for policy: " + xRes.getPolicyName());
+ continue;
+ }
if(StringUtils.equalsIgnoreCase(accessType, "Admin")) {
policyItem.setDelegateAdmin(Boolean.TRUE);
@@ -464,6 +480,16 @@ private List getPolicyItemListForRes(XXResource xRes, XXServic
ipAddress = permMap.getIpAddress();
}
+ if(CollectionUtils.isEmpty(accessList)) {
+ logger.info("no access specified. ignoring policyItem for policy: " + xRes.getPolicyName());
+ continue;
+ }
+
+ if(CollectionUtils.isEmpty(userList) && CollectionUtils.isEmpty(groupList)) {
+ logger.info("no user or group specified. ignoring policyItem for policy: " + xRes.getPolicyName());
+ continue;
+ }
+
policyItem.setUsers(userList);
policyItem.setGroups(groupList);
policyItem.setAccesses(accessList);
@@ -525,4 +551,4 @@ private String getGroupName(VXPermMap permMap) {
return groupName;
}
-}
\ No newline at end of file
+}
From 10f21940e310482d5a68eb225469835f2eb0861d Mon Sep 17 00:00:00 2001
From: Velmurugan Periasamy
Date: Tue, 23 Jun 2015 18:40:53 -0400
Subject: [PATCH 010/202] RANGER-565: Fixed Oracle JDBC driver issue causing
dba_script/db_setup failure with java.sql.SQLRecoverableException: IO Error
when using Oracle
Signed-off-by: sneethiraj
---
kms/scripts/db_setup.py | 1 +
kms/scripts/dba_script.py | 1 +
security-admin/scripts/db_setup.py | 3 ++-
security-admin/scripts/dba_script.py | 3 +++
4 files changed, 7 insertions(+), 1 deletion(-)
diff --git a/kms/scripts/db_setup.py b/kms/scripts/db_setup.py
index fd10f4ec8a7..8116049a270 100644
--- a/kms/scripts/db_setup.py
+++ b/kms/scripts/db_setup.py
@@ -190,6 +190,7 @@ def get_jisql_cmd(self, user, password):
#path = os.getcwd()
path = RANGER_KMS_HOME
self.JAVA_BIN = self.JAVA_BIN.strip("'")
+ self.JAVA_BIN = self.JAVA_BIN + " -Djava.security.egd=file:///dev/urandom "
if os_name == "LINUX":
jisql_cmd = "%s -cp %s:%s/jisql/lib/* org.apache.util.sql.Jisql -driver oraclethin -cstring jdbc:oracle:thin:@%s -u '%s' -p '%s' -noheader -trim" %(self.JAVA_BIN, self.SQL_CONNECTOR_JAR,path, self.host, user, password)
elif os_name == "WINDOWS":
diff --git a/kms/scripts/dba_script.py b/kms/scripts/dba_script.py
index 2a3d5d79162..c549fadd64c 100644
--- a/kms/scripts/dba_script.py
+++ b/kms/scripts/dba_script.py
@@ -326,6 +326,7 @@ def __init__(self, host, SQL_CONNECTOR_JAR, JAVA_BIN):
def get_jisql_cmd(self, user, password):
#TODO: User array for forming command
path = RANGER_KMS_HOME
+ self.JAVA_BIN = self.JAVA_BIN + " -Djava.security.egd=file:///dev/urandom "
if os_name == "LINUX":
jisql_cmd = "%s -cp %s:%s/jisql/lib/* org.apache.util.sql.Jisql -driver oraclethin -cstring jdbc:oracle:thin:@%s -u '%s' -p '%s' -noheader -trim" %(self.JAVA_BIN, self.SQL_CONNECTOR_JAR,path, self.host, user, password)
elif os_name == "WINDOWS":
diff --git a/security-admin/scripts/db_setup.py b/security-admin/scripts/db_setup.py
index 35f4dc93991..90d7d4eaa87 100644
--- a/security-admin/scripts/db_setup.py
+++ b/security-admin/scripts/db_setup.py
@@ -398,6 +398,7 @@ def __init__(self, host, SQL_CONNECTOR_JAR, JAVA_BIN):
def get_jisql_cmd(self, user, password):
path = RANGER_ADMIN_HOME
self.JAVA_BIN = self.JAVA_BIN.strip("'")
+ self.JAVA_BIN = self.JAVA_BIN + " -Djava.security.egd=file:///dev/urandom "
if os_name == "LINUX":
jisql_cmd = "%s -cp %s:%s/jisql/lib/* org.apache.util.sql.Jisql -driver oraclethin -cstring jdbc:oracle:thin:@%s -u '%s' -p '%s' -noheader -trim" %(self.JAVA_BIN, self.SQL_CONNECTOR_JAR, path, self.host, user, password)
elif os_name == "WINDOWS":
@@ -632,7 +633,7 @@ def execute_java_patches(self, xa_db_host, db_user, db_password, db_name):
path = os.path.join("%s","WEB-INF","classes","conf:%s","WEB-INF","classes","lib","*:%s","WEB-INF",":%s","META-INF",":%s","WEB-INF","lib","*:%s","WEB-INF","classes",":%s","WEB-INF","classes","META-INF:%s" )%(app_home ,app_home ,app_home, app_home, app_home, app_home ,app_home ,self.SQL_CONNECTOR_JAR)
elif os_name == "WINDOWS":
path = os.path.join("%s","WEB-INF","classes","conf;%s","WEB-INF","classes","lib","*;%s","WEB-INF",";%s","META-INF",";%s","WEB-INF","lib","*;%s","WEB-INF","classes",";%s","WEB-INF","classes","META-INF;%s" )%(app_home ,app_home ,app_home, app_home, app_home, app_home ,app_home ,self.SQL_CONNECTOR_JAR)
- get_cmd = "%s -Dlogdir=%s -Dlog4j.configuration=db_patch.log4j.xml -cp %s org.apache.ranger.patch.%s"%(self.JAVA_BIN,ranger_log,path,className)
+ get_cmd = "%s -Djava.security.egd=file:///dev/urandom -Dlogdir=%s -Dlog4j.configuration=db_patch.log4j.xml -cp %s org.apache.ranger.patch.%s"%(self.JAVA_BIN,ranger_log,path,className)
if os_name == "LINUX":
ret = subprocess.call(shlex.split(get_cmd))
elif os_name == "WINDOWS":
diff --git a/security-admin/scripts/dba_script.py b/security-admin/scripts/dba_script.py
index a3737edf1ef..133af155bb4 100644
--- a/security-admin/scripts/dba_script.py
+++ b/security-admin/scripts/dba_script.py
@@ -333,10 +333,13 @@ def __init__(self, host, SQL_CONNECTOR_JAR, JAVA_BIN):
def get_jisql_cmd(self, user, password):
#TODO: User array for forming command
path = RANGER_ADMIN_HOME
+ #print "self.JAVA_BIN=" + self.JAVA_BIN
+ self.JAVA_BIN = self.JAVA_BIN + " -Djava.security.egd=file:///dev/urandom "
if os_name == "LINUX":
jisql_cmd = "%s -cp %s:%s/jisql/lib/* org.apache.util.sql.Jisql -driver oraclethin -cstring jdbc:oracle:thin:@%s -u '%s' -p '%s' -noheader -trim" %(self.JAVA_BIN, self.SQL_CONNECTOR_JAR,path, self.host, user, password)
elif os_name == "WINDOWS":
jisql_cmd = "%s -cp %s;%s\jisql\\lib\\* org.apache.util.sql.Jisql -driver oraclethin -cstring jdbc:oracle:thin:@%s -u %s -p %s -noheader -trim" %(self.JAVA_BIN, self.SQL_CONNECTOR_JAR, path, self.host, user, password)
+ #print jisql_cmd
return jisql_cmd
def check_connection(self, db_name, db_user, db_password):
From 89f6eed17fd51b64e49e2f6b2f6c0fc0e6d224f8 Mon Sep 17 00:00:00 2001
From: sneethiraj
Date: Tue, 23 Jun 2015 21:54:27 -0700
Subject: [PATCH 011/202] RANGER-566: modified to use private synonym for
ranger-admin installation on oracle
---
.../db/oracle/xa_core_db_oracle.sql | 3 --
security-admin/scripts/db_setup.py | 27 ++++++++++++++++++
security-admin/scripts/dba_script.py | 28 +++++++++----------
security-admin/scripts/setup.sh | 4 +--
4 files changed, 43 insertions(+), 19 deletions(-)
diff --git a/security-admin/db/oracle/xa_core_db_oracle.sql b/security-admin/db/oracle/xa_core_db_oracle.sql
index 9cc22ff0705..2ede81037cb 100644
--- a/security-admin/db/oracle/xa_core_db_oracle.sql
+++ b/security-admin/db/oracle/xa_core_db_oracle.sql
@@ -429,9 +429,6 @@ CREATE INDEX x_user_FK_upd_by_id ON x_user (upd_by_id);
CREATE INDEX x_user_FK_cred_store_id ON x_user (cred_store_id);
CREATE INDEX x_user_cr_time ON x_user (create_time);
CREATE INDEX x_user_up_time ON x_user(update_time);
-
-CREATE OR REPLACE PUBLIC SYNONYM xa_access_audit FOR xa_access_audit;
-CREATE OR REPLACE PUBLIC SYNONYM XA_ACCESS_AUDIT_SEQ FOR XA_ACCESS_AUDIT_SEQ;
commit;
insert into x_portal_user (
id,CREATE_TIME, UPDATE_TIME,
diff --git a/security-admin/scripts/db_setup.py b/security-admin/scripts/db_setup.py
index 90d7d4eaa87..0d6c49b5029 100644
--- a/security-admin/scripts/db_setup.py
+++ b/security-admin/scripts/db_setup.py
@@ -147,6 +147,9 @@ def apply_auditdb_patches(self, xa_sqlObj,xa_db_host, audit_db_host, db_name, au
def execute_java_patches(xa_db_host, db_user, db_password, db_name):
log("[I] ----------------- Executing java patches ------------", "info")
+ def create_synonym(db_name, db_user, db_password,audit_db_user):
+ log("[I] ----------------- Creating Synonym ------------", "info")
+
class MysqlConf(BaseDB):
# Constructor
def __init__(self, host,SQL_CONNECTOR_JAR,JAVA_BIN):
@@ -465,6 +468,26 @@ def import_db_file(self, db_name, db_user, db_password, file_name):
log("[E] "+name + " import failed!","error")
sys.exit(1)
+ def create_synonym(self,db_name, db_user, db_password,audit_db_user):
+ log("[I] ----------------- Creating Synonym ------------", "info")
+ get_cmd = self.get_jisql_cmd(db_user, db_password)
+ if os_name == "LINUX":
+ query = get_cmd + " -c \; -query 'CREATE OR REPLACE SYNONYM %s.XA_ACCESS_AUDIT FOR %s.XA_ACCESS_AUDIT;'" % (audit_db_user,db_user)
+ ret = subprocess.call(shlex.split(query))
+ elif os_name == "WINDOWS":
+ query = get_cmd + " -query \"CREATE OR REPLACE SYNONYM %s.XA_ACCESS_AUDIT FOR %s.XA_ACCESS_AUDIT;\" -c ;" % (audit_db_user,db_user)
+ ret = subprocess.call(query)
+ if ret != 0:
+ sys.exit(1)
+ if os_name == "LINUX":
+ query = get_cmd + " -c \; -query 'CREATE OR REPLACE SYNONYM %s.XA_ACCESS_AUDIT_SEQ FOR %s.XA_ACCESS_AUDIT_SEQ;'" % (audit_db_user,db_user)
+ ret = subprocess.call(shlex.split(query))
+ elif os_name == "WINDOWS":
+ query = get_cmd + " -query \"CREATE OR REPLACE SYNONYM %s.XA_ACCESS_AUDIT_SEQ FOR %s.XA_ACCESS_AUDIT_SEQ;\" -c ;" % (audit_db_user,db_user)
+ ret = subprocess.call(query)
+ if ret != 0:
+ sys.exit(1)
+
def import_db_patches(self, db_name, db_user, db_password, file_name):
if os.path.isfile(file_name):
name = basename(file_name)
@@ -1285,6 +1308,10 @@ def main(argv):
else:
log("[I] --------- Importing Ranger Core DB Schema ---------","info")
xa_sqlObj.import_db_file(db_name, db_user, db_password, xa_db_core_file)
+ if XA_DB_FLAVOR == "ORACLE":
+ if xa_sqlObj.check_table(db_name, db_user, db_password, xa_access_audit):
+ if db_user != audit_db_user:
+ xa_sqlObj.create_synonym(db_name, db_user, db_password,audit_db_user)
log("[I] --------- Verifying upgrade history table ---------","info")
output = xa_sqlObj.check_table(db_name, db_user, db_password, x_db_version)
if output == False:
diff --git a/security-admin/scripts/dba_script.py b/security-admin/scripts/dba_script.py
index 133af155bb4..045990dc625 100644
--- a/security-admin/scripts/dba_script.py
+++ b/security-admin/scripts/dba_script.py
@@ -391,10 +391,10 @@ def create_rangerdb_user(self, root_user, db_user, db_password, db_root_password
log("[I] User " + db_user + " created", "info")
log("[I] Granting permission to " + db_user, "info")
if os_name == "LINUX":
- query = get_cmd + " -c \; -query 'GRANT CREATE SESSION,CREATE PROCEDURE,CREATE TABLE,CREATE VIEW,CREATE SEQUENCE,CREATE PUBLIC SYNONYM,CREATE TRIGGER,UNLIMITED Tablespace TO %s WITH ADMIN OPTION;'" % (db_user)
+ query = get_cmd + " -c \; -query 'GRANT CREATE SESSION,CREATE PROCEDURE,CREATE TABLE,CREATE VIEW,CREATE SEQUENCE,CREATE PUBLIC SYNONYM,CREATE ANY SYNONYM,CREATE TRIGGER,UNLIMITED Tablespace TO %s WITH ADMIN OPTION;'" % (db_user)
ret = subprocess.call(shlex.split(query))
elif os_name == "WINDOWS":
- query = get_cmd + " -query \"GRANT CREATE SESSION,CREATE PROCEDURE,CREATE TABLE,CREATE VIEW,CREATE SEQUENCE,CREATE PUBLIC SYNONYM,CREATE TRIGGER,UNLIMITED Tablespace TO %s WITH ADMIN OPTION;\" -c ;" % (db_user)
+ query = get_cmd + " -query \"GRANT CREATE SESSION,CREATE PROCEDURE,CREATE TABLE,CREATE VIEW,CREATE SEQUENCE,CREATE PUBLIC SYNONYM,CREATE ANY SYNONYM,CREATE TRIGGER,UNLIMITED Tablespace TO %s WITH ADMIN OPTION;\" -c ;" % (db_user)
ret = subprocess.call(query)
if ret == 0:
log("[I] Granting permissions to Oracle user '" + db_user + "' for %s done" %(self.host), "info")
@@ -483,10 +483,10 @@ def assign_tablespace(self, root_user, db_root_password, db_user, db_password, d
if ret == 0:
log("[I] Granting permission to " + db_user, "info")
if os_name == "LINUX":
- query = get_cmd + " -c \; -query 'GRANT CREATE SESSION,CREATE PROCEDURE,CREATE TABLE,CREATE VIEW,CREATE SEQUENCE,CREATE PUBLIC SYNONYM,CREATE TRIGGER,UNLIMITED Tablespace TO %s WITH ADMIN OPTION;'" % (db_user)
+ query = get_cmd + " -c \; -query 'GRANT CREATE SESSION,CREATE PROCEDURE,CREATE TABLE,CREATE VIEW,CREATE SEQUENCE,CREATE PUBLIC SYNONYM,CREATE ANY SYNONYM,CREATE TRIGGER,UNLIMITED Tablespace TO %s WITH ADMIN OPTION;'" % (db_user)
ret = subprocess.call(shlex.split(query))
elif os_name == "WINDOWS":
- query = get_cmd + " -query \"GRANT CREATE SESSION,CREATE PROCEDURE,CREATE TABLE,CREATE VIEW,CREATE SEQUENCE,CREATE PUBLIC SYNONYM,CREATE TRIGGER,UNLIMITED Tablespace TO %s WITH ADMIN OPTION;\" -c ;" % (db_user)
+ query = get_cmd + " -query \"GRANT CREATE SESSION,CREATE PROCEDURE,CREATE TABLE,CREATE VIEW,CREATE SEQUENCE,CREATE PUBLIC SYNONYM,CREATE ANY SYNONYM,CREATE TRIGGER,UNLIMITED Tablespace TO %s WITH ADMIN OPTION;\" -c ;" % (db_user)
ret = subprocess.call(query)
if ret == 0:
log("[I] Granting Oracle user '" + db_user + "' done", "info")
@@ -499,7 +499,7 @@ def assign_tablespace(self, root_user, db_root_password, db_user, db_password, d
sys.exit(1)
else:
logFile("alter user %s identified by \"%s\" DEFAULT Tablespace %s;" %(db_user, db_password, db_name))
- logFile("GRANT CREATE SESSION,CREATE PROCEDURE,CREATE TABLE,CREATE VIEW,CREATE SEQUENCE,CREATE PUBLIC SYNONYM,CREATE TRIGGER,UNLIMITED Tablespace TO %s WITH ADMIN OPTION;" % (db_user))
+ logFile("GRANT CREATE SESSION,CREATE PROCEDURE,CREATE TABLE,CREATE VIEW,CREATE SEQUENCE,CREATE PUBLIC SYNONYM,CREATE ANY SYNONYM,CREATE TRIGGER,UNLIMITED Tablespace TO %s WITH ADMIN OPTION;" % (db_user))
def create_auditdb(self, audit_db_root_user, db_name ,audit_db_name, db_user, audit_db_user, db_password, audit_db_password, audit_db_root_password,dryMode):
@@ -576,10 +576,10 @@ def create_auditdb(self, audit_db_root_user, db_name ,audit_db_name, db_user, au
if (ret1 == 0 and ret2 == 0):
log("[I] Granting permission to " + db_user, "info")
if os_name == "LINUX":
- query = get_cmd + " -c \; -query 'GRANT CREATE SESSION,CREATE PROCEDURE,CREATE TABLE,CREATE VIEW,CREATE SEQUENCE,CREATE PUBLIC SYNONYM,CREATE TRIGGER,UNLIMITED Tablespace TO %s WITH ADMIN OPTION;'" % (db_user)
+ query = get_cmd + " -c \; -query 'GRANT CREATE SESSION,CREATE PROCEDURE,CREATE TABLE,CREATE VIEW,CREATE SEQUENCE,CREATE PUBLIC SYNONYM,CREATE ANY SYNONYM,CREATE TRIGGER,UNLIMITED Tablespace TO %s WITH ADMIN OPTION;'" % (db_user)
ret = subprocess.call(shlex.split(query))
elif os_name == "WINDOWS":
- query = get_cmd + " -query \"GRANT CREATE SESSION,CREATE PROCEDURE,CREATE TABLE,CREATE VIEW,CREATE SEQUENCE,CREATE PUBLIC SYNONYM,CREATE TRIGGER,UNLIMITED Tablespace TO %s WITH ADMIN OPTION;\" -c ;" % (db_user)
+ query = get_cmd + " -query \"GRANT CREATE SESSION,CREATE PROCEDURE,CREATE TABLE,CREATE VIEW,CREATE SEQUENCE,CREATE PUBLIC SYNONYM,CREATE ANY SYNONYM,CREATE TRIGGER,UNLIMITED Tablespace TO %s WITH ADMIN OPTION;\" -c ;" % (db_user)
ret = subprocess.call(query)
if ret == 0:
return True
@@ -591,16 +591,16 @@ def create_auditdb(self, audit_db_root_user, db_name ,audit_db_name, db_user, au
else:
logFile("alter user %s identified by \"%s\" DEFAULT Tablespace %s;" %(audit_db_user, audit_db_password, db_name))
logFile("alter user %s identified by \"%s\" DEFAULT Tablespace %s;" %(audit_db_user, audit_db_password, audit_db_name))
- logFile("GRANT CREATE SESSION,CREATE PROCEDURE,CREATE TABLE,CREATE VIEW,CREATE SEQUENCE,CREATE PUBLIC SYNONYM,CREATE TRIGGER,UNLIMITED Tablespace TO %s WITH ADMIN OPTION;" % (db_user))
+ logFile("GRANT CREATE SESSION,CREATE PROCEDURE,CREATE TABLE,CREATE VIEW,CREATE SEQUENCE,CREATE PUBLIC SYNONYM,CREATE ANY SYNONYM,CREATE TRIGGER,UNLIMITED Tablespace TO %s WITH ADMIN OPTION;" % (db_user))
def grant_xa_db_user(self, root_user, db_name, db_user, db_password, db_root_password, invoke,dryMode):
if dryMode == False:
get_cmd = self.get_jisql_cmd(root_user ,db_root_password)
if os_name == "LINUX":
- query = get_cmd + " -c \; -query 'GRANT CREATE SESSION,CREATE PROCEDURE,CREATE TABLE,CREATE VIEW,CREATE SEQUENCE,CREATE PUBLIC SYNONYM,CREATE TRIGGER,UNLIMITED Tablespace TO %s WITH ADMIN OPTION;'" % (db_user)
+ query = get_cmd + " -c \; -query 'GRANT CREATE SESSION,CREATE PROCEDURE,CREATE TABLE,CREATE VIEW,CREATE SEQUENCE,CREATE PUBLIC SYNONYM,CREATE ANY SYNONYM,CREATE TRIGGER,UNLIMITED Tablespace TO %s WITH ADMIN OPTION;'" % (db_user)
ret = subprocess.call(shlex.split(query))
elif os_name == "WINDOWS":
- query = get_cmd + " -query \"GRANT CREATE SESSION,CREATE PROCEDURE,CREATE TABLE,CREATE VIEW,CREATE SEQUENCE,CREATE PUBLIC SYNONYM,CREATE TRIGGER,UNLIMITED Tablespace TO %s WITH ADMIN OPTION;\" -c ;" % (db_user)
+ query = get_cmd + " -query \"GRANT CREATE SESSION,CREATE PROCEDURE,CREATE TABLE,CREATE VIEW,CREATE SEQUENCE,CREATE PUBLIC SYNONYM,CREATE ANY SYNONYM,CREATE TRIGGER,UNLIMITED Tablespace TO %s WITH ADMIN OPTION;\" -c ;" % (db_user)
ret = subprocess.call(query)
if ret == 0:
log("[I] Granted permission to " + db_user, "info")
@@ -609,7 +609,7 @@ def grant_xa_db_user(self, root_user, db_name, db_user, db_password, db_root_pas
log("[E] Granting Oracle user '" + db_user + "' failed..", "error")
sys.exit(1)
else:
- logFile("GRANT CREATE SESSION,CREATE PROCEDURE,CREATE TABLE,CREATE VIEW,CREATE SEQUENCE,CREATE PUBLIC SYNONYM,CREATE TRIGGER,UNLIMITED Tablespace TO %s WITH ADMIN OPTION;" % (db_user))
+ logFile("GRANT CREATE SESSION,CREATE PROCEDURE,CREATE TABLE,CREATE VIEW,CREATE SEQUENCE,CREATE PUBLIC SYNONYM,CREATE ANY SYNONYM,CREATE TRIGGER,UNLIMITED Tablespace TO %s WITH ADMIN OPTION;" % (db_user))
def create_auditdb_user(self, xa_db_host , audit_db_host , db_name ,audit_db_name, xa_db_root_user, audit_db_root_user, db_user, audit_db_user, xa_db_root_password, audit_db_root_password, db_password, audit_db_password, DBA_MODE,dryMode):
if DBA_MODE == "TRUE":
@@ -634,10 +634,10 @@ def create_auditdb_user(self, xa_db_host , audit_db_host , db_name ,audit_db_nam
log("[I] User " + db_user + " created", "info")
log("[I] Granting permission to " + db_user, "info")
if os_name == "LINUX":
- query = get_cmd + " -c \; -query 'GRANT CREATE SESSION,CREATE PROCEDURE,CREATE TABLE,CREATE VIEW,CREATE SEQUENCE,CREATE PUBLIC SYNONYM,CREATE TRIGGER,UNLIMITED Tablespace TO %s WITH ADMIN OPTION;'" % (db_user)
+ query = get_cmd + " -c \; -query 'GRANT CREATE SESSION,CREATE PROCEDURE,CREATE TABLE,CREATE VIEW,CREATE SEQUENCE,CREATE PUBLIC SYNONYM,CREATE ANY SYNONYM,CREATE TRIGGER,UNLIMITED Tablespace TO %s WITH ADMIN OPTION;'" % (db_user)
ret = subprocess.call(shlex.split(query))
elif os_name == "WINDOWS":
- query = get_cmd + " -query \"GRANT CREATE SESSION,CREATE PROCEDURE,CREATE TABLE,CREATE VIEW,CREATE SEQUENCE,CREATE PUBLIC SYNONYM,CREATE TRIGGER,UNLIMITED Tablespace TO %s WITH ADMIN OPTION;\" -c ;" % (db_user)
+ query = get_cmd + " -query \"GRANT CREATE SESSION,CREATE PROCEDURE,CREATE TABLE,CREATE VIEW,CREATE SEQUENCE,CREATE PUBLIC SYNONYM,CREATE ANY SYNONYM,CREATE TRIGGER,UNLIMITED Tablespace TO %s WITH ADMIN OPTION;\" -c ;" % (db_user)
ret = subprocess.call(query)
if ret == 0:
log("[I] Granting permissions to Oracle user '" + db_user + "' for %s Done" %(self.host), "info")
@@ -652,7 +652,7 @@ def create_auditdb_user(self, xa_db_host , audit_db_host , db_name ,audit_db_nam
sys.exit(1)
else:
logFile("create user %s identified by \"%s\";" %(db_user, db_password))
- logFile("GRANT CREATE SESSION,CREATE PROCEDURE,CREATE TABLE,CREATE VIEW,CREATE SEQUENCE,CREATE PUBLIC SYNONYM,CREATE TRIGGER,UNLIMITED Tablespace TO %s WITH ADMIN OPTION;" % (db_user))
+ logFile("GRANT CREATE SESSION,CREATE PROCEDURE,CREATE TABLE,CREATE VIEW,CREATE SEQUENCE,CREATE PUBLIC SYNONYM,CREATE ANY SYNONYM,CREATE TRIGGER,UNLIMITED Tablespace TO %s WITH ADMIN OPTION;" % (db_user))
if self.verify_user(audit_db_root_user, audit_db_user, audit_db_root_password,dryMode):
if dryMode == False:
diff --git a/security-admin/scripts/setup.sh b/security-admin/scripts/setup.sh
index 12224c4d15b..b79cba47545 100755
--- a/security-admin/scripts/setup.sh
+++ b/security-admin/scripts/setup.sh
@@ -797,11 +797,11 @@ update_properties() {
if [ "${DB_FLAVOR}" == "ORACLE" ]
then
propertyName=ranger.jpa.jdbc.url
- newPropertyValue="jdbc:oracle:thin:\@//${DB_HOST}"
+ newPropertyValue="jdbc:oracle:thin:@${DB_HOST}"
updatePropertyToFilePy $propertyName $newPropertyValue $to_file_ranger
propertyName=ranger.jpa.audit.jdbc.url
- newPropertyValue="jdbc:oracle:thin:\@//${DB_HOST}"
+ newPropertyValue="jdbc:oracle:thin:@${DB_HOST}"
updatePropertyToFilePy $propertyName $newPropertyValue $to_file_ranger
propertyName=ranger.jpa.jdbc.dialect
From 5ad0820f0b853a2d4061312ba24a264f1206f1b4 Mon Sep 17 00:00:00 2001
From: sneethiraj
Date: Mon, 22 Jun 2015 18:29:39 -0700
Subject: [PATCH 012/202] RANGER-564: added incubating as part of the release
filename
---
release-build.xml | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/release-build.xml b/release-build.xml
index 5b3db7e05be..b968d859fab 100644
--- a/release-build.xml
+++ b/release-build.xml
@@ -21,7 +21,8 @@
-
+
+
From 70887df6ccdfd0903f06a11e8705e62f87199623 Mon Sep 17 00:00:00 2001
From: Madhan Neethiraj
Date: Fri, 19 Jun 2015 17:34:13 -0400
Subject: [PATCH 013/202] RANGER-561: YARN plugin updated to fallback to YARN
ACL, instead of creating Ranger policies
---
.../constants/RangerHadoopConstants.java | 5 +
.../yarn/authorizer/RangerYarnAuthorizer.java | 208 ++++++++++++------
2 files changed, 148 insertions(+), 65 deletions(-)
diff --git a/agents-common/src/main/java/org/apache/ranger/authorization/hadoop/constants/RangerHadoopConstants.java b/agents-common/src/main/java/org/apache/ranger/authorization/hadoop/constants/RangerHadoopConstants.java
index a80002763bf..ac9e93d3257 100644
--- a/agents-common/src/main/java/org/apache/ranger/authorization/hadoop/constants/RangerHadoopConstants.java
+++ b/agents-common/src/main/java/org/apache/ranger/authorization/hadoop/constants/RangerHadoopConstants.java
@@ -41,17 +41,22 @@ public class RangerHadoopConstants {
public static final String STORM_ACCESS_VERIFIER_CLASS_NAME_PROP = "storm.authorization.verifier.classname" ;
public static final String STORM_ACCESS_VERIFIER_CLASS_NAME_DEFAULT_VALUE = "org.apache.ranger.pdp.storm.RangerAuthorizer" ;
+ public static final String RANGER_ADD_YARN_PERMISSION_PROP = "ranger.add-yarn-authorization" ;
+ public static final boolean RANGER_ADD_YARN_PERMISSION_DEFAULT = true ;
+
//
// Loging constants
//
public static final String AUDITLOG_FIELD_DELIMITER_PROP = "xasecure.auditlog.fieldDelimiterString";
public static final String AUDITLOG_RANGER_MODULE_ACL_NAME_PROP = "xasecure.auditlog.xasecureAcl.name" ;
public static final String AUDITLOG_HADOOP_MODULE_ACL_NAME_PROP = "xasecure.auditlog.hadoopAcl.name" ;
+ public static final String AUDITLOG_YARN_MODULE_ACL_NAME_PROP = "ranger.auditlog.yarnAcl.name" ;
public static final String DEFAULT_LOG_FIELD_DELIMITOR = "|" ;
public static final String DEFAULT_XASECURE_MODULE_ACL_NAME = "xasecure-acl" ;
public static final String DEFAULT_RANGER_MODULE_ACL_NAME = "ranger-acl" ;
public static final String DEFAULT_HADOOP_MODULE_ACL_NAME = "hadoop-acl" ;
+ public static final String DEFAULT_YARN_MODULE_ACL_NAME = "yarn-acl" ;
public static final String AUDITLOG_FIELDINFO_VISIBLE_PROP = "xasecure.auditlog.fieldInfoVisible" ;
diff --git a/plugin-yarn/src/main/java/org/apache/ranger/authorization/yarn/authorizer/RangerYarnAuthorizer.java b/plugin-yarn/src/main/java/org/apache/ranger/authorization/yarn/authorizer/RangerYarnAuthorizer.java
index e322477ef70..ab9b7a93091 100644
--- a/plugin-yarn/src/main/java/org/apache/ranger/authorization/yarn/authorizer/RangerYarnAuthorizer.java
+++ b/plugin-yarn/src/main/java/org/apache/ranger/authorization/yarn/authorizer/RangerYarnAuthorizer.java
@@ -21,13 +21,9 @@
package org.apache.ranger.authorization.yarn.authorizer;
import java.net.InetAddress;
-import java.util.Collection;
-import java.util.HashSet;
+import java.util.HashMap;
import java.util.Map;
-import java.util.Set;
-import org.apache.commons.collections.CollectionUtils;
-import org.apache.commons.collections.MapUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
@@ -35,14 +31,16 @@
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.authorize.AccessControlList;
import org.apache.hadoop.yarn.security.*;
+import org.apache.hadoop.yarn.security.PrivilegedEntity.EntityType;
+import org.apache.ranger.audit.model.AuthzAuditEvent;
+import org.apache.ranger.authorization.hadoop.config.RangerConfiguration;
+import org.apache.ranger.authorization.hadoop.constants.RangerHadoopConstants;
import org.apache.ranger.authorization.utils.StringUtil;
import org.apache.ranger.plugin.audit.RangerDefaultAuditHandler;
import org.apache.ranger.plugin.policyengine.RangerAccessRequestImpl;
import org.apache.ranger.plugin.policyengine.RangerAccessResult;
-import org.apache.ranger.plugin.policyengine.RangerPolicyEngine;
import org.apache.ranger.plugin.policyengine.RangerAccessResourceImpl;
import org.apache.ranger.plugin.service.RangerBasePlugin;
-import org.apache.ranger.plugin.util.GrantRevokeRequest;
import com.google.common.collect.Sets;
@@ -51,11 +49,14 @@ public class RangerYarnAuthorizer extends YarnAuthorizationProvider {
public static final String ACCESS_TYPE_SUBMIT_APP = "submit-app";
public static final String ACCESS_TYPE_ADMIN = "admin";
+ private static boolean yarnAuthEnabled = RangerHadoopConstants.RANGER_ADD_YARN_PERMISSION_DEFAULT;
+
private static final Log LOG = LogFactory.getLog(RangerYarnAuthorizer.class);
private static volatile RangerYarnPlugin yarnPlugin = null;
private AccessControlList admins = null;
+ private Map> yarnAcl = new HashMap>();
@Override
public void init(Configuration conf) {
@@ -78,6 +79,8 @@ public void init(Configuration conf) {
}
}
+ RangerYarnAuthorizer.yarnAuthEnabled = RangerConfiguration.getInstance().getBoolean(RangerHadoopConstants.RANGER_ADD_YARN_PERMISSION_PROP, RangerHadoopConstants.RANGER_ADD_YARN_PERMISSION_DEFAULT);
+
if(LOG.isDebugEnabled()) {
LOG.debug("<== RangerYarnAuthorizer.init()");
}
@@ -86,23 +89,34 @@ public void init(Configuration conf) {
@Override
public boolean checkPermission(AccessType accessType, PrivilegedEntity entity, UserGroupInformation ugi) {
if(LOG.isDebugEnabled()) {
- LOG.debug("==> RangerYarnAuthorizer.checkPermission(" + accessType + ", " + entity + ", " + ugi + ")");
+ LOG.debug("==> RangerYarnAuthorizer.checkPermission(" + accessType + ", " + toString(entity) + ", " + ugi + ")");
}
- boolean ret = false;
-
- RangerYarnPlugin plugin = yarnPlugin;
+ boolean ret = false;
+ RangerYarnPlugin plugin = yarnPlugin;
+ RangerYarnAuditHandler auditHandler = null;
+ RangerAccessResult result = null;
if(plugin != null) {
RangerYarnAccessRequest request = new RangerYarnAccessRequest(entity, getRangerAccessType(accessType), accessType.name(), ugi);
- RangerAccessResult result = plugin.isAccessAllowed(request);
+ auditHandler = new RangerYarnAuditHandler();
+ result = plugin.isAccessAllowed(request, auditHandler);
+ }
+
+ if(RangerYarnAuthorizer.yarnAuthEnabled && (result == null || !result.getIsAccessDetermined())) {
+ ret = isAllowedByYarnAcl(accessType, entity, ugi, auditHandler);
+ } else {
ret = result == null ? false : result.getIsAllowed();
}
+ if(auditHandler != null) {
+ auditHandler.flushAudit();
+ }
+
if(LOG.isDebugEnabled()) {
- LOG.debug("<== RangerYarnAuthorizer.checkPermission(" + accessType + ", " + entity + ", " + ugi + "): " + ret);
+ LOG.debug("<== RangerYarnAuthorizer.checkPermission(" + accessType + ", " + toString(entity) + ", " + ugi + "): " + ret);
}
return ret;
@@ -116,6 +130,8 @@ public boolean isAdmin(UserGroupInformation ugi) {
boolean ret = false;
+ AccessControlList admins = this.admins;
+
if(admins != null) {
ret = admins.isUserAllowed(ugi);
}
@@ -143,58 +159,51 @@ public void setAdmins(AccessControlList acl, UserGroupInformation ugi) {
@Override
public void setPermission(PrivilegedEntity entity, Map permission, UserGroupInformation ugi) {
if(LOG.isDebugEnabled()) {
- LOG.debug("==> RangerYarnAuthorizer.setPermission(" + entity + ", " + permission + ", " + ugi + ")");
+ LOG.debug("==> RangerYarnAuthorizer.setPermission(" + toString(entity) + ", " + permission + ", " + ugi + ")");
}
- RangerYarnPlugin plugin = yarnPlugin;
+ yarnAcl.put(entity, permission);
- if(plugin != null && entity != null && !MapUtils.isEmpty(permission) && ugi != null) {
- RangerYarnResource resource = new RangerYarnResource(entity);
-
- GrantRevokeRequest request = new GrantRevokeRequest();
- request.setResource(resource.getAsMap());
- request.setGrantor(ugi.getShortUserName());
- request.setDelegateAdmin(Boolean.FALSE);
- request.setEnableAudit(Boolean.TRUE);
- request.setReplaceExistingPermissions(Boolean.FALSE);
- request.setIsRecursive(Boolean.TRUE);
-
- for(Map.Entry e : permission.entrySet()) {
- AccessType accessType = e.getKey();
- AccessControlList acl = e.getValue();
-
- Set accessTypes = new HashSet();
- accessTypes.add(getRangerAccessType(accessType));
- request.setAccessTypes(accessTypes);
-
- if(acl.isAllAllowed()) {
- Set publicGroup = new HashSet();
- publicGroup.add(RangerPolicyEngine.GROUP_PUBLIC);
-
- request.setUsers(null);
- request.setGroups(publicGroup);
- } else if(CollectionUtils.isEmpty(acl.getUsers()) && CollectionUtils.isEmpty(acl.getGroups())) {
- if(LOG.isDebugEnabled()) {
- LOG.debug("grantAccess(): empty users and groups - skipped");
- }
-
- continue;
- } else {
- request.setUsers(getSet(acl.getUsers()));
- request.setGroups(getSet(acl.getGroups()));
- }
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("<== RangerYarnAuthorizer.setPermission(" + toString(entity) + ", " + permission + ", " + ugi + ")");
+ }
+ }
- try {
- plugin.grantAccess(request, plugin.getResultProcessor());
- } catch(Exception excp) {
- LOG.error("grantAccess(" + request + ") failed", excp);
- }
+ public boolean isAllowedByYarnAcl(AccessType accessType, PrivilegedEntity entity, UserGroupInformation ugi, RangerYarnAuditHandler auditHandler) {
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("==> RangerYarnAuthorizer.isAllowedByYarnAcl(" + accessType + ", " + toString(entity) + ", " + ugi + ")");
+ }
+
+ boolean ret = false;
+
+ for(Map.Entry> e : yarnAcl.entrySet()) {
+ PrivilegedEntity aclEntity = e.getKey();
+ Map entityPermissions = e.getValue();
+
+ AccessControlList acl = entityPermissions == null ? null : entityPermissions.get(accessType);
+
+ if(acl == null || !acl.isUserAllowed(ugi)) {
+ continue;
}
+
+ if(! isSelfOrChildOf(entity, aclEntity)) {
+ continue;
+ }
+
+ ret = true;
+
+ break;
+ }
+
+ if(auditHandler != null) {
+ auditHandler.logYarnAclEvent(ret);
}
if(LOG.isDebugEnabled()) {
- LOG.debug("<== RangerYarnAuthorizer.setPermission(" + entity + ", " + permission + ", " + ugi + ")");
+ LOG.debug("<== RangerYarnAuthorizer.isAllowedByYarnAcl(" + accessType + ", " + toString(entity) + ", " + ugi + "): " + ret);
}
+
+ return ret;
}
private static String getRangerAccessType(AccessType accessType) {
@@ -213,22 +222,32 @@ private static String getRangerAccessType(AccessType accessType) {
return ret;
}
- private Set getSet(Collection strings) {
- Set ret = null;
+ private boolean isSelfOrChildOf(PrivilegedEntity queue, PrivilegedEntity parentQueue) {
+ boolean ret = queue.equals(parentQueue);
+
+ if(!ret && queue.getType() == EntityType.QUEUE) {
+ String queueName = queue.getName();
+ String parentQueueName = parentQueue.getName();
- if(! CollectionUtils.isEmpty(strings)) {
- if(strings instanceof Set>) {
- ret = (Set)strings;
- } else {
- ret = new HashSet();
- for(String str : strings) {
- ret.add(str);
+ if(queueName.contains(".") && !StringUtil.isEmpty(parentQueueName)) {
+ if(parentQueueName.charAt(parentQueueName.length() - 1) != '.') {
+ parentQueueName += ".";
}
+
+ ret = queueName.startsWith(parentQueueName);
}
}
return ret;
}
+
+ private String toString(PrivilegedEntity entity) {
+ if(entity != null) {
+ return "{name=" + entity.getName() + "; type=" + entity.getType() + "}";
+ }
+
+ return "null";
+ }
}
class RangerYarnPlugin extends RangerBasePlugin {
@@ -273,4 +292,63 @@ private static String getRemoteIp() {
}
return ret ;
}
+}
+
+class RangerYarnAuditHandler extends RangerDefaultAuditHandler {
+ private static final Log LOG = LogFactory.getLog(RangerYarnAuditHandler.class);
+
+ private static final String YarnModuleName = RangerConfiguration.getInstance().get(RangerHadoopConstants.AUDITLOG_YARN_MODULE_ACL_NAME_PROP , RangerHadoopConstants.DEFAULT_YARN_MODULE_ACL_NAME) ;
+
+ private boolean isAuditEnabled = false;
+ private AuthzAuditEvent auditEvent = null;
+
+ public RangerYarnAuditHandler() {
+ }
+
+ @Override
+ public void processResult(RangerAccessResult result) {
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("==> RangerYarnAuditHandler.logAudit(" + result + ")");
+ }
+
+ if(! isAuditEnabled && result.getIsAudited()) {
+ isAuditEnabled = true;
+ }
+
+ auditEvent = super.getAuthzEvents(result);
+
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("<== RangerYarnAuditHandler.logAudit(" + result + "): " + auditEvent);
+ }
+ }
+
+ public void logYarnAclEvent(boolean accessGranted) {
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("==> RangerYarnAuditHandler.logYarnAclEvent(" + accessGranted + ")");
+ }
+
+ if(auditEvent != null) {
+ auditEvent.setAccessResult((short) (accessGranted ? 1 : 0));
+ auditEvent.setAclEnforcer(YarnModuleName);
+ auditEvent.setPolicyId(-1);
+ }
+
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("<== RangerYarnAuditHandler.logYarnAclEvent(" + accessGranted + "): " + auditEvent);
+ }
+ }
+
+ public void flushAudit() {
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("==> RangerYarnAuditHandler.flushAudit(" + isAuditEnabled + ", " + auditEvent + ")");
+ }
+
+ if(isAuditEnabled) {
+ super.logAuthzAudit(auditEvent);
+ }
+
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("<== RangerYarnAuditHandler.flushAudit(" + isAuditEnabled + ", " + auditEvent + ")");
+ }
+ }
}
\ No newline at end of file
From cc690cd7a9fd1ec8b4e8bb6013c97fd4ff31d999 Mon Sep 17 00:00:00 2001
From: Madhan Neethiraj
Date: Thu, 25 Jun 2015 02:08:14 -0700
Subject: [PATCH 014/202] RANGER-568: fixed RangerTimeOfDayMatcher condition to
handle 12am/12pm correctly
---
.../RangerTimeOfDayMatcher.java | 14 ++++-
.../RangerTimeOfDayMatcherTest.java | 55 ++++++++++++++++++-
2 files changed, 66 insertions(+), 3 deletions(-)
diff --git a/agents-common/src/main/java/org/apache/ranger/plugin/conditionevaluator/RangerTimeOfDayMatcher.java b/agents-common/src/main/java/org/apache/ranger/plugin/conditionevaluator/RangerTimeOfDayMatcher.java
index 3ddb250e3a8..f65f29ebcbe 100644
--- a/agents-common/src/main/java/org/apache/ranger/plugin/conditionevaluator/RangerTimeOfDayMatcher.java
+++ b/agents-common/src/main/java/org/apache/ranger/plugin/conditionevaluator/RangerTimeOfDayMatcher.java
@@ -105,12 +105,22 @@ int[] extractDuration(String value) {
endMinute = Integer.parseInt(m.group(7));
}
String endType = m.group(8).toUpperCase();
- if (startType.equals("P")) {
+ if(startHour == 12) {
+ if(startType.equals("A")) {
+ startHour = 0;
+ }
+ } else if (startType.equals("P")) {
startHour += 12;
}
- if (endType.equals("P")) {
+
+ if(endHour == 12) {
+ if(endType.equals("A")) {
+ endHour = 0;
+ }
+ } else if (endType.equals("P")) {
endHour += 12;
}
+
result = new int[] { (startHour*60)+startMin, (endHour*60)+endMinute };
}
}
diff --git a/agents-common/src/test/java/org/apache/ranger/plugin/conditionevaluator/RangerTimeOfDayMatcherTest.java b/agents-common/src/test/java/org/apache/ranger/plugin/conditionevaluator/RangerTimeOfDayMatcherTest.java
index e894d985472..7e8ef0ad4be 100644
--- a/agents-common/src/test/java/org/apache/ranger/plugin/conditionevaluator/RangerTimeOfDayMatcherTest.java
+++ b/agents-common/src/test/java/org/apache/ranger/plugin/conditionevaluator/RangerTimeOfDayMatcherTest.java
@@ -51,7 +51,8 @@ public void test_patterMatching_happyPath() {
String[] durations = new String[] {
"9am-5pm", " 9Am -5 Pm", " 9Am -5 Pm", "9 AM -5 p.m.", "9a.M - 5Pm.",
"9:30am-5:30pm", " 9:00Am -5:59 Pm",
- " 9 am - 4 pm ", "9pm-5AM"
+ " 9 am - 4 pm ", "9pm-5AM",
+ "11am-12pm", "11pm-12am", "12am-12pm", "12pm-12am"
};
check(durations, true);
}
@@ -101,6 +102,10 @@ public void test_patterMatching_happyPath_groups() {
{ "9:30AM - 5:15pm", "9", "30", "A", "5", "15", "p" },
{ "9:30 AM - 5:15 p.m.", "9", "30", "A", "5", "15", "p" },
{ "9pm-5am", "9", null, "p", "5", null, "a"},
+ { "11am-12pm", "11", null, "a", "12", null, "p" },
+ { "11pm-12am", "11", null, "p", "12", null, "a" },
+ { "12am-12pm", "12", null, "a", "12", null, "p" },
+ { "12pm-12am", "12", null, "p", "12", null, "a" },
};
checkGroups(input);
}
@@ -126,6 +131,10 @@ public void test_ExtractDuration_happyPath() {
{ "9am-5pm", true, 9*60, (12+5)*60 },
{ "1 PM - 10P.M.", true, (12+1)*60, (12+10)*60 },
{ "1PM - 9AM", true, (12+1)*60, 9*60 },
+ { "11am-12pm", true, 11*60, 12*60 },
+ { "11pm-12am", true, (12+11)*60, 0*60 },
+ { "12am-12pm", true, 0*60, 12*60 },
+ { "12pm-12am", true, 12*60, 0*60 },
{ "1PM", false, null, null }, // illegal patterns should come back as null, too
};
for (Object[] data: input) {
@@ -217,4 +226,48 @@ public void test_end2end_happyPath() {
}
}
}
+
+ @Test
+ public void test_end2end_happyPath_12_oClock() {
+ RangerPolicyItemCondition itemCondition = mock(RangerPolicyItemCondition.class);
+ when(itemCondition.getValues()).thenReturn(Arrays.asList("12am-1am", "11am-12pm", "12pm-1pm", "11pm-12am"));
+
+ RangerTimeOfDayMatcher matcher = new RangerTimeOfDayMatcher();
+ matcher.setConditionDef(null);
+ matcher.setPolicyItemCondition(itemCondition);
+ matcher.init();
+
+ Object[][] input = new Object[][] {
+ { 0, 00, true },
+ { 0, 01, true },
+ { 1, 00, true },
+ { 1, 01, false },
+ { 10, 59, false },
+ { 11, 00, true },
+ { 11, 59, true },
+ { 12, 00, true },
+ { 12, 01, true },
+ { 12, 59, true },
+ { 13, 00, true },
+ { 13, 01, false },
+ {22, 59, false },
+ {23, 0, true },
+ {23, 59, true },
+ };
+
+ RangerAccessRequest request = mock(RangerAccessRequest.class);
+ for (Object[] data : input) {
+ int hour = (int)data[0];
+ int minute = (int)data[1];
+ Calendar c = new GregorianCalendar(2015, Calendar.APRIL, 1, hour, minute);
+ Date aDate = c.getTime();
+ when(request.getAccessTime()).thenReturn(aDate);
+ boolean matchExpected = (boolean)data[2];
+ if (matchExpected) {
+ assertTrue("" + hour, matcher.isMatched(request));
+ } else {
+ assertFalse("" + hour, matcher.isMatched(request));
+ }
+ }
+ }
}
From babc79c28cbf10cea1b6e8ca08f38a484ad7b278 Mon Sep 17 00:00:00 2001
From: Alok Lal
Date: Thu, 25 Jun 2015 15:04:14 -0700
Subject: [PATCH 015/202] RANGER-570 Knox plugin: added shell classes with old
class names so that knox plugin will work after ranger upgrade from 0.4 to
0.5
Signed-off-by: sneethiraj
---
.../knox/filter/XASecurePDPKnoxFilter.java | 25 +++++++++++++++++++
1 file changed, 25 insertions(+)
create mode 100644 knox-agent/src/main/java/com/xasecure/pdp/knox/filter/XASecurePDPKnoxFilter.java
diff --git a/knox-agent/src/main/java/com/xasecure/pdp/knox/filter/XASecurePDPKnoxFilter.java b/knox-agent/src/main/java/com/xasecure/pdp/knox/filter/XASecurePDPKnoxFilter.java
new file mode 100644
index 00000000000..6b9d6fd1ec1
--- /dev/null
+++ b/knox-agent/src/main/java/com/xasecure/pdp/knox/filter/XASecurePDPKnoxFilter.java
@@ -0,0 +1,25 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package com.xasecure.pdp.knox.filter;
+
+import org.apache.ranger.authorization.knox.RangerPDPKnoxFilter;
+
+public class XASecurePDPKnoxFilter extends RangerPDPKnoxFilter {
+}
From 6af6fe3546be1d6b7dc36e647dcc38f3919fe4d0 Mon Sep 17 00:00:00 2001
From: Velmurugan Periasamy
Date: Thu, 25 Jun 2015 19:05:44 -0400
Subject: [PATCH 016/202] RANGER-569: Do not modify hbase.rpc.protection when
ranger hbase plugin is enabled
Signed-off-by: sneethiraj
---
hbase-agent/conf/hbase-site-changes.cfg | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/hbase-agent/conf/hbase-site-changes.cfg b/hbase-agent/conf/hbase-site-changes.cfg
index e47f80d5959..8c8992acc9f 100644
--- a/hbase-agent/conf/hbase-site-changes.cfg
+++ b/hbase-agent/conf/hbase-site-changes.cfg
@@ -14,9 +14,9 @@
# limitations under the License.
#hbase.security.authentication kerberos mod create-if-not-exists
hbase.security.authorization true mod create-if-not-exists
+hbase.coprocessor.master.classes com.xasecure.authorization.hbase.XaSecureAuthorizationCoprocessor delval - ,
+hbase.coprocessor.region.classes com.xasecure.authorization.hbase.XaSecureAuthorizationCoprocessor delval - ,
hbase.coprocessor.master.classes org.apache.hadoop.hbase.security.access.AccessController delval - ,
hbase.coprocessor.region.classes org.apache.hadoop.hbase.security.access.AccessController delval - ,
hbase.coprocessor.master.classes org.apache.ranger.authorization.hbase.RangerAuthorizationCoprocessor append create-if-not-exists ,
hbase.coprocessor.region.classes org.apache.ranger.authorization.hbase.RangerAuthorizationCoprocessor append create-if-not-exists ,
-hbase.rpc.protection privacy mod create-if-not-exists
-hbase.rpc.engine org.apache.hadoop.hbase.ipc.SecureRpcEngine mod create-if-not-exists
From 1dbb9b05f08485ef93e5a3a5b316bdef1b9c33f8 Mon Sep 17 00:00:00 2001
From: Madhan Neethiraj
Date: Sat, 20 Jun 2015 23:18:38 -0400
Subject: [PATCH 017/202] RANGER-563: permissions are duplicated in some
policyItems after upgrade
Signed-off-by: sneethiraj
---
.../ranger/patch/PatchMigration_J10002.java | 22 ++++++++++++++++---
1 file changed, 19 insertions(+), 3 deletions(-)
diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchMigration_J10002.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchMigration_J10002.java
index 44306d83c97..621159d3197 100644
--- a/security-admin/src/main/java/org/apache/ranger/patch/PatchMigration_J10002.java
+++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchMigration_J10002.java
@@ -471,10 +471,10 @@ private List getPolicyItemListForRes(XXResource xRes, XXServic
if(StringUtils.equalsIgnoreCase(accessType, "Admin")) {
policyItem.setDelegateAdmin(Boolean.TRUE);
if ( svcDef.getId() == EmbeddedServiceDefsUtil.instance().getHBaseServiceDefId()) {
- accessList.add(new RangerPolicyItemAccess(accessType));
+ addAccessType(accessType, accessList);
}
} else {
- accessList.add(new RangerPolicyItemAccess(accessType));
+ addAccessType(accessType, accessList);
}
ipAddress = permMap.getIpAddress();
@@ -509,7 +509,23 @@ private List getPolicyItemListForRes(XXResource xRes, XXServic
return policyItems;
}
-
+
+ private void addAccessType(String accessType, List accessList) {
+ boolean alreadyExists = false;
+
+ for(RangerPolicyItemAccess access : accessList) {
+ if(StringUtils.equalsIgnoreCase(accessType, access.getType())) {
+ alreadyExists = true;
+
+ break;
+ }
+ }
+
+ if(!alreadyExists) {
+ accessList.add(new RangerPolicyItemAccess(accessType));
+ }
+ }
+
private void updateSequences() {
daoMgr.getXXServiceDef().updateSequence();
daoMgr.getXXService().updateSequence();
From 3c509cd45c8883855f528e61344a85b6b6620c84 Mon Sep 17 00:00:00 2001
From: Alok Lal
Date: Thu, 25 Jun 2015 19:17:51 -0700
Subject: [PATCH 018/202] RANGER-571 Storm plugin: added shell classes with old
class names so that it will work after ranger upgrade from 0.4 to 0.5
Signed-off-by: sneethiraj
---
.../authorizer/XaSecureStormAuthorizer.java | 32 +++++++++++++++++++
1 file changed, 32 insertions(+)
create mode 100644 storm-agent/src/main/java/com/xasecure/authorization/storm/authorizer/XaSecureStormAuthorizer.java
diff --git a/storm-agent/src/main/java/com/xasecure/authorization/storm/authorizer/XaSecureStormAuthorizer.java b/storm-agent/src/main/java/com/xasecure/authorization/storm/authorizer/XaSecureStormAuthorizer.java
new file mode 100644
index 00000000000..723dd79bce5
--- /dev/null
+++ b/storm-agent/src/main/java/com/xasecure/authorization/storm/authorizer/XaSecureStormAuthorizer.java
@@ -0,0 +1,32 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package com.xasecure.authorization.storm.authorizer;
+
+import org.apache.ranger.authorization.storm.authorizer.RangerStormAuthorizer;
+
+/**
+ * This class exists only to provide for seamless upgrade/downgrade capabilities. Class name is in storm conf which must allow for seamles upgrade and downgrade.
+ * Thus when class names were changed XaSecure* -> Ranger* this shell class serves to allow for seamles upgrade as well as downgrade.
+ *
+ * This class is final because if one needs to customize coprocessor it is expected that RangerStormAuthorizer would be modified/extended as that is
+ * the "real" authorizer! This class, hence, should NEVER be more than an EMPTY shell!
+ */
+final public class XaSecureStormAuthorizer extends RangerStormAuthorizer {
+}
From de946a3f01cf22d37110e25faff03b4ce9aa4b55 Mon Sep 17 00:00:00 2001
From: Don Bosco Durai
Date: Fri, 12 Jun 2015 16:40:45 -0700
Subject: [PATCH 019/202] RANGER-552 Ranger KMS not able to audit to kerberos
HDFS
---
.../destination/HDFSAuditDestination.java | 2 +-
.../ranger/audit/provider/MiscUtil.java | 183 ++++++++++++++++--
.../authorizer/RangerKafkaAuthorizer.java | 41 +---
.../kms/authorizer/RangerKmsAuthorizer.java | 44 ++++-
4 files changed, 225 insertions(+), 45 deletions(-)
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/destination/HDFSAuditDestination.java b/agents-audit/src/main/java/org/apache/ranger/audit/destination/HDFSAuditDestination.java
index 4fc3a0b2209..49e5fbbd2c8 100644
--- a/agents-audit/src/main/java/org/apache/ranger/audit/destination/HDFSAuditDestination.java
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/destination/HDFSAuditDestination.java
@@ -216,7 +216,7 @@ synchronized private PrintWriter getLogFileStream() throws Throwable {
FileSystem fileSystem = FileSystem.get(uri, conf);
Path hdfPath = new Path(fullPath);
- logger.info("Checking whether log file exists. hdfPath=" + fullPath);
+ logger.info("Checking whether log file exists. hdfPath=" + fullPath + ", UGI=" + MiscUtil.getUGILoginUser());
int i = 0;
while (fileSystem.exists(hdfPath)) {
i++;
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/provider/MiscUtil.java b/agents-audit/src/main/java/org/apache/ranger/audit/provider/MiscUtil.java
index 6eee55c2378..bfded938971 100644
--- a/agents-audit/src/main/java/org/apache/ranger/audit/provider/MiscUtil.java
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/provider/MiscUtil.java
@@ -20,6 +20,7 @@
import java.io.IOException;
import java.net.InetAddress;
import java.rmi.dgc.VMID;
+import java.security.Principal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
@@ -30,18 +31,27 @@
import java.util.Set;
import java.util.StringTokenizer;
import java.util.UUID;
+import java.util.regex.Pattern;
import javax.security.auth.Subject;
+import javax.security.auth.login.AppConfigurationEntry;
+import javax.security.auth.login.Configuration;
+import javax.security.auth.login.LoginContext;
+import javax.security.auth.login.LoginException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.security.UserGroupInformation;
+import org.apache.hadoop.security.authentication.util.KerberosName;
+import org.apache.hadoop.security.authentication.util.KerberosUtil;
import org.apache.log4j.helpers.LogLog;
import org.apache.ranger.authorization.hadoop.utils.RangerCredentialProvider;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
+import static org.apache.hadoop.util.PlatformName.IBM_JAVA;
+
public class MiscUtil {
private static final Log logger = LogFactory.getLog(MiscUtil.class);
@@ -64,7 +74,7 @@ public class MiscUtil {
private static UserGroupInformation ugiLoginUser = null;
private static Subject subjectLoginUser = null;
- private static Map logHistoryList = new Hashtable();
+ private static Map logHistoryList = new Hashtable();
private static int logInterval = 30000; // 30 seconds
static {
@@ -410,19 +420,51 @@ public static String getCredentialString(String url, String alias) {
return ret;
}
+ public static UserGroupInformation createUGIFromSubject(Subject subject)
+ throws IOException {
+ logger.info("SUBJECT " + (subject == null ? "not found" : "found"));
+ UserGroupInformation ugi = null;
+ if (subject != null) {
+ logger.info("SUBJECT.PRINCIPALS.size()="
+ + subject.getPrincipals().size());
+ java.util.Set principals = subject.getPrincipals();
+ for (Principal principal : principals) {
+ logger.info("SUBJECT.PRINCIPAL.NAME=" + principal.getName());
+ }
+ try {
+ // Do not remove the below statement. The default
+ // getLoginUser does some initialization which is needed
+ // for getUGIFromSubject() to work.
+ logger.info("Default UGI before using Subject from Kafka:"
+ + UserGroupInformation.getLoginUser());
+ } catch (Throwable t) {
+ logger.error(t);
+ }
+ ugi = UserGroupInformation.getUGIFromSubject(subject);
+ logger.info("SUBJECT.UGI.NAME=" + ugi.getUserName() + ", ugi="
+ + ugi);
+ } else {
+ logger.info("Server username is not available");
+ }
+ return ugi;
+ }
+
/**
* @param ugiLoginUser
*/
- public static void setUGILoginUser(UserGroupInformation newUGI, Subject newSubject) {
+ public static void setUGILoginUser(UserGroupInformation newUGI,
+ Subject newSubject) {
if (newUGI != null) {
UserGroupInformation.setLoginUser(newUGI);
ugiLoginUser = newUGI;
- logger.info("Setting UGI=" + newUGI );
+ logger.info("Setting UGI=" + newUGI);
} else {
logger.error("UGI is null. Not setting it.");
}
- logger.info("Setting SUBJECT");
- subjectLoginUser = newSubject;
+ if (newSubject != null) {
+ logger.info("Setting SUBJECT");
+ subjectLoginUser = newSubject;
+ }
}
public static UserGroupInformation getUGILoginUser() {
@@ -436,7 +478,6 @@ public static UserGroupInformation getUGILoginUser() {
return ugiLoginUser;
}
-
public static Subject getSubjectLoginUser() {
return subjectLoginUser;
}
@@ -462,13 +503,14 @@ static public Set getGroupsForRequestUser(String userName) {
return groupsSet;
}
} catch (Throwable e) {
- logErrorMessageByInterval(
- logger, "Error getting groups for users. userName=" + userName, e);
+ logErrorMessageByInterval(logger,
+ "Error getting groups for users. userName=" + userName, e);
}
return null;
}
- static public boolean logErrorMessageByInterval(Log useLogger, String message) {
+ static public boolean logErrorMessageByInterval(Log useLogger,
+ String message) {
return logErrorMessageByInterval(useLogger, message, null);
}
@@ -476,7 +518,8 @@ static public boolean logErrorMessageByInterval(Log useLogger, String message) {
* @param string
* @param e
*/
- static public boolean logErrorMessageByInterval(Log useLogger, String message, Throwable e) {
+ static public boolean logErrorMessageByInterval(Log useLogger,
+ String message, Throwable e) {
LogHistory log = logHistoryList.get(message);
if (log == null) {
log = new LogHistory();
@@ -494,7 +537,7 @@ static public boolean logErrorMessageByInterval(Log useLogger, String message, T
} else {
useLogger.error(message, e);
}
-
+
return true;
} else {
log.counter++;
@@ -503,9 +546,127 @@ static public boolean logErrorMessageByInterval(Log useLogger, String message, T
}
+ public static void authWithKerberos(String keytab, String principal,
+ String nameRules) {
+
+ if (keytab == null) {
+ return;
+ }
+ Subject serverSubject = new Subject();
+ int successLoginCount = 0;
+ String[] spnegoPrincipals = null;
+ try {
+ if (principal.equals("*")) {
+ spnegoPrincipals = KerberosUtil.getPrincipalNames(keytab,
+ Pattern.compile("HTTP/.*"));
+ if (spnegoPrincipals.length == 0) {
+ logger.error("No principals found in keytab=" + keytab);
+ }
+ } else {
+ spnegoPrincipals = new String[] { principal };
+ }
+
+ if (nameRules != null) {
+ KerberosName.setRules(nameRules);
+ }
+
+ List loginContexts = new ArrayList();
+ for (String spnegoPrincipal : spnegoPrincipals) {
+ try {
+ logger.info("Login using keytab " + keytab
+ + ", for principal " + spnegoPrincipal);
+ final KerberosConfiguration kerberosConfiguration = new KerberosConfiguration(
+ keytab, spnegoPrincipal);
+ final LoginContext loginContext = new LoginContext("",
+ serverSubject, null, kerberosConfiguration);
+ loginContext.login();
+ successLoginCount++;
+ logger.info("Login success keytab " + keytab
+ + ", for principal " + spnegoPrincipal);
+ loginContexts.add(loginContext);
+ } catch (Throwable t) {
+ logger.error("Login failed keytab " + keytab
+ + ", for principal " + spnegoPrincipal, t);
+ }
+ }
+ } catch (Throwable t) {
+ logger.error("Failed to login as [" + spnegoPrincipals + "]", t);
+ }
+
+ if (successLoginCount > 0) {
+ logger.info("Total login success count=" + successLoginCount);
+ try {
+ UserGroupInformation ugi = createUGIFromSubject(serverSubject);
+ if (ugi != null) {
+ setUGILoginUser(ugi, serverSubject);
+ }
+ } catch (Throwable e) {
+ logger.error("Error creating UGI from subject. subject="
+ + serverSubject);
+ }
+ } else {
+ logger.error("Total logins were successfull from keytab=" + keytab
+ + ", principal=" + principal);
+ }
+ }
+
static class LogHistory {
long lastLogTime = 0;
int counter = 0;
}
+ /**
+ * Kerberos context configuration for the JDK GSS library.
+ */
+ private static class KerberosConfiguration extends Configuration {
+ private String keytab;
+ private String principal;
+
+ public KerberosConfiguration(String keytab, String principal) {
+ this.keytab = keytab;
+ this.principal = principal;
+ }
+
+ @Override
+ public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
+ Map options = new HashMap();
+ if (IBM_JAVA) {
+ options.put("useKeytab", keytab.startsWith("file://") ? keytab
+ : "file://" + keytab);
+ options.put("principal", principal);
+ options.put("credsType", "acceptor");
+ } else {
+ options.put("keyTab", keytab);
+ options.put("principal", principal);
+ options.put("useKeyTab", "true");
+ options.put("storeKey", "true");
+ options.put("doNotPrompt", "true");
+ options.put("useTicketCache", "true");
+ options.put("renewTGT", "true");
+ options.put("isInitiator", "false");
+ }
+ options.put("refreshKrb5Config", "true");
+ String ticketCache = System.getenv("KRB5CCNAME");
+ if (ticketCache != null) {
+ if (IBM_JAVA) {
+ options.put("useDefaultCcache", "true");
+ // The first value searched when "useDefaultCcache" is used.
+ System.setProperty("KRB5CCNAME", ticketCache);
+ options.put("renewTGT", "true");
+ options.put("credsType", "both");
+ } else {
+ options.put("ticketCache", ticketCache);
+ }
+ }
+ if (logger.isDebugEnabled()) {
+ options.put("debug", "true");
+ }
+
+ return new AppConfigurationEntry[] { new AppConfigurationEntry(
+ KerberosUtil.getKrb5LoginModuleName(),
+ AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
+ options), };
+ }
+ }
+
}
diff --git a/plugin-kafka/src/main/java/org/apache/ranger/authorization/kafka/authorizer/RangerKafkaAuthorizer.java b/plugin-kafka/src/main/java/org/apache/ranger/authorization/kafka/authorizer/RangerKafkaAuthorizer.java
index 3341f84503a..dbb2723709b 100644
--- a/plugin-kafka/src/main/java/org/apache/ranger/authorization/kafka/authorizer/RangerKafkaAuthorizer.java
+++ b/plugin-kafka/src/main/java/org/apache/ranger/authorization/kafka/authorizer/RangerKafkaAuthorizer.java
@@ -19,6 +19,7 @@
package org.apache.ranger.authorization.kafka.authorizer;
+import java.io.IOException;
import java.security.Principal;
import java.util.Date;
@@ -81,43 +82,19 @@ public RangerKafkaAuthorizer() {
public void initialize(KafkaConfig kafkaConfig) {
if (rangerPlugin == null) {
- rangerPlugin = new RangerBasePlugin("kafka", "kafka");
-
try {
Subject subject = LoginManager.subject();
- logger.info("SUBJECT "
- + (subject == null ? "not found" : "found"));
- if (subject != null) {
- logger.info("SUBJECT.PRINCIPALS.size()="
- + subject.getPrincipals().size());
- java.util.Set principals = subject
- .getPrincipals();
- for (Principal principal : principals) {
- logger.info("SUBJECT.PRINCIPAL.NAME="
- + principal.getName());
- }
- try {
- // Do not remove the below statement. The default
- // getLoginUser does some initialization which is needed
- // for getUGIFromSubject() to work.
- logger.info("Default UGI before using Subject from Kafka:"
- + UserGroupInformation.getLoginUser());
- } catch (Throwable t) {
- logger.error(t);
- }
- UserGroupInformation ugi = UserGroupInformation
- .getUGIFromSubject(subject);
- logger.info("SUBJECT.UGI.NAME=" + ugi.getUserName()
- + ", ugi=" + ugi);
+ UserGroupInformation ugi = MiscUtil
+ .createUGIFromSubject(subject);
+ if (ugi != null) {
MiscUtil.setUGILoginUser(ugi, subject);
- } else {
- logger.info("Server username is not available");
}
logger.info("LoginUser=" + MiscUtil.getUGILoginUser());
} catch (Throwable t) {
logger.error("Error getting principal.", t);
}
+ rangerPlugin = new RangerBasePlugin("kafka", "kafka");
logger.info("Calling plugin.init()");
rangerPlugin.init();
@@ -135,12 +112,12 @@ public boolean authorize(Session session, Operation operation,
"Authorizer is still not initialized");
return false;
}
-
- //TODO: If resource type if consumer group, then allow it by default
- if(resource.resourceType().equals(ResourceType.CONSUMER_GROUP)) {
+
+ // TODO: If resource type if consumer group, then allow it by default
+ if (resource.resourceType().equals(ResourceType.CONSUMER_GROUP)) {
return true;
}
-
+
String userName = null;
if (session.principal() != null) {
userName = session.principal().getName();
diff --git a/plugin-kms/src/main/java/org/apache/ranger/authorization/kms/authorizer/RangerKmsAuthorizer.java b/plugin-kms/src/main/java/org/apache/ranger/authorization/kms/authorizer/RangerKmsAuthorizer.java
index 3407a1d4749..04b8b916251 100755
--- a/plugin-kms/src/main/java/org/apache/ranger/authorization/kms/authorizer/RangerKmsAuthorizer.java
+++ b/plugin-kms/src/main/java/org/apache/ranger/authorization/kms/authorizer/RangerKmsAuthorizer.java
@@ -26,6 +26,7 @@
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
+import java.util.regex.Pattern;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.crypto.key.kms.server.KMSACLsType;
@@ -40,6 +41,7 @@
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.authorize.AccessControlList;
import org.apache.hadoop.security.authorize.AuthorizationException;
+import org.apache.ranger.audit.provider.MiscUtil;
import org.apache.ranger.authorization.utils.StringUtil;
import org.apache.ranger.plugin.audit.RangerDefaultAuditHandler;
import org.apache.ranger.plugin.policyengine.RangerAccessRequestImpl;
@@ -81,15 +83,52 @@ public class RangerKmsAuthorizer implements Runnable, KeyACLs {
private static volatile RangerKMSPlugin kmsPlugin = null;
+ /**
+ * Constant that identifies the authentication mechanism.
+ */
+ public static final String TYPE = "kerberos";
+
+ /**
+ * Constant for the configuration property that indicates the kerberos principal.
+ */
+ public static final String PRINCIPAL = TYPE + ".principal";
+
+ /**
+ * Constant for the configuration property that indicates the keytab file path.
+ */
+ public static final String KEYTAB = TYPE + ".keytab";
+
+ /**
+ * Constant for the configuration property that indicates the Kerberos name
+ * rules for the Kerberos principals.
+ */
+ public static final String NAME_RULES = TYPE + ".name.rules";
+
RangerKmsAuthorizer(Configuration conf) {
+ LOG.info("RangerKmsAuthorizer(conf)...");
+ authWithKerberos();
if (conf == null) {
conf = loadACLs();
}
setKMSACLs(conf);
init(conf);
+
}
- public RangerKmsAuthorizer() {
+ /**
+ *
+ */
+ private void authWithKerberos() {
+ //Let's if we can create the login user UGI
+ Configuration kconf = new Configuration();
+ kconf.addResource("kms-site.xml");
+ String keytab = kconf.get("hadoop.kms.authentication.kerberos.keytab");
+ String principal = kconf.get("hadoop.kms.authentication.kerberos.principal");
+ String nameRules = kconf.get(NAME_RULES);
+ MiscUtil.authWithKerberos(keytab, principal, nameRules);
+ }
+
+ public RangerKmsAuthorizer() {
this(null);
}
@@ -241,6 +280,7 @@ public void init(Configuration conf) {
plugin.init();
kmsPlugin = plugin;
+
}
}
}
@@ -306,6 +346,8 @@ private static String getRangerAccessType(KMSACLsType.Type accessType) {
}
}
+
+
class RangerKMSPlugin extends RangerBasePlugin {
public RangerKMSPlugin() {
super("kms", "kms");
From 34f7e3b078c80bad84791d543ae159acd2aa7fc1 Mon Sep 17 00:00:00 2001
From: Don Bosco Durai
Date: Fri, 12 Jun 2015 18:56:51 -0700
Subject: [PATCH 020/202] RANGER-552 Need to get UGI from keytab, instead of
subject
---
.../audit/provider/BaseAuditHandler.java | 19 +++-
.../ranger/audit/provider/MiscUtil.java | 87 +++++++++++--------
.../apache/ranger/audit/queue/AuditQueue.java | 12 +++
3 files changed, 79 insertions(+), 39 deletions(-)
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/provider/BaseAuditHandler.java b/agents-audit/src/main/java/org/apache/ranger/audit/provider/BaseAuditHandler.java
index 3859a7e89e4..30db18bc253 100644
--- a/agents-audit/src/main/java/org/apache/ranger/audit/provider/BaseAuditHandler.java
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/provider/BaseAuditHandler.java
@@ -169,6 +169,10 @@ public void setParentPath(String parentPath) {
this.parentPath = parentPath;
}
+ public String getFinalPath() {
+ return getName();
+ }
+
public void setName(String name) {
providerName = name;
}
@@ -249,22 +253,31 @@ public void logStatus() {
lastStatusLogTime = currTime;
long diffCount = totalCount - lastIntervalCount;
- if (diffCount == 0) {
- return;
- }
long diffSuccess = totalSuccessCount - lastIntervalSuccessCount;
long diffFailed = totalFailedCount - lastIntervalFailedCount;
long diffStashed = totalStashedCount - lastStashedCount;
long diffDeferred = totalDeferredCount - lastDeferredCount;
+ if (diffCount == 0 && diffSuccess == 0 && diffFailed == 0
+ && diffStashed == 0 && diffDeferred == 0) {
+ return;
+ }
+
lastIntervalCount = totalCount;
lastIntervalSuccessCount = totalSuccessCount;
lastIntervalFailedCount = totalFailedCount;
lastStashedCount = totalStashedCount;
lastDeferredCount = totalDeferredCount;
+ String finalPath = "";
+ String tFinalPath = getFinalPath();
+ if (!getName().equals(tFinalPath)) {
+ finalPath = ", finalDestination=" + tFinalPath;
+ }
+
String msg = "Audit Status Log: name="
+ getName()
+ + finalPath
+ ", interval="
+ formatIntervalForLog(diffTime)
+ ", events="
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/provider/MiscUtil.java b/agents-audit/src/main/java/org/apache/ranger/audit/provider/MiscUtil.java
index bfded938971..a3a3a844ecf 100644
--- a/agents-audit/src/main/java/org/apache/ranger/audit/provider/MiscUtil.java
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/provider/MiscUtil.java
@@ -37,8 +37,6 @@
import javax.security.auth.login.AppConfigurationEntry;
import javax.security.auth.login.Configuration;
import javax.security.auth.login.LoginContext;
-import javax.security.auth.login.LoginException;
-
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.security.UserGroupInformation;
@@ -435,7 +433,8 @@ public static UserGroupInformation createUGIFromSubject(Subject subject)
// Do not remove the below statement. The default
// getLoginUser does some initialization which is needed
// for getUGIFromSubject() to work.
- logger.info("Default UGI before using Subject from Kafka:"
+ UserGroupInformation.getLoginUser();
+ logger.info("Default UGI before using new Subject:"
+ UserGroupInformation.getLoginUser());
} catch (Throwable t) {
logger.error(t);
@@ -549,7 +548,7 @@ static public boolean logErrorMessageByInterval(Log useLogger,
public static void authWithKerberos(String keytab, String principal,
String nameRules) {
- if (keytab == null) {
+ if (keytab == null || principal == null) {
return;
}
Subject serverSubject = new Subject();
@@ -570,44 +569,60 @@ public static void authWithKerberos(String keytab, String principal,
KerberosName.setRules(nameRules);
}
- List loginContexts = new ArrayList();
- for (String spnegoPrincipal : spnegoPrincipals) {
- try {
- logger.info("Login using keytab " + keytab
- + ", for principal " + spnegoPrincipal);
- final KerberosConfiguration kerberosConfiguration = new KerberosConfiguration(
- keytab, spnegoPrincipal);
- final LoginContext loginContext = new LoginContext("",
- serverSubject, null, kerberosConfiguration);
- loginContext.login();
- successLoginCount++;
- logger.info("Login success keytab " + keytab
- + ", for principal " + spnegoPrincipal);
- loginContexts.add(loginContext);
- } catch (Throwable t) {
- logger.error("Login failed keytab " + keytab
- + ", for principal " + spnegoPrincipal, t);
+ boolean useKeytab = true;
+ if (!useKeytab) {
+ logger.info("Creating UGI with subject");
+ List loginContexts = new ArrayList();
+ for (String spnegoPrincipal : spnegoPrincipals) {
+ try {
+ logger.info("Login using keytab " + keytab
+ + ", for principal " + spnegoPrincipal);
+ final KerberosConfiguration kerberosConfiguration = new KerberosConfiguration(
+ keytab, spnegoPrincipal);
+ final LoginContext loginContext = new LoginContext("",
+ serverSubject, null, kerberosConfiguration);
+ loginContext.login();
+ successLoginCount++;
+ logger.info("Login success keytab " + keytab
+ + ", for principal " + spnegoPrincipal);
+ loginContexts.add(loginContext);
+ } catch (Throwable t) {
+ logger.error("Login failed keytab " + keytab
+ + ", for principal " + spnegoPrincipal, t);
+ }
+ if (successLoginCount > 0) {
+ logger.info("Total login success count="
+ + successLoginCount);
+ try {
+ UserGroupInformation
+ .loginUserFromSubject(serverSubject);
+ // UserGroupInformation ugi =
+ // createUGIFromSubject(serverSubject);
+ // if (ugi != null) {
+ // setUGILoginUser(ugi, serverSubject);
+ // }
+ } catch (Throwable e) {
+ logger.error("Error creating UGI from subject. subject="
+ + serverSubject);
+ }
+ } else {
+ logger.error("Total logins were successfull from keytab="
+ + keytab + ", principal=" + principal);
+ }
}
+ } else {
+ logger.info("Creating UGI from keytab directly. keytab="
+ + keytab + ", principal=" + spnegoPrincipals[0]);
+ UserGroupInformation ugi = UserGroupInformation
+ .loginUserFromKeytabAndReturnUGI(spnegoPrincipals[0],
+ keytab);
+ MiscUtil.setUGILoginUser(ugi, null);
}
+
} catch (Throwable t) {
logger.error("Failed to login as [" + spnegoPrincipals + "]", t);
}
- if (successLoginCount > 0) {
- logger.info("Total login success count=" + successLoginCount);
- try {
- UserGroupInformation ugi = createUGIFromSubject(serverSubject);
- if (ugi != null) {
- setUGILoginUser(ugi, serverSubject);
- }
- } catch (Throwable e) {
- logger.error("Error creating UGI from subject. subject="
- + serverSubject);
- }
- } else {
- logger.error("Total logins were successfull from keytab=" + keytab
- + ", principal=" + principal);
- }
}
static class LogHistory {
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/queue/AuditQueue.java b/agents-audit/src/main/java/org/apache/ranger/audit/queue/AuditQueue.java
index 000a658b276..88c98314b96 100644
--- a/agents-audit/src/main/java/org/apache/ranger/audit/queue/AuditQueue.java
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/queue/AuditQueue.java
@@ -132,6 +132,18 @@ public void setParentPath(String parentPath) {
}
}
+ @Override
+ public String getFinalPath() {
+ if (consumer != null) {
+ if (consumer instanceof BaseAuditHandler) {
+ return ((BaseAuditHandler) consumer).getFinalPath();
+ } else {
+ return consumer.getName();
+ }
+ }
+ return getName();
+ }
+
@Override
public void setName(String name) {
super.setName(name);
From 69e0e8c12e0dad74834e6f92e4d40fe77b5a2a29 Mon Sep 17 00:00:00 2001
From: sneethiraj
Date: Tue, 30 Jun 2015 10:21:46 -0400
Subject: [PATCH 021/202] RANGER-574: fixes to add hdfs jars to knox/kms/storm
bundles (Changes from Ramesh Mani)
---
kms/pom.xml | 5 +++++
knox-agent/pom.xml | 12 +++++++++++-
pom.xml | 1 +
src/main/assembly/kms.xml | 7 ++++++-
src/main/assembly/knox-agent.xml | 9 ++++++---
src/main/assembly/storm-agent.xml | 4 ++++
storm-agent/pom.xml | 15 +++++++++++++++
7 files changed, 48 insertions(+), 5 deletions(-)
diff --git a/kms/pom.xml b/kms/pom.xml
index a726a86678d..877ad95d1a8 100644
--- a/kms/pom.xml
+++ b/kms/pom.xml
@@ -441,6 +441,11 @@
noggit
${noggit.version}
+
+ org.apache.hadoop
+ hadoop-hdfs
+ ${hadoop.version}
+
diff --git a/knox-agent/pom.xml b/knox-agent/pom.xml
index d817836e1f3..85506df8f52 100644
--- a/knox-agent/pom.xml
+++ b/knox-agent/pom.xml
@@ -94,10 +94,20 @@
commons-lang
${commons.lang.version}
-
+
commons-collections
commons-collections
${commons.collections.version}
+
+ org.apache.hadoop
+ hadoop-hdfs
+ ${hadoop.version}
+
+
+ org.htrace
+ htrace-core
+ ${htrace-core.version}
+
diff --git a/pom.xml b/pom.xml
index 0cd84f34310..99a23b27cf5 100644
--- a/pom.xml
+++ b/pom.xml
@@ -132,6 +132,7 @@
2.7.0
2.7.0
2.7.0
+ 3.0.4
1.3
1.1.0
1.2.0
diff --git a/src/main/assembly/kms.xml b/src/main/assembly/kms.xml
index a2e0e2a8af2..33da2486c43 100755
--- a/src/main/assembly/kms.xml
+++ b/src/main/assembly/kms.xml
@@ -96,12 +96,14 @@
com.google.code.findbugs:jsr305
io.netty:netty
com.thoughtworks.paranamer:paranamer
- com.google.protobuf:protobuf-java
org.xerial.snappy:snappy-java
xmlenc:xmlenc
org.tukaani:xz
org.apache.httpcomponents:httpmime:jar:${httpcomponent.httpmime.version}
org.noggit:noggit:jar:${noggit.version}
+ com.google.protobuf:protobuf-java:jar:${protobuf-java.version}
+ org.apache.hadoop:hadoop-hdfs:jar:${hadoop.version}
+ org.htrace:htrace-core:jar:${htrace-core.version}
@@ -135,6 +137,9 @@
org.apache.tomcat.embed:tomcat-embed*
org.eclipse.jdt.core.compiler:ecj:jar:P20140317-1600
+ com.google.protobuf:protobuf-java:jar:${protobuf-java.version}
+ org.apache.hadoop:hadoop-hdfs:jar:${hadoop.version}
+ org.htrace:htrace-core:jar:${htrace-core.version}
false
diff --git a/src/main/assembly/knox-agent.xml b/src/main/assembly/knox-agent.xml
index 85a1d92dd6f..d21487a57c1 100644
--- a/src/main/assembly/knox-agent.xml
+++ b/src/main/assembly/knox-agent.xml
@@ -35,9 +35,12 @@
/lib
commons-configuration:commons-configuration
- org.apache.httpcomponents:httpmime:jar:${httpcomponent.httpmime.version}
- org.noggit:noggit:jar:${noggit.version}
-
+ org.apache.httpcomponents:httpmime:jar:${httpcomponent.httpmime.version}
+ org.noggit:noggit:jar:${noggit.version}
+ com.google.protobuf:protobuf-java:jar:${protobuf-java.version}
+ org.apache.hadoop:hadoop-hdfs:jar:${hadoop.version}
+ org.htrace:htrace-core:jar:${htrace-core.version}
+
false
diff --git a/src/main/assembly/storm-agent.xml b/src/main/assembly/storm-agent.xml
index bbf8543c8ca..8753e43b36d 100644
--- a/src/main/assembly/storm-agent.xml
+++ b/src/main/assembly/storm-agent.xml
@@ -52,6 +52,10 @@
org.apache.httpcomponents:httpcore:jar:${httpcomponent.httpcore.version}
org.apache.httpcomponents:httpmime:jar:${httpcomponent.httpmime.version}
org.noggit:noggit:jar:${noggit.version}
+ com.google.protobuf:protobuf-java:jar:${protobuf-java.version}
+ org.apache.hadoop:hadoop-hdfs:jar:${hadoop.version}
+ org.htrace:htrace-core:jar:${htrace-core.version}
+ commons-cli:commons-cli:jar:${commons.cli.version}
diff --git a/storm-agent/pom.xml b/storm-agent/pom.xml
index 507598772d6..b59bd8c5056 100644
--- a/storm-agent/pom.xml
+++ b/storm-agent/pom.xml
@@ -52,5 +52,20 @@
credentialbuilder
${project.version}
+
+ org.apache.hadoop
+ hadoop-hdfs
+ ${hadoop.version}
+
+
+ commons-cli
+ commons-cli
+ ${commons.cli.version}
+
+
+ org.htrace
+ htrace-core
+ ${htrace-core.version}
+
From b0d3cfb686eaad108c574f2cbfe782b63668b80e Mon Sep 17 00:00:00 2001
From: sneethiraj
Date: Wed, 1 Jul 2015 12:28:43 -0400
Subject: [PATCH 022/202] RANGER-574: resubmitting the additional jar as the
htrace lib should be bundled from org.apache.htrace and not from org.htrace
---
kms/pom.xml | 4 ++--
knox-agent/pom.xml | 2 +-
pom.xml | 2 +-
src/main/assembly/kms.xml | 6 +++---
src/main/assembly/knox-agent.xml | 2 +-
src/main/assembly/storm-agent.xml | 2 +-
storm-agent/pom.xml | 2 +-
7 files changed, 10 insertions(+), 10 deletions(-)
diff --git a/kms/pom.xml b/kms/pom.xml
index 877ad95d1a8..b89837dcae9 100644
--- a/kms/pom.xml
+++ b/kms/pom.xml
@@ -332,9 +332,9 @@
${hadoop-auth.version}
- org.htrace
+ org.apache.htrace
htrace-core
- 3.0.4
+ ${htrace-core.version}
org.apache.httpcomponents
diff --git a/knox-agent/pom.xml b/knox-agent/pom.xml
index 85506df8f52..9e85527e261 100644
--- a/knox-agent/pom.xml
+++ b/knox-agent/pom.xml
@@ -105,7 +105,7 @@
${hadoop.version}
- org.htrace
+ org.apache.htrace
htrace-core
${htrace-core.version}
diff --git a/pom.xml b/pom.xml
index 99a23b27cf5..2ae8d3d0b6c 100644
--- a/pom.xml
+++ b/pom.xml
@@ -132,7 +132,7 @@
2.7.0
2.7.0
2.7.0
- 3.0.4
+ 3.1.0-incubating
1.3
1.1.0
1.2.0
diff --git a/src/main/assembly/kms.xml b/src/main/assembly/kms.xml
index 33da2486c43..52ab5a0d1eb 100755
--- a/src/main/assembly/kms.xml
+++ b/src/main/assembly/kms.xml
@@ -81,7 +81,7 @@
org.apache.curator:curator-recipes
com.google.code.gson:gson
org.apache.hadoop:hadoop-annotations
- org.htrace:htrace-core
+ org.apache.htrace:htrace-core
org.apache.httpcomponents:httpcore
org.codehaus.jackson:jackson-core-asl
org.codehaus.jackson:jackson-jaxrs
@@ -103,7 +103,7 @@
org.noggit:noggit:jar:${noggit.version}
com.google.protobuf:protobuf-java:jar:${protobuf-java.version}
org.apache.hadoop:hadoop-hdfs:jar:${hadoop.version}
- org.htrace:htrace-core:jar:${htrace-core.version}
+ org.apache.htrace:htrace-core:jar:${htrace-core.version}
@@ -139,7 +139,7 @@
org.eclipse.jdt.core.compiler:ecj:jar:P20140317-1600
com.google.protobuf:protobuf-java:jar:${protobuf-java.version}
org.apache.hadoop:hadoop-hdfs:jar:${hadoop.version}
- org.htrace:htrace-core:jar:${htrace-core.version}
+ org.apache.htrace:htrace-core:jar:${htrace-core.version}
false
diff --git a/src/main/assembly/knox-agent.xml b/src/main/assembly/knox-agent.xml
index d21487a57c1..7c082708be2 100644
--- a/src/main/assembly/knox-agent.xml
+++ b/src/main/assembly/knox-agent.xml
@@ -39,7 +39,7 @@
org.noggit:noggit:jar:${noggit.version}
com.google.protobuf:protobuf-java:jar:${protobuf-java.version}
org.apache.hadoop:hadoop-hdfs:jar:${hadoop.version}
- org.htrace:htrace-core:jar:${htrace-core.version}
+ org.apache.htrace:htrace-core:jar:${htrace-core.version}
false
diff --git a/src/main/assembly/storm-agent.xml b/src/main/assembly/storm-agent.xml
index 8753e43b36d..aacdb78d185 100644
--- a/src/main/assembly/storm-agent.xml
+++ b/src/main/assembly/storm-agent.xml
@@ -54,7 +54,7 @@
org.noggit:noggit:jar:${noggit.version}
com.google.protobuf:protobuf-java:jar:${protobuf-java.version}
org.apache.hadoop:hadoop-hdfs:jar:${hadoop.version}
- org.htrace:htrace-core:jar:${htrace-core.version}
+ org.apache.htrace:htrace-core:jar:${htrace-core.version}
commons-cli:commons-cli:jar:${commons.cli.version}
diff --git a/storm-agent/pom.xml b/storm-agent/pom.xml
index b59bd8c5056..5fd0aa35133 100644
--- a/storm-agent/pom.xml
+++ b/storm-agent/pom.xml
@@ -63,7 +63,7 @@
${commons.cli.version}
- org.htrace
+ org.apache.htrace
htrace-core
${htrace-core.version}
From 6729af52109835b882611687562b9d89f9b0669f Mon Sep 17 00:00:00 2001
From: Gautam Borad
Date: Mon, 6 Jul 2015 13:58:41 +0530
Subject: [PATCH 023/202] RANGER-575 : Allow KMS policies to be assigned to all
users
Signed-off-by: sneethiraj
---
.../webapp/scripts/views/policies/PermissionList.js | 11 +----------
.../src/main/webapp/scripts/views/users/UserForm.js | 3 ++-
2 files changed, 3 insertions(+), 11 deletions(-)
diff --git a/security-admin/src/main/webapp/scripts/views/policies/PermissionList.js b/security-admin/src/main/webapp/scripts/views/policies/PermissionList.js
index 09018922edb..0cba319728b 100644
--- a/security-admin/src/main/webapp/scripts/views/policies/PermissionList.js
+++ b/security-admin/src/main/webapp/scripts/views/policies/PermissionList.js
@@ -200,16 +200,7 @@ define(function(require) {
url: url,
dataType: 'json',
data: function (term, page) {
- var data = { name : term, isVisible : XAEnums.VisibilityStatus.STATUS_VISIBLE.value };
- var userRoleList = []
- _.each(XAEnums.UserRoles,function(val, key){
- if(SessionMgr.isKeyAdmin() && XAEnums.UserRoles.ROLE_KEY_ADMIN.value == val.value){
- userRoleList.push(key)
- }else if(!SessionMgr.isKeyAdmin() && XAEnums.UserRoles.ROLE_KEY_ADMIN.value != val.value){
- userRoleList.push(key)
- }
- })
- return _.extend(data,{'userRoleList' : userRoleList });
+ return {name : term, isVisible : XAEnums.VisibilityStatus.STATUS_VISIBLE.value};
},
results: function (data, page) {
var results = [] , selectedVals = [];
diff --git a/security-admin/src/main/webapp/scripts/views/users/UserForm.js b/security-admin/src/main/webapp/scripts/views/users/UserForm.js
index 31e99ced55b..52a278d2fae 100644
--- a/security-admin/src/main/webapp/scripts/views/users/UserForm.js
+++ b/security-admin/src/main/webapp/scripts/views/users/UserForm.js
@@ -144,7 +144,8 @@ define(function(require){
if(SessionMgr.getUserProfile().get('loginId') != "admin"){
if(this.model.get('name') != "admin"){
- if(_.contains(SessionMgr.getUserProfile().get('userRoleList'),'ROLE_SYS_ADMIN')){
+ if(_.contains(SessionMgr.getUserProfile().get('userRoleList'),'ROLE_SYS_ADMIN')
+ || _.contains(SessionMgr.getUserProfile().get('userRoleList'),'ROLE_KEY_ADMIN')){
this.fields.userRoleList.editor.$el.attr('disabled',false);
}else{
if(!SessionMgr.isKeyAdmin()){
From 353d1a53aa98560a455e735476165a50181e1591 Mon Sep 17 00:00:00 2001
From: rmani
Date: Thu, 9 Jul 2015 17:37:06 -0700
Subject: [PATCH 024/202] RANGER-576:Storm audit not showing access type in the
Ranger Admin Audit UI
---
.../org/apache/ranger/authorization/storm/StormRangerPlugin.java | 1 +
1 file changed, 1 insertion(+)
diff --git a/storm-agent/src/main/java/org/apache/ranger/authorization/storm/StormRangerPlugin.java b/storm-agent/src/main/java/org/apache/ranger/authorization/storm/StormRangerPlugin.java
index 323ab58ca00..f8663af86aa 100644
--- a/storm-agent/src/main/java/org/apache/ranger/authorization/storm/StormRangerPlugin.java
+++ b/storm-agent/src/main/java/org/apache/ranger/authorization/storm/StormRangerPlugin.java
@@ -68,6 +68,7 @@ public RangerAccessRequest buildAccessRequest(String _user, String[] _groups, St
}
request.setAccessType(_operation);
request.setClientIPAddress(_clientIp);
+ request.setAction(_operation);
// build resource and connect stuff into request
RangerAccessResourceImpl resource = new RangerAccessResourceImpl();
resource.setValue(ResourceName.Topology, _topology);
From 4874016ad8d686710ba6db266cb449800438739f Mon Sep 17 00:00:00 2001
From: Gautam Borad
Date: Mon, 17 Aug 2015 10:24:19 +0530
Subject: [PATCH 025/202] RANGER-614.2 : Provide support of SQL Anywhere as a
DB in Ranger
Signed-off-by: sneethiraj
---
.../audit/provider/DbAuditProvider.java | 2 +-
agents-common/scripts/enable-agent.sh | 4 +
hbase-agent/scripts/install.sh | 12 +
hdfs-agent/scripts/install.sh | 12 +
hive-agent/scripts/install.sh | 12 +
.../main/java/org/apache/util/sql/Jisql.java | 13 +
.../sqlanywhere/kms_core_db_sqlanywhere.sql | 44 +
.../db/sqlserver/kms_core_db_sqlserver.sql | 1 +
kms/scripts/db_setup.py | 96 ++
kms/scripts/dba_script.py | 185 ++-
kms/scripts/install.properties | 6 +-
kms/scripts/setup.sh | 26 +
knox-agent/scripts/install.sh | 12 +
.../sqlanywhere/create_dbversion_catalog.sql | 26 +
.../sqlanywhere/xa_audit_db_sqlanywhere.sql | 56 +
.../db/sqlanywhere/xa_core_db_sqlanywhere.sql | 1107 +++++++++++++++++
security-admin/scripts/db_setup.py | 278 +++++
security-admin/scripts/dba_script.py | 214 +++-
security-admin/scripts/install.properties | 22 +-
security-admin/scripts/setup.sh | 40 +
.../org/apache/ranger/biz/RangerBizUtil.java | 4 +
.../org/apache/ranger/biz/SessionMgr.java | 9 +-
.../apache/ranger/common/AppConstants.java | 1 +
.../listener/SpringEventListener.java | 8 +-
storm-agent/scripts/install.sh | 12 +
25 files changed, 2180 insertions(+), 22 deletions(-)
create mode 100644 kms/scripts/db/sqlanywhere/kms_core_db_sqlanywhere.sql
create mode 100644 security-admin/db/sqlanywhere/create_dbversion_catalog.sql
create mode 100644 security-admin/db/sqlanywhere/xa_audit_db_sqlanywhere.sql
create mode 100644 security-admin/db/sqlanywhere/xa_core_db_sqlanywhere.sql
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/provider/DbAuditProvider.java b/agents-audit/src/main/java/org/apache/ranger/audit/provider/DbAuditProvider.java
index d475f8976e4..98da1c2d814 100644
--- a/agents-audit/src/main/java/org/apache/ranger/audit/provider/DbAuditProvider.java
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/provider/DbAuditProvider.java
@@ -199,7 +199,7 @@ private synchronized boolean init() {
}
LOG.info("DbAuditProvider: init()");
-
+ LOG.info("java.library.path:"+System.getProperty("java.library.path"));
try {
entityManagerFactory = Persistence.createEntityManagerFactory("xa_server", mDbProperties);
diff --git a/agents-common/scripts/enable-agent.sh b/agents-common/scripts/enable-agent.sh
index 16efe7490d1..6adb2c44e90 100755
--- a/agents-common/scripts/enable-agent.sh
+++ b/agents-common/scripts/enable-agent.sh
@@ -382,6 +382,10 @@ then
then
export XAAUDIT_DB_JDBC_URL="jdbc:sqlserver://${audit_db_hostname};databaseName=${audit_db_name}"
export XAAUDIT_DB_JDBC_DRIVER="com.microsoft.sqlserver.jdbc.SQLServerDriver"
+ elif [ "${db_flavor}" = "SQLANYWHERE" ]
+ then
+ export XAAUDIT_DB_JDBC_URL="jdbc:sqlanywhere:database=${audit_db_name};host=${audit_db_hostname}"
+ export XAAUDIT_DB_JDBC_DRIVER="sap.jdbc4.sqlanywhere.IDriver"
else
echo "Audit is not specified with a valid db_flavor: [${db_flavor}]. Ignoring audit ..."
export XAAUDIT_DB_JDBC_URL="jdbc:${db_flavor}://${audit_db_hostname}/${audit_db_name}"
diff --git a/hbase-agent/scripts/install.sh b/hbase-agent/scripts/install.sh
index 8190603b265..116beab58e8 100644
--- a/hbase-agent/scripts/install.sh
+++ b/hbase-agent/scripts/install.sh
@@ -312,6 +312,18 @@ then
newPropertyValue="com.microsoft.sqlserver.jdbc.SQLServerDriver"
updatePropertyToFile $propertyName $newPropertyValue $to_file
fi
+if [ "${DB_FLAVOR}" == "SQLANYWHERE" ]
+then
+ audit_db_hostname=`grep '^XAAUDIT.DB.HOSTNAME' ${install_dir}/install.properties | awk -F= '{ print $2 }'`
+ audit_db_name=`grep '^XAAUDIT.DB.DATABASE_NAME' ${install_dir}/install.properties | awk -F= '{ print $2 }'`
+ propertyName=XAAUDIT.DB.JDBC_URL
+ newPropertyValue="jdbc:sqlanywhere:database=${audit_db_name};host=${audit_db_hostname}"
+ updatePropertyToFile $propertyName $newPropertyValue $to_file
+
+ propertyName=XAAUDIT.DB.JDBC_DRIVER
+ newPropertyValue="sap.jdbc4.sqlanywhere.IDriver"
+ updatePropertyToFile $propertyName $newPropertyValue $to_file
+fi
for f in ${install_dir}/installer/conf/*-changes.cfg
do
if [ -f ${f} ]
diff --git a/hdfs-agent/scripts/install.sh b/hdfs-agent/scripts/install.sh
index 2afd030872f..e9215fdc720 100644
--- a/hdfs-agent/scripts/install.sh
+++ b/hdfs-agent/scripts/install.sh
@@ -319,6 +319,18 @@ then
newPropertyValue="com.microsoft.sqlserver.jdbc.SQLServerDriver"
updatePropertyToFile $propertyName $newPropertyValue $to_file
fi
+if [ "${DB_FLAVOR}" == "SQLANYWHERE" ]
+then
+ audit_db_hostname=`grep '^XAAUDIT.DB.HOSTNAME' ${install_dir}/install.properties | awk -F= '{ print $2 }'`
+ audit_db_name=`grep '^XAAUDIT.DB.DATABASE_NAME' ${install_dir}/install.properties | awk -F= '{ print $2 }'`
+ propertyName=XAAUDIT.DB.JDBC_URL
+ newPropertyValue="jdbc:sqlanywhere:database=${audit_db_name};host=${audit_db_hostname}"
+ updatePropertyToFile $propertyName $newPropertyValue $to_file
+
+ propertyName=XAAUDIT.DB.JDBC_DRIVER
+ newPropertyValue="sap.jdbc4.sqlanywhere.IDriver"
+ updatePropertyToFile $propertyName $newPropertyValue $to_file
+fi
for f in ${install_dir}/installer/conf/*-changes.cfg
do
if [ -f ${f} ]
diff --git a/hive-agent/scripts/install.sh b/hive-agent/scripts/install.sh
index 6798a3cb37f..74c6e568a87 100644
--- a/hive-agent/scripts/install.sh
+++ b/hive-agent/scripts/install.sh
@@ -296,6 +296,18 @@ then
newPropertyValue="com.microsoft.sqlserver.jdbc.SQLServerDriver"
updatePropertyToFile $propertyName $newPropertyValue $to_file
fi
+if [ "${DB_FLAVOR}" == "SQLANYWHERE" ]
+then
+ audit_db_hostname=`grep '^XAAUDIT.DB.HOSTNAME' ${install_dir}/install.properties | awk -F= '{ print $2 }'`
+ audit_db_name=`grep '^XAAUDIT.DB.DATABASE_NAME' ${install_dir}/install.properties | awk -F= '{ print $2 }'`
+ propertyName=XAAUDIT.DB.JDBC_URL
+ newPropertyValue="jdbc:sqlanywhere:database=${audit_db_name};host=${audit_db_hostname}"
+ updatePropertyToFile $propertyName $newPropertyValue $to_file
+
+ propertyName=XAAUDIT.DB.JDBC_DRIVER
+ newPropertyValue="sap.jdbc4.sqlanywhere.IDriver"
+ updatePropertyToFile $propertyName $newPropertyValue $to_file
+fi
for f in ${install_dir}/installer/conf/*-changes.cfg
do
if [ -f ${f} ]
diff --git a/jisql/src/main/java/org/apache/util/sql/Jisql.java b/jisql/src/main/java/org/apache/util/sql/Jisql.java
index b9453e8b96e..cf7563c7130 100644
--- a/jisql/src/main/java/org/apache/util/sql/Jisql.java
+++ b/jisql/src/main/java/org/apache/util/sql/Jisql.java
@@ -214,6 +214,9 @@
*
*/
public class Jisql {
+ //Sybase SQL Anywhere JDBC4-Type2 (Native) Driver
+ private static final String sapJDBC4SqlAnywhereDriverName= "sap.jdbc4.sqlanywhere.IDriver";
+ private static final String sybaseJDBC4SqlAnywhereDriverName= "sybase.jdbc4.sqlanywhere.IDriver";
private static final String sybaseJConnect6DriverName = "com.sybase.jdbc3.jdbc.SybDriver";
private static final String sybaseJConnect5DriverName = "com.sybase.jdbc2.jdbc.SybDriver";
private static final String sybaseJConnect4DriverName = "com.sybase.jdbc.SybDriver";
@@ -518,6 +521,12 @@ public void doIsql() throws IOException, SQLException {
// Ignore IOE when closing streams
}
}
+ if (resultSet != null) {
+ try {
+ resultSet.close();
+ } catch (SQLException sqle) {
+ }
+ }
if (statement != null) {
try {
statement.close();
@@ -649,6 +658,10 @@ else if (driverName.compareToIgnoreCase("mysqlconj") == 0)
driverName = mySQLConnectJDriverName;
else if (driverName.compareToIgnoreCase("mysqlcaucho") == 0)
driverName = mySQLCauchoDriverName;
+ else if (driverName.compareToIgnoreCase("sapsajdbc4") == 0)
+ driverName = sapJDBC4SqlAnywhereDriverName;
+ else if (driverName.compareToIgnoreCase("sybasesajdbc4") == 0)
+ driverName = sybaseJDBC4SqlAnywhereDriverName;
}
connectString = (String) options.valueOf("cstring");
diff --git a/kms/scripts/db/sqlanywhere/kms_core_db_sqlanywhere.sql b/kms/scripts/db/sqlanywhere/kms_core_db_sqlanywhere.sql
new file mode 100644
index 00000000000..fd7abdda461
--- /dev/null
+++ b/kms/scripts/db/sqlanywhere/kms_core_db_sqlanywhere.sql
@@ -0,0 +1,44 @@
+-- Licensed to the Apache Software Foundation(ASF) under one or more
+-- contributor license agreements. See the NOTICE file distributed with
+-- this work for additional information regarding copyright ownership.
+-- The ASF licenses this file to You under the Apache License, Version 2.0
+--(the "License"); you may not use this file except in compliance with
+-- the License. You may obtain a copy of the License at
+--
+-- http://www.apache.org/licenses/LICENSE-2.0
+--
+-- Unless required by applicable law or agreed to in writing,software
+-- distributed under the License is distributed on an "AS IS" BASIS,
+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+-- See the License for the specific language governing permissions and
+-- limitations under the License.
+CREATE TABLE ranger_masterkey(
+ id bigint IDENTITY NOT NULL,
+ create_time datetime DEFAULT NULL NULL,
+ update_time datetime DEFAULT NULL NULL,
+ added_by_id bigint DEFAULT NULL NULL,
+ upd_by_id bigint DEFAULT NULL NULL,
+ cipher varchar(255) DEFAULT NULL NULL,
+ bitlength int DEFAULT NULL NULL,
+ masterkey varchar(2048),
+ CONSTRAINT ranger_masterkey_PK_id PRIMARY KEY CLUSTERED(id)
+)
+GO
+CREATE TABLE ranger_keystore(
+ id bigint IDENTITY NOT NULL,
+ create_time datetime DEFAULT NULL NULL,
+ update_time datetime DEFAULT NULL NULL,
+ added_by_id bigint DEFAULT NULL NULL,
+ upd_by_id bigint DEFAULT NULL NULL,
+ kms_alias varchar(255) NOT NULL,
+ kms_createdDate bigint DEFAULT NULL NULL,
+ kms_cipher varchar(255) DEFAULT NULL NULL,
+ kms_bitLength bigint DEFAULT NULL NULL,
+ kms_description varchar(512) DEFAULT NULL NULL,
+ kms_version bigint DEFAULT NULL NULL,
+ kms_attributes varchar(1024) DEFAULT NULL NULL,
+ kms_encoded varchar(2048),
+ CONSTRAINT ranger_keystore_PK_id PRIMARY KEY CLUSTERED(id)
+)
+GO
+exit
diff --git a/kms/scripts/db/sqlserver/kms_core_db_sqlserver.sql b/kms/scripts/db/sqlserver/kms_core_db_sqlserver.sql
index 32cc38c16d3..6567d3bd6b8 100644
--- a/kms/scripts/db/sqlserver/kms_core_db_sqlserver.sql
+++ b/kms/scripts/db/sqlserver/kms_core_db_sqlserver.sql
@@ -44,6 +44,7 @@ CREATE TABLE [dbo].[ranger_keystore](
[create_time] [datetime2] DEFAULT NULL NULL,
[update_time] [datetime2] DEFAULT NULL NULL,
[added_by_id] [bigint] DEFAULT NULL NULL,
+ [upd_by_id] [bigint] DEFAULT NULL NULL,
[kms_alias] [varchar](255) NOT NULL,
[kms_createdDate] [bigint] DEFAULT NULL NULL,
[kms_cipher] [varchar](255) DEFAULT NULL NULL,
diff --git a/kms/scripts/db_setup.py b/kms/scripts/db_setup.py
index 8116049a270..9dbeb04c471 100644
--- a/kms/scripts/db_setup.py
+++ b/kms/scripts/db_setup.py
@@ -402,6 +402,89 @@ def check_table(self, db_name, db_user, db_password, TABLE_NAME):
log("[I] Table '" + TABLE_NAME + "' does not exist in database '" + db_name + "'","info")
return False
+class SqlAnywhereConf(BaseDB):
+ # Constructor
+ def __init__(self, host, SQL_CONNECTOR_JAR, JAVA_BIN):
+ self.host = host
+ self.SQL_CONNECTOR_JAR = SQL_CONNECTOR_JAR
+ self.JAVA_BIN = JAVA_BIN
+
+ def get_jisql_cmd(self, user, password, db_name):
+ path = RANGER_KMS_HOME
+ self.JAVA_BIN = self.JAVA_BIN.strip("'")
+ if os_name == "LINUX":
+ jisql_cmd = "%s -cp %s:%s/jisql/lib/* org.apache.util.sql.Jisql -user %s -password %s -driver sapsajdbc4 -cstring jdbc:sqlanywhere:database=%s;host=%s -noheader -trim"%(self.JAVA_BIN, self.SQL_CONNECTOR_JAR, path,user, password,db_name,self.host)
+ elif os_name == "WINDOWS":
+ jisql_cmd = "%s -cp %s;%s\\jisql\\lib\\* org.apache.util.sql.Jisql -user %s -password %s -driver sapsajdbc4 -cstring jdbc:sqlanywhere:database=%s;host=%s -noheader -trim"%(self.JAVA_BIN, self.SQL_CONNECTOR_JAR, path, user, password,db_name,self.host)
+ return jisql_cmd
+
+ def check_connection(self, db_name, db_user, db_password):
+ log("[I] Checking connection", "info")
+ get_cmd = self.get_jisql_cmd(db_user, db_password, db_name)
+ if os_name == "LINUX":
+ query = get_cmd + " -c \; -query \"SELECT 1;\""
+ elif os_name == "WINDOWS":
+ query = get_cmd + " -query \"SELECT 1;\" -c ;"
+ output = check_output(query)
+ if output.strip('1 |'):
+ log("[I] Connection success", "info")
+ return True
+ else:
+ log("[E] Can't establish connection", "error")
+ sys.exit(1)
+
+ def import_db_file(self, db_name, db_user, db_password, file_name):
+ name = basename(file_name)
+ if os.path.isfile(file_name):
+ log("[I] Importing db schema to database " + db_name + " from file: " + name,"info")
+ get_cmd = self.get_jisql_cmd(db_user, db_password, db_name)
+ if os_name == "LINUX":
+ query = get_cmd + " -input %s" %file_name
+ ret = subprocess.call(shlex.split(query))
+ elif os_name == "WINDOWS":
+ query = get_cmd + " -input %s" %file_name
+ ret = subprocess.call(query)
+ if ret == 0:
+ log("[I] "+name + " DB schema imported successfully","info")
+ else:
+ log("[E] "+name + " DB Schema import failed!","error")
+ sys.exit(1)
+ else:
+ log("[I] DB Schema file " + name+ " not found","error")
+ sys.exit(1)
+
+ def check_table(self, db_name, db_user, db_password, TABLE_NAME):
+ self.set_options(db_name, db_user, db_password, TABLE_NAME)
+ get_cmd = self.get_jisql_cmd(db_user, db_password, db_name)
+ if os_name == "LINUX":
+ query = get_cmd + " -c \; -query \"SELECT name FROM sysobjects where name = '%s' and type='U';\"" %(TABLE_NAME)
+ elif os_name == "WINDOWS":
+ query = get_cmd + " -query \"SELECT name FROM sysobjects where name = '%s' and type='U';\" -c ;" %(TABLE_NAME)
+ output = check_output(query)
+ if output.strip(TABLE_NAME + " |"):
+ log("[I] Table '" + TABLE_NAME + "' already exists in database '" + db_name + "'","info")
+ return True
+ else:
+ log("[I] Table '" + TABLE_NAME + "' does not exist in database '" + db_name + "'","info")
+ return False
+
+ def set_options(self, db_name, db_user, db_password, TABLE_NAME):
+ get_cmd = self.get_jisql_cmd(db_user, db_password, db_name)
+ if os_name == "LINUX":
+ query = get_cmd + " -c \; -query \"set option public.reserved_keywords='LIMIT';\""
+ elif os_name == "WINDOWS":
+ query = get_cmd + " -query \"set option public.reserved_keywords='LIMIT';\" -c ;"
+ ret = subprocess.call(shlex.split(query))
+ if os_name == "LINUX":
+ query = get_cmd + " -c \; -query \"set option public.max_statement_count=0;\""
+ elif os_name == "WINDOWS":
+ query = get_cmd + " -query \"set option public.max_statement_count=0;\" -c;"
+ ret = subprocess.call(shlex.split(query))
+ if os_name == "LINUX":
+ query = get_cmd + " -c \; -query \"set option public.max_cursor_count=0;\""
+ elif os_name == "WINDOWS":
+ query = get_cmd + " -query \"set option public.max_cursor_count=0;\" -c;"
+ ret = subprocess.call(shlex.split(query))
def main(argv):
populate_global_dict()
@@ -443,6 +526,9 @@ def main(argv):
sqlserver_core_file = globalDict['sqlserver_core_file']
sqlserver_patches = os.path.join('db','sqlserver','patches')
+ sqlanywhere_core_file = globalDict['sqlanywhere_core_file']
+ sqlanywhere_patches = os.path.join('db','sqlanywhere','patches')
+
db_name = globalDict['db_name']
db_user = globalDict['db_user']
db_password = globalDict['db_password']
@@ -470,6 +556,16 @@ def main(argv):
SQLSERVER_CONNECTOR_JAR = globalDict['SQL_CONNECTOR_JAR']
xa_sqlObj = SqlServerConf(xa_db_host, SQLSERVER_CONNECTOR_JAR, JAVA_BIN)
xa_db_core_file = os.path.join(RANGER_KMS_HOME , sqlserver_core_file)
+
+ elif XA_DB_FLAVOR == "SQLANYWHERE":
+ if not os_name == "WINDOWS" :
+ if os.environ['LD_LIBRARY_PATH'] == "":
+ log("[E] ---------- LD_LIBRARY_PATH environment property not defined, aborting installation. ----------", "error")
+ sys.exit(1)
+ SQLANYWHERE_CONNECTOR_JAR = globalDict['SQL_CONNECTOR_JAR']
+ xa_sqlObj = SqlAnywhereConf(xa_db_host, SQLANYWHERE_CONNECTOR_JAR, JAVA_BIN)
+ xa_db_core_file = os.path.join(RANGER_KMS_HOME , sqlanywhere_core_file)
+
else:
log("[E] --------- NO SUCH SUPPORTED DB FLAVOUR!! ---------", "error")
sys.exit(1)
diff --git a/kms/scripts/dba_script.py b/kms/scripts/dba_script.py
index c549fadd64c..0830af4e6fb 100644
--- a/kms/scripts/dba_script.py
+++ b/kms/scripts/dba_script.py
@@ -887,6 +887,177 @@ def grant_xa_db_user(self, root_user, db_name, db_user, db_password, db_root_pas
logFile("ALTER LOGIN [%s] WITH DEFAULT_DATABASE=[%s];" %(db_user, db_name))
logFile("USE %s EXEC sp_addrolemember N'db_owner', N'%s';" %(db_name, db_user))
+class SqlAnywhereConf(BaseDB):
+ # Constructor
+ def __init__(self, host, SQL_CONNECTOR_JAR, JAVA_BIN):
+ self.host = host
+ self.SQL_CONNECTOR_JAR = SQL_CONNECTOR_JAR
+ self.JAVA_BIN = JAVA_BIN
+
+ def get_jisql_cmd(self, user, password, db_name):
+ #TODO: User array for forming command
+ path = RANGER_KMS_HOME
+ self.JAVA_BIN = self.JAVA_BIN.strip("'")
+ if os_name == "LINUX":
+ jisql_cmd = "%s -cp %s:%s/jisql/lib/* org.apache.util.sql.Jisql -user %s -password %s -driver sapsajdbc4 -cstring jdbc:sqlanywhere:database=%s;host=%s -noheader -trim"%(self.JAVA_BIN, self.SQL_CONNECTOR_JAR, path,user, password,db_name,self.host)
+ elif os_name == "WINDOWS":
+ jisql_cmd = "%s -cp %s;%s\\jisql\\lib\\* org.apache.util.sql.Jisql -user %s -password %s -driver sapsajdbc4 -cstring jdbc:sqlanywhere:database=%s;host=%s -noheader -trim"%(self.JAVA_BIN, self.SQL_CONNECTOR_JAR, path, user, password,db_name,self.host)
+ return jisql_cmd
+ def verify_user(self, root_user, db_root_password, db_user,dryMode):
+ if dryMode == False:
+ log("[I] Verifying user " + db_user , "info")
+ get_cmd = self.get_jisql_cmd(root_user, db_root_password, '')
+ if os_name == "LINUX":
+ query = get_cmd + " -c \; -query \"select name from syslogins where name = '%s';\"" %(db_user)
+ elif os_name == "WINDOWS":
+ query = get_cmd + " -query \"select name from syslogins where name = '%s';\" -c ;" %(db_user)
+ output = check_output(query)
+ if output.strip(db_user + " |"):
+ return True
+ else:
+ return False
+
+ def check_connection(self, db_name, db_user, db_password):
+ log("[I] Checking connection", "info")
+ get_cmd = self.get_jisql_cmd(db_user, db_password, db_name)
+ if os_name == "LINUX":
+ query = get_cmd + " -c \; -query \"SELECT 1;\""
+ elif os_name == "WINDOWS":
+ query = get_cmd + " -query \"SELECT 1;\" -c ;"
+ output = check_output(query)
+ if output.strip('1 |'):
+ log("[I] Connection success", "info")
+ return True
+ else:
+ log("[E] Can't establish connection", "error")
+ sys.exit(1)
+ def create_rangerdb_user(self, root_user, db_user, db_password, db_root_password,dryMode):
+ if self.check_connection('', root_user, db_root_password):
+ if self.verify_user(root_user, db_root_password, db_user,dryMode):
+ if dryMode == False:
+ log("[I] SQL Anywhere user " + db_user + " already exists.", "info")
+ else:
+ if dryMode == False:
+ get_cmd = self.get_jisql_cmd(root_user, db_root_password, '')
+ log("[I] User does not exists, Creating Login user " + db_user, "info")
+ if os_name == "LINUX":
+ query = get_cmd + " -c \; -query \"CREATE USER %s IDENTIFIED BY '%s';\"" %(db_user,db_password)
+ ret = subprocess.call(shlex.split(query))
+ elif os_name == "WINDOWS":
+ query = get_cmd + " -query \"CREATE USER %s IDENTIFIED BY '%s';\" -c ;" %(db_user,db_password)
+ ret = subprocess.call(query)
+ if ret == 0:
+ if self.verify_user(root_user, db_root_password, db_user,dryMode):
+ log("[I] SQL Anywhere user " + db_user + " created", "info")
+ else:
+ log("[E] SQL Anywhere user " +db_user+" creation failed..", "error")
+ sys.exit(1)
+ else:
+ log("[E] SQL Anywhere user " +db_user+" creation failed..", "error")
+ sys.exit(1)
+ else:
+ logFile("CREATE USER %s IDENTIFIED BY = '%s';" %(db_user,db_password))
+
+ def verify_db(self, root_user, db_root_password, db_name,dryMode):
+ if dryMode == False:
+ log("[I] Verifying database " + db_name, "info")
+ get_cmd = self.get_jisql_cmd(root_user, db_root_password, '')
+ if os_name == "LINUX":
+ query = get_cmd + " -c \; -query \"select alias from sa_db_info() where alias='%s';\"" %(db_name)
+ elif os_name == "WINDOWS":
+ query = get_cmd + " -query \"select alias from sa_db_info() where alias='%s';\" -c ;" %(db_name)
+ output = check_output(query)
+ if output.strip(db_name + " |"):
+ return True
+ else:
+ return False
+ def create_db(self, root_user, db_root_password, db_name, db_user, db_password,dryMode):
+ if self.verify_db(root_user, db_root_password, db_name,dryMode):
+ if dryMode == False:
+ log("[I] Database " + db_name + " already exists.","info")
+ else:
+ if dryMode == False:
+ log("[I] Database does not exist. Creating database : " + db_name,"info")
+ get_cmd = self.get_jisql_cmd(root_user, db_root_password, '')
+ if os_name == "LINUX":
+ query = get_cmd + " -c \; -query \"create database '%s' dba user '%s' dba password '%s' database size 100MB;\"" %(db_name,db_user, db_password)
+ ret = subprocess.call(shlex.split(query))
+ elif os_name == "WINDOWS":
+ query = get_cmd + " -query \"create database '%s' dba user '%s' dba password '%s' database size 100MB;\" -c ;" %(db_name,db_user, db_password)
+ ret = subprocess.call(query)
+ if ret != 0:
+ log("[E] Database creation failed..","error")
+ sys.exit(1)
+ else:
+ self.start_db(root_user, db_root_password, db_name,dryMode)
+ if self.verify_db(root_user, db_root_password, db_name,dryMode):
+ self.create_user(root_user, db_name ,db_user, db_password, db_root_password,dryMode)
+ log("[I] Creating database " + db_name + " succeeded", "info")
+ return True
+ else:
+ log("[E] Database creation failed..","error")
+ sys.exit(1)
+ else:
+ logFile("create database '%s' dba user '%s' dba password '%s' database size 100MB;" %(db_name,db_user, db_password))
+
+ def create_user(self, root_user, db_name ,db_user, db_password, db_root_password,dryMode):
+ get_cmd = self.get_jisql_cmd(root_user, db_root_password, '')
+ if os_name == "LINUX":
+ query = get_cmd + " -c \; -query \"select name from syslogins where name ='%s';\"" %(db_user)
+ elif os_name == "WINDOWS":
+ query = get_cmd + " -query \"select name from syslogins where name ='%s';\" -c ;" %(db_user)
+ output = check_output(query)
+ if output.strip(db_user + " |"):
+ if dryMode == False:
+ log("[I] User "+db_user+" exist ","info")
+ else:
+ if dryMode == False:
+ if os_name == "LINUX":
+ query = get_cmd + " -c \; -query \"CREATE USER %s IDENTIFIED BY '%s';\"" %(db_user, db_password)
+ ret = subprocess.call(shlex.split(query))
+ elif os_name == "WINDOWS":
+ query = get_cmd + " -query \"CREATE USER %s IDENTIFIED BY '%s';\" -c ;" %(db_user, db_password)
+ ret = subprocess.call(query)
+ if ret == 0:
+ if os_name == "LINUX":
+ query = get_cmd + " -c \; -query \"select name from syslogins where name ='%s';\"" %(db_user)
+ elif os_name == "WINDOWS":
+ query = get_cmd + " -query \"select name from syslogins where name ='%s';\" -c ;" %(db_user)
+ output = check_output(query)
+ if output.strip(db_user + " |"):
+ log("[I] User "+db_user+" exist ","info")
+ else:
+ log("[E] Database creation failed..","error")
+ sys.exit(1)
+ else:
+ log("[E] Database creation failed..","error")
+ sys.exit(1)
+ else:
+ logFile("CREATE USER %s IDENTIFIED BY '%s';" %(db_user, db_password))
+ def grant_xa_db_user(self, root_user, db_name, db_user, db_password, db_root_password, is_revoke,dryMode):
+ if dryMode == False:
+ log("[I] Granting permission to user '" + db_user + "' on db '" + db_name + "'" , "info")
+ get_cmd = self.get_jisql_cmd(root_user, db_root_password, '')
+ if os_name == "LINUX":
+ query = get_cmd + " -c \; -query \"GRANT CONNECT to %s IDENTIFIED BY '%s';\"" %(db_user, db_password)
+ ret = subprocess.call(shlex.split(query))
+ elif os_name == "WINDOWS":
+ query = get_cmd + " -query \"GRANT CONNECT to %s IDENTIFIED BY '%s';\" -c ;" %(db_user, db_password)
+ ret = subprocess.call(query)
+ if ret != 0:
+ sys.exit(1)
+ else:
+ logFile("GRANT CONNECT to %s IDENTIFIED BY '%s';" %(db_user, db_password))
+
+ def start_db(self,root_user, db_root_password, db_name,dryMode):
+ if dryMode == False:
+ log("[I] Starting database " + db_name, "info")
+ get_cmd = self.get_jisql_cmd(root_user, db_root_password, '')
+ if os_name == "LINUX":
+ query = get_cmd + " -c \; -query \"start database '%s' autostop off;\"" %(db_name)
+ elif os_name == "WINDOWS":
+ query = get_cmd + " -query \"start database '%s' autostop off;\" -c ;" %(db_name)
+ output = check_output(query)
def main(argv):
@@ -967,7 +1138,7 @@ def main(argv):
else:
XA_DB_FLAVOR=''
while XA_DB_FLAVOR == "":
- log("Enter db flavour{MYSQL|ORACLE|POSTGRES|MSSQL} :","info")
+ log("Enter db flavour{MYSQL|ORACLE|POSTGRES|MSSQL|SQLANYWHERE} :","info")
XA_DB_FLAVOR=raw_input()
XA_DB_FLAVOR = XA_DB_FLAVOR.upper()
@@ -1042,6 +1213,8 @@ def main(argv):
#sqlserver_core_file = globalDict['sqlserver_core_file']
sqlserver_core_file = os.path.join('db','sqlserver','xa_core_db_sqlserver.sql')
+ sqlanywhere_core_file = os.path.join('db','sqlanywhere','xa_core_db_sqlanywhere.sql')
+
x_db_version = 'x_db_version_h'
x_user = 'x_portal_user'
@@ -1068,6 +1241,16 @@ def main(argv):
SQLSERVER_CONNECTOR_JAR=CONNECTOR_JAR
xa_sqlObj = SqlServerConf(xa_db_host, SQLSERVER_CONNECTOR_JAR, JAVA_BIN)
xa_db_core_file = os.path.join(RANGER_KMS_HOME,sqlserver_core_file)
+
+ elif XA_DB_FLAVOR == "SQLANYWHERE":
+ if not os_name == "WINDOWS" :
+ if os.environ['LD_LIBRARY_PATH'] == "":
+ log("[E] ---------- LD_LIBRARY_PATH environment property not defined, aborting installation. ----------", "error")
+ sys.exit(1)
+ SQLANYWHERE_CONNECTOR_JAR=CONNECTOR_JAR
+ xa_sqlObj = SqlAnywhereConf(xa_db_host, SQLANYWHERE_CONNECTOR_JAR, JAVA_BIN)
+ xa_db_core_file = os.path.join(RANGER_KMS_HOME,sqlanywhere_core_file)
+
else:
log("[E] ---------- NO SUCH SUPPORTED DB FLAVOUR.. ----------", "error")
sys.exit(1)
diff --git a/kms/scripts/install.properties b/kms/scripts/install.properties
index cfe9adf6d28..bad7f204626 100755
--- a/kms/scripts/install.properties
+++ b/kms/scripts/install.properties
@@ -23,7 +23,7 @@
PYTHON_COMMAND_INVOKER=python
-#DB_FLAVOR=MYSQL|ORACLE|POSTGRES|MSSQL
+#DB_FLAVOR=MYSQL|ORACLE|POSTGRES|MSSQL|SQLANYWHERE
DB_FLAVOR=MYSQL
#
# The executable path to be used to invoke command-line MYSQL
@@ -39,6 +39,7 @@ SQL_COMMAND_INVOKER='mysql'
#SQL_CONNECTOR_JAR=/usr/share/java/mysql-connector-java.jar
#SQL_CONNECTOR_JAR=/usr/share/java/postgresql.jar
#SQL_CONNECTOR_JAR=/usr/share/java/sqljdbc4.jar
+#SQL_CONNECTOR_JAR=/opt/sqlanywhere17/java/sajdbc4.jar
SQL_CONNECTOR_JAR=/usr/share/java/mysql-connector-java.jar
@@ -49,7 +50,7 @@ SQL_CONNECTOR_JAR=/usr/share/java/mysql-connector-java.jar
# ** it will be prompted to enter the password during installation process
# **************************************************************************
#
-#db_root_user=root|SYS|postgres|sa
+#db_root_user=root|SYS|postgres|sa|dba
db_root_user=root
db_root_password=
db_host=localhost
@@ -224,6 +225,7 @@ postgres_core_file=db/postgres/kms_core_db_postgres.sql
sqlserver_core_file=db/sqlserver/kms_core_db_sqlserver.sql
+sqlanywhere_core_file=db/sqlanywhere/kms_core_db_sqlanywhere.sql
cred_keystore_filename=$app_home/WEB-INF/classes/conf/.jceks/rangerkms.jceks
KMS_BLACKLIST_DECRYPT_EEK=hdfs
diff --git a/kms/scripts/setup.sh b/kms/scripts/setup.sh
index 972e55e0270..1410f460c21 100755
--- a/kms/scripts/setup.sh
+++ b/kms/scripts/setup.sh
@@ -277,6 +277,19 @@ sanity_check_files() {
log "[E] ${sqlserver_core_file} does not exists" ; exit 1;
fi
fi
+ if [ "${DB_FLAVOR}" == "SQLANYWHERE" ]
+ then
+ if [ "${LD_LIBRARY_PATH}" == "" ]
+ then
+ log "[E] LD_LIBRARY_PATH environment property not defined, aborting installation."
+ exit 1
+ fi
+ if test -f ${sqlanywhere_core_file}; then
+ log "[I] ${sqlanywhere_core_file} file found"
+ else
+ log "[E] ${sqlanywhere_core_file} does not exists" ; exit 1;
+ fi
+ fi
}
create_rollback_point() {
@@ -397,7 +410,20 @@ update_properties() {
updatePropertyToFilePy $propertyName $newPropertyValue $to_file
fi
+ if [ "${DB_FLAVOR}" == "SQLANYWHERE" ]
+ then
+ propertyName=ranger.ks.jpa.jdbc.url
+ newPropertyValue="jdbc:sqlanywhere:database=${db_name};host=${DB_HOST}"
+ updatePropertyToFilePy $propertyName $newPropertyValue $to_file
+
+ propertyName=ranger.ks.jpa.jdbc.dialect
+ newPropertyValue="org.eclipse.persistence.platform.database.SQLAnywherePlatform"
+ updatePropertyToFilePy $propertyName $newPropertyValue $to_file
+ propertyName=ranger.ks.jpa.jdbc.driver
+ newPropertyValue="sap.jdbc4.sqlanywhere.IDriver"
+ updatePropertyToFilePy $propertyName $newPropertyValue $to_file
+ fi
keystore="${cred_keystore_filename}"
echo "Starting configuration for XA DB credentials:"
diff --git a/knox-agent/scripts/install.sh b/knox-agent/scripts/install.sh
index 2255eac8261..163dbc56677 100644
--- a/knox-agent/scripts/install.sh
+++ b/knox-agent/scripts/install.sh
@@ -215,6 +215,18 @@ then
newPropertyValue="com.microsoft.sqlserver.jdbc.SQLServerDriver"
updatePropertyToFile $propertyName $newPropertyValue $to_file
fi
+if [ "${DB_FLAVOR}" == "SQLANYWHERE" ]
+then
+ audit_db_hostname=`grep '^XAAUDIT.DB.HOSTNAME' ${install_dir}/install.properties | awk -F= '{ print $2 }'`
+ audit_db_name=`grep '^XAAUDIT.DB.DATABASE_NAME' ${install_dir}/install.properties | awk -F= '{ print $2 }'`
+ propertyName=XAAUDIT.DB.JDBC_URL
+ newPropertyValue="jdbc:sqlanywhere:database=${audit_db_name};host=${audit_db_hostname}"
+ updatePropertyToFile $propertyName $newPropertyValue $to_file
+
+ propertyName=XAAUDIT.DB.JDBC_DRIVER
+ newPropertyValue="sap.jdbc4.sqlanywhere.IDriver"
+ updatePropertyToFile $propertyName $newPropertyValue $to_file
+fi
for f in ${install_dir}/installer/conf/*-changes.cfg
do
if [ -f ${f} ]
diff --git a/security-admin/db/sqlanywhere/create_dbversion_catalog.sql b/security-admin/db/sqlanywhere/create_dbversion_catalog.sql
new file mode 100644
index 00000000000..59d1b2c548b
--- /dev/null
+++ b/security-admin/db/sqlanywhere/create_dbversion_catalog.sql
@@ -0,0 +1,26 @@
+-- Licensed to the Apache Software Foundation(ASF) under one or more
+-- contributor license agreements. See the NOTICE file distributed with
+-- this work for additional information regarding copyright ownership.
+-- The ASF licenses this file to You under the Apache License, Version 2.0
+--(the "License"); you may not use this file except in compliance with
+-- the License. You may obtain a copy of the License at
+--
+-- http://www.apache.org/licenses/LICENSE-2.0
+--
+-- Unless required by applicable law or agreed to in writing,software
+-- distributed under the License is distributed on an "AS IS" BASIS,
+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+-- See the License for the specific language governing permissions and
+-- limitations under the License.
+
+create table dbo.x_db_version_h(
+id bigint identity not null primary key,
+version varchar(64) not null,
+inst_at datetime not null,
+inst_by varchar(256) not null,
+updated_at datetime not null,
+updated_by varchar(256) not null,
+active varchar(1) default 'Y' check(active IN ('Y', 'N'))
+)
+GO
+exit
\ No newline at end of file
diff --git a/security-admin/db/sqlanywhere/xa_audit_db_sqlanywhere.sql b/security-admin/db/sqlanywhere/xa_audit_db_sqlanywhere.sql
new file mode 100644
index 00000000000..8154a9a8704
--- /dev/null
+++ b/security-admin/db/sqlanywhere/xa_audit_db_sqlanywhere.sql
@@ -0,0 +1,56 @@
+-- Licensed to the Apache Software Foundation(ASF) under one or more
+-- contributor license agreements. See the NOTICE file distributed with
+-- this work for additional information regarding copyright ownership.
+-- The ASF licenses this file to You under the Apache License, Version 2.0
+--(the "License"); you may not use this file except in compliance with
+-- the License. You may obtain a copy of the License at
+--
+-- http://www.apache.org/licenses/LICENSE-2.0
+--
+-- Unless required by applicable law or agreed to in writing,software
+-- distributed under the License is distributed on an "AS IS" BASIS,
+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+-- See the License for the specific language governing permissions and
+-- limitations under the License.
+
+CREATE TABLE dbo.xa_access_audit(
+ id bigint IDENTITY NOT NULL,
+ create_time datetime DEFAULT NULL NULL,
+ update_time datetime DEFAULT NULL NULL,
+ added_by_id bigint DEFAULT NULL NULL,
+ upd_by_id bigint DEFAULT NULL NULL,
+ audit_type int DEFAULT 0 NOT NULL,
+ access_result int DEFAULT 0 NULL,
+ access_type varchar(255) DEFAULT NULL NULL,
+ acl_enforcer varchar(255) DEFAULT NULL NULL,
+ agent_id varchar(255) DEFAULT NULL NULL,
+ client_ip varchar(255) DEFAULT NULL NULL,
+ client_type varchar(255) DEFAULT NULL NULL,
+ policy_id bigint DEFAULT 0 NULL,
+ repo_name varchar(255) DEFAULT NULL NULL,
+ repo_type int DEFAULT 0 NULL,
+ result_reason varchar(255) DEFAULT NULL NULL,
+ session_id varchar(255) DEFAULT NULL NULL,
+ event_time datetime DEFAULT NULL NULL,
+ request_user varchar(255) DEFAULT NULL NULL,
+ action varchar(2000) DEFAULT NULL NULL,
+ request_data varchar(4000) DEFAULT NULL NULL,
+ resource_path varchar(4000) DEFAULT NULL NULL,
+ resource_type varchar(255) DEFAULT NULL NULL,
+ seq_num bigint DEFAULT 0 NULL,
+ event_count bigint DEFAULT 1 NULL,
+ event_dur_ms bigint DEFAULT 1 NULL,
+ CONSTRAINT xa_access_audit_PK_id PRIMARY KEY CLUSTERED(id)
+)
+GO
+CREATE NONCLUSTERED INDEX xa_access_audit_cr_time ON dbo.xa_access_audit(create_time ASC)
+GO
+CREATE NONCLUSTERED INDEX xa_access_audit_event_time ON dbo.xa_access_audit(event_time ASC)
+GO
+CREATE NONCLUSTERED INDEX xa_access_audit_added_by_id ON dbo.xa_access_audit(added_by_id ASC)
+GO
+CREATE NONCLUSTERED INDEX xa_access_audit_upd_by_id ON dbo.xa_access_audit(upd_by_id ASC)
+GO
+CREATE NONCLUSTERED INDEX xa_access_audit_up_time ON dbo.xa_access_audit(update_time ASC)
+GO
+exit
\ No newline at end of file
diff --git a/security-admin/db/sqlanywhere/xa_core_db_sqlanywhere.sql b/security-admin/db/sqlanywhere/xa_core_db_sqlanywhere.sql
new file mode 100644
index 00000000000..0760cb87596
--- /dev/null
+++ b/security-admin/db/sqlanywhere/xa_core_db_sqlanywhere.sql
@@ -0,0 +1,1107 @@
+-- Licensed to the Apache Software Foundation(ASF) under one or more
+-- contributor license agreements. See the NOTICE file distributed with
+-- this work for additional information regarding copyright ownership.
+-- The ASF licenses this file to You under the Apache License, Version 2.0
+--(the "License"); you may not use this file except in compliance with
+-- the License. You may obtain a copy of the License at
+--
+-- http://www.apache.org/licenses/LICENSE-2.0
+--
+-- Unless required by applicable law or agreed to in writing,software
+-- distributed under the License is distributed on an "AS IS" BASIS,
+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+-- See the License for the specific language governing permissions and
+-- limitations under the License.
+
+create table dbo.x_portal_user(
+ id bigint IDENTITY NOT NULL,
+ create_time datetime DEFAULT NULL NULL,
+ update_time datetime DEFAULT NULL NULL,
+ added_by_id bigint DEFAULT NULL NULL,
+ upd_by_id bigint DEFAULT NULL NULL,
+ first_name varchar(256) DEFAULT NULL NULL,
+ last_name varchar(256) DEFAULT NULL NULL,
+ pub_scr_name varchar(2048) DEFAULT NULL NULL,
+ login_id varchar(767) DEFAULT NULL NULL,
+ password varchar(512) NOT NULL,
+ email varchar(512) DEFAULT NULL NULL,
+ status int DEFAULT 0 NOT NULL,
+ user_src int DEFAULT 0 NOT NULL,
+ notes varchar(4000) DEFAULT NULL NULL,
+ CONSTRAINT x_portal_user_PK_id PRIMARY KEY CLUSTERED(id),
+ CONSTRAINT x_portal_user_UK_email UNIQUE NONCLUSTERED (email),
+ CONSTRAINT x_portal_user_UK_login_id UNIQUE NONCLUSTERED (login_id)
+)
+GO
+create table dbo.x_portal_user_role(
+ id bigint IDENTITY NOT NULL,
+ create_time datetime DEFAULT NULL NULL,
+ update_time datetime DEFAULT NULL NULL,
+ added_by_id bigint DEFAULT NULL NULL,
+ upd_by_id bigint DEFAULT NULL NULL,
+ user_id bigint NOT NULL,
+ user_role varchar(128) DEFAULT NULL NULL,
+ status int DEFAULT 0 NOT NULL,
+ CONSTRAINT x_portal_user_role_PK_id PRIMARY KEY CLUSTERED(id)
+)
+GO
+create table dbo.xa_access_audit(
+ id bigint IDENTITY NOT NULL,
+ create_time datetime DEFAULT NULL NULL,
+ update_time datetime DEFAULT NULL NULL,
+ added_by_id bigint DEFAULT NULL NULL,
+ upd_by_id bigint DEFAULT NULL NULL,
+ audit_type int DEFAULT 0 NOT NULL,
+ access_result int DEFAULT 0 NULL,
+ access_type varchar(255) DEFAULT NULL NULL,
+ acl_enforcer varchar(255) DEFAULT NULL NULL,
+ agent_id varchar(255) DEFAULT NULL NULL,
+ client_ip varchar(255) DEFAULT NULL NULL,
+ client_type varchar(255) DEFAULT NULL NULL,
+ policy_id bigint DEFAULT 0 NULL,
+ repo_name varchar(255) DEFAULT NULL NULL,
+ repo_type int DEFAULT 0 NULL,
+ result_reason varchar(255) DEFAULT NULL NULL,
+ session_id varchar(255) DEFAULT NULL NULL,
+ event_time datetime DEFAULT NULL NULL,
+ request_user varchar(255) DEFAULT NULL NULL,
+ action varchar(2000) DEFAULT NULL NULL,
+ request_data varchar(4000) DEFAULT NULL NULL,
+ resource_path varchar(4000) DEFAULT NULL NULL,
+ resource_type varchar(255) DEFAULT NULL NULL,
+ seq_num bigint DEFAULT 0 NULL,
+ event_count bigint DEFAULT 1 NULL,
+ event_dur_ms bigint DEFAULT 1 NULL,
+ CONSTRAINT xa_access_audit_PK_id PRIMARY KEY CLUSTERED(id)
+)
+GO
+create table dbo.x_asset(
+ id bigint IDENTITY NOT NULL,
+ create_time datetime DEFAULT NULL NULL,
+ update_time datetime DEFAULT NULL NULL,
+ added_by_id bigint DEFAULT NULL NULL,
+ upd_by_id bigint DEFAULT NULL NULL,
+ asset_name varchar(1024) NOT NULL,
+ descr varchar(4000) NOT NULL,
+ act_status int DEFAULT 0 NOT NULL,
+ asset_type int DEFAULT 0 NOT NULL,
+ config text NULL,
+ sup_native tinyint DEFAULT 0 NOT NULL,
+ CONSTRAINT x_asset_PK_id PRIMARY KEY CLUSTERED(id)
+)
+GO
+create table dbo.x_auth_sess(
+ id bigint IDENTITY NOT NULL,
+ create_time datetime DEFAULT NULL NULL,
+ update_time datetime DEFAULT NULL NULL,
+ added_by_id bigint DEFAULT NULL NULL,
+ upd_by_id bigint DEFAULT NULL NULL,
+ login_id varchar(767) NOT NULL,
+ user_id bigint DEFAULT NULL NULL,
+ ext_sess_id varchar(512) DEFAULT NULL NULL,
+ auth_time datetime NOT NULL,
+ auth_status int DEFAULT 0 NOT NULL,
+ auth_type int DEFAULT 0 NOT NULL,
+ auth_provider int DEFAULT 0 NOT NULL,
+ device_type int DEFAULT 0 NOT NULL,
+ req_ip varchar(48) NOT NULL,
+ req_ua varchar(1024) DEFAULT NULL NULL,
+ CONSTRAINT x_auth_sess_PK_id PRIMARY KEY CLUSTERED(id)
+)
+GO
+create table dbo.x_cred_store(
+ id bigint IDENTITY NOT NULL,
+ create_time datetime DEFAULT NULL NULL,
+ update_time datetime DEFAULT NULL NULL,
+ added_by_id bigint DEFAULT NULL NULL,
+ upd_by_id bigint DEFAULT NULL NULL,
+ store_name varchar(1024) NOT NULL,
+ descr varchar(4000) NOT NULL,
+ CONSTRAINT x_cred_store_PK_id PRIMARY KEY CLUSTERED(id)
+)
+GO
+create table dbo.x_db_base(
+ id bigint IDENTITY NOT NULL,
+ create_time datetime DEFAULT NULL NULL,
+ update_time datetime DEFAULT NULL NULL,
+ added_by_id bigint DEFAULT NULL NULL,
+ upd_by_id bigint DEFAULT NULL NULL,
+ CONSTRAINT x_db_base_PK_id PRIMARY KEY CLUSTERED(id)
+)
+GO
+create table dbo.x_group(
+ id bigint IDENTITY NOT NULL,
+ create_time datetime DEFAULT NULL NULL,
+ update_time datetime DEFAULT NULL NULL,
+ added_by_id bigint DEFAULT NULL NULL,
+ upd_by_id bigint DEFAULT NULL NULL,
+ group_name varchar(1024) NOT NULL,
+ descr varchar(4000) NOT NULL,
+ status int DEFAULT 0 NOT NULL,
+ group_type int DEFAULT 0 NOT NULL,
+ cred_store_id bigint DEFAULT NULL NULL,
+ group_src int DEFAULT 0 NOT NULL,
+ is_visible int DEFAULT 1 NOT NULL,
+ CONSTRAINT x_group_PK_id PRIMARY KEY CLUSTERED(id)
+)
+GO
+create table dbo.x_group_groups(
+ id bigint IDENTITY NOT NULL,
+ create_time datetime DEFAULT NULL NULL,
+ update_time datetime DEFAULT NULL NULL,
+ added_by_id bigint DEFAULT NULL NULL,
+ upd_by_id bigint DEFAULT NULL NULL,
+ group_name varchar(1024) NOT NULL,
+ p_group_id bigint DEFAULT NULL NULL,
+ group_id bigint DEFAULT NULL NULL,
+ CONSTRAINT x_group_groups_PK_id PRIMARY KEY CLUSTERED(id)
+)
+GO
+create table dbo.x_user(
+ id bigint IDENTITY NOT NULL,
+ create_time datetime DEFAULT NULL NULL,
+ update_time datetime DEFAULT NULL NULL,
+ added_by_id bigint DEFAULT NULL NULL,
+ upd_by_id bigint DEFAULT NULL NULL,
+ user_name varchar(1024) NOT NULL,
+ descr varchar(4000) NOT NULL,
+ status int DEFAULT 0 NOT NULL,
+ cred_store_id bigint DEFAULT NULL NULL,
+ is_visible int DEFAULT 1 NOT NULL,
+ CONSTRAINT x_user_PK_id PRIMARY KEY CLUSTERED(id)
+)
+GO
+create table dbo.x_group_users(
+ id bigint IDENTITY NOT NULL,
+ create_time datetime DEFAULT NULL NULL,
+ update_time datetime DEFAULT NULL NULL,
+ added_by_id bigint DEFAULT NULL NULL,
+ upd_by_id bigint DEFAULT NULL NULL,
+ group_name varchar(1024) NOT NULL,
+ p_group_id bigint DEFAULT NULL NULL,
+ user_id bigint DEFAULT NULL NULL,
+ CONSTRAINT x_group_users_PK_id PRIMARY KEY CLUSTERED(id)
+)
+GO
+create table dbo.x_policy_export_audit(
+ id bigint IDENTITY NOT NULL,
+ create_time datetime DEFAULT NULL NULL,
+ update_time datetime DEFAULT NULL NULL,
+ added_by_id bigint DEFAULT NULL NULL,
+ upd_by_id bigint DEFAULT NULL NULL,
+ client_ip varchar(255) NOT NULL,
+ agent_id varchar(255) DEFAULT NULL NULL,
+ req_epoch bigint NOT NULL,
+ last_updated datetime DEFAULT NULL NULL,
+ repository_name varchar(1024) DEFAULT NULL NULL,
+ exported_json text DEFAULT NULL NULL,
+ http_ret_code int DEFAULT 0 NOT NULL,
+ CONSTRAINT x_policy_export_audit_PK_id PRIMARY KEY CLUSTERED(id)
+)
+GO
+create table dbo.x_resource(
+ id bigint IDENTITY NOT NULL,
+ create_time datetime DEFAULT NULL NULL,
+ update_time datetime DEFAULT NULL NULL,
+ added_by_id bigint DEFAULT NULL NULL,
+ upd_by_id bigint DEFAULT NULL NULL,
+ res_name varchar(4000) DEFAULT NULL NULL,
+ descr varchar(4000) DEFAULT NULL NULL,
+ res_type int DEFAULT 0 NOT NULL,
+ asset_id bigint NOT NULL,
+ parent_id bigint DEFAULT NULL NULL,
+ parent_path varchar(4000) DEFAULT NULL NULL,
+ is_encrypt int DEFAULT 0 NOT NULL,
+ is_recursive int DEFAULT 0 NOT NULL,
+ res_group varchar(1024) DEFAULT NULL NULL,
+ res_dbs text NULL,
+ res_tables text NULL,
+ res_col_fams text NULL,
+ res_cols text NULL,
+ res_udfs text NULL,
+ res_status int DEFAULT 1 NOT NULL,
+ table_type int DEFAULT 0 NOT NULL,
+ col_type int DEFAULT 0 NOT NULL,
+ policy_name varchar(500) DEFAULT NULL NULL,
+ res_topologies text DEFAULT NULL NULL,
+ res_services text DEFAULT NULL NULL,
+ CONSTRAINT x_resource_PK_id PRIMARY KEY CLUSTERED(id)
+)
+GO
+create table dbo.x_trx_log(
+ id bigint IDENTITY NOT NULL,
+ create_time datetime DEFAULT NULL NULL,
+ update_time datetime DEFAULT NULL NULL,
+ added_by_id bigint DEFAULT NULL NULL,
+ upd_by_id bigint DEFAULT NULL NULL,
+ class_type int DEFAULT 0 NOT NULL,
+ object_id bigint DEFAULT NULL NULL,
+ parent_object_id bigint DEFAULT NULL NULL,
+ parent_object_class_type int DEFAULT 0 NOT NULL,
+ parent_object_name varchar(1024) DEFAULT NULL NULL,
+ object_name varchar(1024) DEFAULT NULL NULL,
+ attr_name varchar(255) DEFAULT NULL NULL,
+ prev_val text DEFAULT NULL NULL,
+ new_val text DEFAULT NULL NULL,
+ trx_id varchar(1024)DEFAULT NULL NULL,
+ action varchar(255) DEFAULT NULL NULL,
+ sess_id varchar(512) DEFAULT NULL NULL,
+ req_id varchar(30) DEFAULT NULL NULL,
+ sess_type varchar(30) DEFAULT NULL NULL,
+ CONSTRAINT x_trx_log_PK_id PRIMARY KEY CLUSTERED(id)
+)
+GO
+create table dbo.x_perm_map(
+ id bigint IDENTITY NOT NULL,
+ create_time datetime DEFAULT NULL NULL,
+ update_time datetime DEFAULT NULL NULL,
+ added_by_id bigint DEFAULT NULL NULL,
+ upd_by_id bigint DEFAULT NULL NULL,
+ perm_group varchar(1024) DEFAULT NULL NULL,
+ res_id bigint DEFAULT NULL NULL,
+ group_id bigint DEFAULT NULL NULL,
+ user_id bigint DEFAULT NULL NULL,
+ perm_for int DEFAULT 0 NOT NULL,
+ perm_type int DEFAULT 0 NOT NULL,
+ is_recursive int DEFAULT 0 NOT NULL,
+ is_wild_card tinyint DEFAULT 1 NOT NULL,
+ grant_revoke tinyint DEFAULT 1 NOT NULL,
+ ip_address text DEFAULT NULL NULL,
+ CONSTRAINT x_perm_map_PK_id PRIMARY KEY CLUSTERED(id)
+)
+GO
+create table dbo.x_audit_map(
+ id bigint IDENTITY NOT NULL,
+ create_time datetime DEFAULT NULL NULL,
+ update_time datetime DEFAULT NULL NULL,
+ added_by_id bigint DEFAULT NULL NULL,
+ upd_by_id bigint DEFAULT NULL NULL,
+ res_id bigint DEFAULT NULL NULL,
+ group_id bigint DEFAULT NULL NULL,
+ user_id bigint DEFAULT NULL NULL,
+ audit_type int DEFAULT 0 NOT NULL,
+ CONSTRAINT x_audit_map_PK_id PRIMARY KEY CLUSTERED(id)
+)
+GO
+CREATE VIEW dbo.vx_trx_log AS select x_trx_log.id AS id,x_trx_log.create_time AS create_time,x_trx_log.update_time AS update_time,x_trx_log.added_by_id AS added_by_id,x_trx_log.upd_by_id AS upd_by_id,x_trx_log.class_type AS class_type,x_trx_log.object_id AS object_id,x_trx_log.parent_object_id AS parent_object_id,x_trx_log.parent_object_class_type AS parent_object_class_type,x_trx_log.attr_name AS attr_name,x_trx_log.parent_object_name AS parent_object_name,x_trx_log.object_name AS object_name,x_trx_log.prev_val AS prev_val,x_trx_log.new_val AS new_val,x_trx_log.trx_id AS trx_id,x_trx_log.action AS action,x_trx_log.sess_id AS sess_id,x_trx_log.req_id AS req_id,x_trx_log.sess_type AS sess_type from x_trx_log where id in(select min(x_trx_log.id) from x_trx_log group by x_trx_log.trx_id)
+GO
+create table dbo.x_service_def(
+ id bigint IDENTITY NOT NULL,
+ guid varchar(1024) DEFAULT NULL NULL,
+ create_time datetime DEFAULT NULL NULL,
+ update_time datetime DEFAULT NULL NULL,
+ added_by_id bigint DEFAULT NULL NULL,
+ upd_by_id bigint DEFAULT NULL NULL,
+ version bigint DEFAULT NULL NULL,
+ name varchar(1024) DEFAULT NULL NULL,
+ impl_class_name varchar(1024) DEFAULT NULL NULL,
+ label varchar(1024) DEFAULT NULL NULL,
+ description varchar(1024) DEFAULT NULL NULL,
+ rb_key_label varchar(1024) DEFAULT NULL NULL,
+ rb_key_description varchar(1024) DEFAULT NULL NULL,
+ is_enabled tinyint DEFAULT 1 NULL,
+ CONSTRAINT x_service_def_PK_id PRIMARY KEY CLUSTERED(id)
+)
+GO
+create table dbo.x_service (
+ id bigint IDENTITY NOT NULL,
+ guid varchar(1024) DEFAULT NULL NULL,
+ create_time datetime DEFAULT NULL NULL,
+ update_time datetime DEFAULT NULL NULL,
+ added_by_id bigint DEFAULT NULL NULL,
+ upd_by_id bigint DEFAULT NULL NULL,
+ version bigint DEFAULT NULL NULL,
+ type bigint DEFAULT NULL NULL,
+ name varchar(512) DEFAULT NULL NULL,
+ policy_version bigint DEFAULT NULL NULL,
+ policy_update_time datetime DEFAULT NULL NULL,
+ description varchar(1024) DEFAULT NULL NULL,
+ is_enabled tinyint DEFAULT 0 NOT NULL,
+ CONSTRAINT x_service_def_PK_id PRIMARY KEY CLUSTERED(id)
+)
+GO
+create table dbo.x_policy (
+ id bigint IDENTITY NOT NULL,
+ guid varchar(1024) DEFAULT NULL NULL,
+ create_time datetime DEFAULT NULL NULL,
+ update_time datetime DEFAULT NULL NULL,
+ added_by_id bigint DEFAULT NULL NULL,
+ upd_by_id bigint DEFAULT NULL NULL,
+ version bigint DEFAULT NULL NULL,
+ service bigint DEFAULT NULL NULL,
+ name varchar(512) DEFAULT NULL NULL,
+ policy_type int DEFAULT 0 NULL,
+ description varchar(1024) DEFAULT NULL NULL,
+ resource_signature varchar(128) DEFAULT NULL NULL,
+ is_enabled tinyint DEFAULT 0 NOT NULL,
+ is_audit_enabled tinyint DEFAULT 0 NOT NULL,
+ CONSTRAINT x_policy_PK_id PRIMARY KEY CLUSTERED(id)
+)
+GO
+create table dbo.x_service_config_def (
+ id bigint IDENTITY NOT NULL,
+ guid varchar(1024) DEFAULT NULL NULL,
+ create_time datetime DEFAULT NULL NULL,
+ update_time datetime DEFAULT NULL NULL,
+ added_by_id bigint DEFAULT NULL NULL,
+ upd_by_id bigint DEFAULT NULL NULL,
+ def_id bigint NOT NULL,
+ item_id bigint NOT NULL,
+ name varchar(1024) DEFAULT NULL NULL,
+ type varchar(1024) DEFAULT NULL NULL,
+ sub_type varchar(1024) DEFAULT NULL NULL,
+ is_mandatory tinyint DEFAULT 0 NOT NULL,
+ default_value varchar(1024) DEFAULT NULL NULL,
+ validation_reg_ex varchar(1024) DEFAULT NULL NULL,
+ validation_message varchar(1024) DEFAULT NULL NULL,
+ ui_hint varchar(1024) DEFAULT NULL NULL,
+ label varchar(1024) DEFAULT NULL NULL,
+ description varchar(1024) DEFAULT NULL NULL,
+ rb_key_label varchar(1024) DEFAULT NULL NULL,
+ rb_key_description varchar(1024) DEFAULT NULL NULL,
+ rb_key_validation_message varchar(1024) DEFAULT NULL NULL,
+ sort_order tinyint DEFAULT 0 NULL,
+ CONSTRAINT x_service_config_def_PK_id PRIMARY KEY CLUSTERED(id)
+)
+GO
+create table dbo.x_resource_def (
+ id bigint IDENTITY NOT NULL,
+ guid varchar(1024) DEFAULT NULL NULL,
+ create_time datetime DEFAULT NULL NULL,
+ update_time datetime DEFAULT NULL NULL,
+ added_by_id bigint DEFAULT NULL NULL,
+ upd_by_id bigint DEFAULT NULL NULL,
+ def_id bigint NOT NULL,
+ item_id bigint NOT NULL,
+ name varchar(1024) DEFAULT NULL NULL,
+ type varchar(1024) DEFAULT NULL NULL,
+ res_level bigint DEFAULT NULL NULL,
+ parent bigint DEFAULT NULL NULL,
+ mandatory tinyint DEFAULT 0 NOT NULL,
+ look_up_supported tinyint DEFAULT 0 NOT NULL,
+ recursive_supported tinyint DEFAULT 0 NOT NULL,
+ excludes_supported tinyint DEFAULT 0 NOT NULL,
+ matcher varchar(1024) DEFAULT NULL NULL,
+ matcher_options varchar(1024) DEFAULT NULL NULL,
+ validation_reg_ex varchar(1024) DEFAULT NULL NULL,
+ validation_message varchar(1024) DEFAULT NULL NULL,
+ ui_hint varchar(1024) DEFAULT NULL NULL,
+ label varchar(1024) DEFAULT NULL NULL,
+ description varchar(1024) DEFAULT NULL NULL,
+ rb_key_label varchar(1024) DEFAULT NULL NULL,
+ rb_key_description varchar(1024) DEFAULT NULL NULL,
+ rb_key_validation_message varchar(1024) DEFAULT NULL NULL,
+ sort_order tinyint DEFAULT 0 NULL,
+ CONSTRAINT x_resource_def_PK_id PRIMARY KEY CLUSTERED(id)
+)
+GO
+create table dbo.x_access_type_def (
+ id bigint IDENTITY NOT NULL,
+ guid varchar(1024) DEFAULT NULL NULL,
+ create_time datetime DEFAULT NULL NULL,
+ update_time datetime DEFAULT NULL NULL,
+ added_by_id bigint DEFAULT NULL NULL,
+ upd_by_id bigint DEFAULT NULL NULL,
+ def_id bigint NOT NULL,
+ item_id bigint NOT NULL,
+ name varchar(1024) DEFAULT NULL NULL,
+ label varchar(1024) DEFAULT NULL NULL,
+ rb_key_label varchar(1024) DEFAULT NULL NULL,
+ sort_order tinyint DEFAULT 0 NULL,
+ CONSTRAINT x_access_type_def_PK_id PRIMARY KEY CLUSTERED(id)
+)
+GO
+create table dbo.x_access_type_def_grants(
+ id bigint IDENTITY NOT NULL,
+ guid varchar(1024) DEFAULT NULL NULL,
+ create_time datetime DEFAULT NULL NULL,
+ update_time datetime DEFAULT NULL NULL,
+ added_by_id bigint DEFAULT NULL NULL,
+ upd_by_id bigint DEFAULT NULL NULL,
+ atd_id bigint NOT NULL,
+ implied_grant varchar(1024) DEFAULT NULL NULL,
+ CONSTRAINT x_access_type_def_grants_PK_id PRIMARY KEY CLUSTERED(id)
+)
+GO
+create table dbo.x_policy_condition_def (
+ id bigint IDENTITY NOT NULL,
+ guid varchar(1024) DEFAULT NULL NULL,
+ create_time datetime DEFAULT NULL NULL,
+ update_time datetime DEFAULT NULL NULL,
+ added_by_id bigint DEFAULT NULL NULL,
+ upd_by_id bigint DEFAULT NULL NULL,
+ def_id bigint NOT NULL,
+ item_id bigint NOT NULL,
+ name varchar(1024) DEFAULT NULL NULL,
+ evaluator varchar(1024) DEFAULT NULL NULL,
+ evaluator_options varchar(1024) DEFAULT NULL NULL,
+ validation_reg_ex varchar(1024) DEFAULT NULL NULL,
+ validation_message varchar(1024) DEFAULT NULL NULL,
+ ui_hint varchar(1024) DEFAULT NULL NULL,
+ label varchar(1024) DEFAULT NULL NULL,
+ description varchar(1024) DEFAULT NULL NULL,
+ rb_key_label varchar(1024) DEFAULT NULL NULL,
+ rb_key_description varchar(1024) DEFAULT NULL NULL,
+ rb_key_validation_message varchar(1024) DEFAULT NULL NULL,
+ sort_order tinyint DEFAULT 0 NULL,
+ CONSTRAINT x_policy_condition_def_grants_PK_id PRIMARY KEY CLUSTERED(id)
+)
+GO
+create table dbo.x_context_enricher_def(
+ id bigint IDENTITY NOT NULL,
+ guid varchar(1024) DEFAULT NULL NULL,
+ create_time datetime DEFAULT NULL NULL,
+ update_time datetime DEFAULT NULL NULL,
+ added_by_id bigint DEFAULT NULL NULL,
+ upd_by_id bigint DEFAULT NULL NULL,
+ def_id bigint NOT NULL,
+ item_id bigint NOT NULL,
+ name varchar(1024) DEFAULT NULL NULL,
+ enricher varchar(1024) DEFAULT NULL NULL,
+ enricher_options varchar(1024) DEFAULT NULL NULL,
+ sort_order tinyint DEFAULT 0 NULL,
+ CONSTRAINT x_context_enricher_def_grants_PK_id PRIMARY KEY CLUSTERED(id)
+)
+GO
+create table dbo.x_enum_def (
+ id bigint IDENTITY NOT NULL,
+ guid varchar(1024) DEFAULT NULL NULL,
+ create_time datetime DEFAULT NULL NULL,
+ update_time datetime DEFAULT NULL NULL,
+ added_by_id bigint DEFAULT NULL NULL,
+ upd_by_id bigint DEFAULT NULL NULL,
+ def_id bigint NOT NULL,
+ item_id bigint NOT NULL,
+ name varchar(1024) DEFAULT NULL NULL,
+ default_index bigint DEFAULT NULL NULL,
+ CONSTRAINT x_enum_def_grants_PK_id PRIMARY KEY CLUSTERED(id)
+)
+GO
+create table dbo.x_enum_element_def (
+ id bigint IDENTITY NOT NULL,
+ guid varchar(1024) DEFAULT NULL NULL,
+ create_time datetime DEFAULT NULL NULL,
+ update_time datetime DEFAULT NULL NULL,
+ added_by_id bigint DEFAULT NULL NULL,
+ upd_by_id bigint DEFAULT NULL NULL,
+ enum_def_id bigint NOT NULL,
+ item_id bigint NOT NULL,
+ name varchar(1024) DEFAULT NULL NULL,
+ label varchar(1024) DEFAULT NULL NULL,
+ rb_key_label varchar(1024) DEFAULT NULL NULL,
+ sort_order tinyint DEFAULT 0 NULL,
+ CONSTRAINT x_enum_element_def_PK_id PRIMARY KEY CLUSTERED(id)
+)
+GO
+create table dbo.x_service_config_map (
+ id bigint IDENTITY NOT NULL,
+ guid varchar(1024) DEFAULT NULL NULL,
+ create_time datetime DEFAULT NULL NULL,
+ update_time datetime DEFAULT NULL NULL,
+ added_by_id bigint DEFAULT NULL NULL,
+ upd_by_id bigint DEFAULT NULL NULL,
+ service bigint NOT NULL,
+ config_key varchar(1024) DEFAULT NULL NULL,
+ config_value varchar(4000) DEFAULT NULL NULL,
+ CONSTRAINT x_service_config_map_PK_id PRIMARY KEY CLUSTERED(id)
+)
+GO
+create table dbo.x_policy_resource (
+ id bigint IDENTITY NOT NULL,
+ guid varchar(1024) DEFAULT NULL NULL,
+ create_time datetime DEFAULT NULL NULL,
+ update_time datetime DEFAULT NULL NULL,
+ added_by_id bigint DEFAULT NULL NULL,
+ upd_by_id bigint DEFAULT NULL NULL,
+ policy_id bigint NOT NULL,
+ res_def_id bigint NOT NULL,
+ is_excludes tinyint DEFAULT 0 NOT NULL,
+ is_recursive tinyint DEFAULT 0 NOT NULL,
+ CONSTRAINT x_policy_resource_PK_id PRIMARY KEY CLUSTERED(id)
+)
+GO
+create table dbo.x_policy_resource_map (
+ id bigint IDENTITY NOT NULL,
+ guid varchar(1024) DEFAULT NULL NULL,
+ create_time datetime DEFAULT NULL NULL,
+ update_time datetime DEFAULT NULL NULL,
+ added_by_id bigint DEFAULT NULL NULL,
+ upd_by_id bigint DEFAULT NULL NULL,
+ resource_id bigint NOT NULL,
+ value varchar(1024) DEFAULT NULL NULL,
+ sort_order tinyint DEFAULT 0 NULL,
+ CONSTRAINT x_policy_resource_map_PK_id PRIMARY KEY CLUSTERED(id)
+)
+GO
+create table dbo.x_policy_item (
+ id bigint IDENTITY NOT NULL,
+ guid varchar(1024) DEFAULT NULL NULL,
+ create_time datetime DEFAULT NULL NULL,
+ update_time datetime DEFAULT NULL NULL,
+ added_by_id bigint DEFAULT NULL NULL,
+ upd_by_id bigint DEFAULT NULL NULL,
+ policy_id bigint NOT NULL,
+ delegate_admin tinyint DEFAULT 0 NOT NULL,
+ sort_order tinyint DEFAULT 0 NULL,
+ CONSTRAINT x_policy_item_PK_id PRIMARY KEY CLUSTERED(id)
+)
+GO
+create table dbo.x_policy_item_access (
+ id bigint IDENTITY NOT NULL,
+ guid varchar(1024) DEFAULT NULL NULL,
+ create_time datetime DEFAULT NULL NULL,
+ update_time datetime DEFAULT NULL NULL,
+ added_by_id bigint DEFAULT NULL NULL,
+ upd_by_id bigint DEFAULT NULL NULL,
+ policy_item_id bigint NOT NULL,
+ type bigint NOT NULL,
+ is_allowed tinyint DEFAULT 0 NOT NULL,
+ sort_order tinyint DEFAULT 0 NULL,
+ CONSTRAINT x_policy_item_access_PK_id PRIMARY KEY CLUSTERED(id)
+)
+GO
+create table dbo.x_policy_item_condition (
+ id bigint IDENTITY NOT NULL,
+ guid varchar(1024) DEFAULT NULL NULL,
+ create_time datetime DEFAULT NULL NULL,
+ update_time datetime DEFAULT NULL NULL,
+ added_by_id bigint DEFAULT NULL NULL,
+ upd_by_id bigint DEFAULT NULL NULL,
+ policy_item_id bigint NOT NULL,
+ type bigint NOT NULL,
+ value varchar(1024) DEFAULT NULL NULL,
+ sort_order tinyint DEFAULT 0 NULL,
+ CONSTRAINT x_policy_item_condition_PK_id PRIMARY KEY CLUSTERED(id)
+)
+GO
+create table dbo.x_policy_item_user_perm (
+ id bigint IDENTITY NOT NULL,
+ guid varchar(1024) DEFAULT NULL NULL,
+ create_time datetime DEFAULT NULL NULL,
+ update_time datetime DEFAULT NULL NULL,
+ added_by_id bigint DEFAULT NULL NULL,
+ upd_by_id bigint DEFAULT NULL NULL,
+ policy_item_id bigint NOT NULL,
+ user_id bigint DEFAULT NULL NULL,
+ sort_order tinyint DEFAULT 0 NULL,
+ CONSTRAINT x_policy_item_user_perm_PK_id PRIMARY KEY CLUSTERED(id)
+)
+GO
+create table dbo.x_policy_item_group_perm (
+ id bigint IDENTITY NOT NULL,
+ guid varchar(1024) DEFAULT NULL NULL,
+ create_time datetime DEFAULT NULL NULL,
+ update_time datetime DEFAULT NULL NULL,
+ added_by_id bigint DEFAULT NULL NULL,
+ upd_by_id bigint DEFAULT NULL NULL,
+ policy_item_id bigint NOT NULL,
+ group_id bigint DEFAULT NULL NULL,
+ sort_order tinyint DEFAULT 0 NULL,
+ CONSTRAINT x_policy_item_group_perm_PK_id PRIMARY KEY CLUSTERED(id)
+)
+GO
+create table dbo.x_data_hist (
+ id bigint IDENTITY NOT NULL,
+ create_time datetime DEFAULT NULL NULL,
+ update_time datetime DEFAULT NULL NULL,
+ obj_guid varchar(1024) NOT NULL,
+ obj_class_type int NOT NULL,
+ obj_id bigint NOT NULL,
+ obj_name varchar(1024) NOT NULL,
+ version bigint DEFAULT NULL NULL,
+ action varchar(512) NOT NULL,
+ from_time datetime NOT NULL,
+ to_time datetime DEFAULT NULL NULL,
+ content text NOT NULL,
+ CONSTRAINT x_data_hist_PK_id PRIMARY KEY CLUSTERED(id)
+)
+GO
+create table dbo.x_modules_master (
+ id bigint IDENTITY NOT NULL,
+ create_time datetime DEFAULT NULL NULL,
+ update_time datetime DEFAULT NULL NULL,
+ added_by_id bigint DEFAULT NULL NULL,
+ upd_by_id bigint DEFAULT NULL NULL,
+ module varchar(1024)NOT NULL,
+ url varchar(1024) DEFAULT NULL NULL,
+ CONSTRAINT x_modules_master_PK_id PRIMARY KEY CLUSTERED(id)
+)
+GO
+create table dbo.x_user_module_perm (
+ id bigint IDENTITY NOT NULL,
+ user_id bigint DEFAULT NULL NULL,
+ module_id bigint DEFAULT NULL NULL,
+ create_time datetime DEFAULT NULL NULL,
+ update_time datetime DEFAULT NULL NULL,
+ added_by_id bigint DEFAULT NULL NULL,
+ upd_by_id bigint DEFAULT NULL NULL,
+ is_allowed int DEFAULT 1 NOT NULL,
+ CONSTRAINT x_user_module_perm_PK_id PRIMARY KEY CLUSTERED(id)
+)
+GO
+create table dbo.x_group_module_perm (
+ id bigint IDENTITY NOT NULL,
+ group_id bigint DEFAULT NULL NULL,
+ module_id bigint DEFAULT NULL NULL,
+ create_time datetime DEFAULT NULL NULL,
+ update_time datetime DEFAULT NULL NULL,
+ added_by_id bigint DEFAULT NULL NULL,
+ upd_by_id bigint DEFAULT NULL NULL,
+ is_allowed int DEFAULT 1 NOT NULL,
+ CONSTRAINT x_group_module_perm_PK_id PRIMARY KEY CLUSTERED(id)
+)
+ALTER TABLE dbo.x_asset ADD CONSTRAINT x_asset_FK_added_by_id FOREIGN KEY(added_by_id) REFERENCES dbo.x_portal_user(id)
+GO
+ALTER TABLE dbo.x_asset ADD CONSTRAINT x_asset_FK_upd_by_id FOREIGN KEY(upd_by_id) REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_audit_map ADD CONSTRAINT x_audit_map_FK_added_by_id FOREIGN KEY(added_by_id) REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_audit_map ADD CONSTRAINT x_audit_map_FK_group_id FOREIGN KEY(group_id) REFERENCES dbo.x_group (id)
+GO
+ALTER TABLE dbo.x_audit_map ADD CONSTRAINT x_audit_map_FK_res_id FOREIGN KEY(res_id) REFERENCES dbo.x_resource (id)
+GO
+ALTER TABLE dbo.x_audit_map ADD CONSTRAINT x_audit_map_FK_upd_by_id FOREIGN KEY(upd_by_id) REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_audit_map ADD CONSTRAINT x_audit_map_FK_user_id FOREIGN KEY(user_id) REFERENCES dbo.x_user (id)
+GO
+ALTER TABLE dbo.x_auth_sess ADD CONSTRAINT x_auth_sess_FK_added_by_id FOREIGN KEY(added_by_id) REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_auth_sess ADD CONSTRAINT x_auth_sess_FK_upd_by_id FOREIGN KEY(upd_by_id) REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_auth_sess ADD CONSTRAINT x_auth_sess_FK_user_id FOREIGN KEY(user_id) REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_cred_store ADD CONSTRAINT x_cred_store_FK_added_by_id FOREIGN KEY(added_by_id) REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_cred_store ADD CONSTRAINT x_cred_store_FK_upd_by_id FOREIGN KEY(upd_by_id) REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_db_base ADD CONSTRAINT x_db_base_FK_added_by_id FOREIGN KEY(added_by_id) REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_db_base ADD CONSTRAINT x_db_base_FK_upd_by_id FOREIGN KEY(upd_by_id) REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_group ADD CONSTRAINT x_group_FK_added_by_id FOREIGN KEY(added_by_id) REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_group ADD CONSTRAINT x_group_FK_cred_store_id FOREIGN KEY(cred_store_id) REFERENCES dbo.x_cred_store (id)
+GO
+ALTER TABLE dbo.x_group ADD CONSTRAINT x_group_FK_upd_by_id FOREIGN KEY(upd_by_id) REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_group_groups ADD CONSTRAINT x_group_groups_FK_added_by_id FOREIGN KEY(added_by_id) REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_group_groups ADD CONSTRAINT x_group_groups_FK_group_id FOREIGN KEY(group_id) REFERENCES dbo.x_group (id)
+GO
+ALTER TABLE dbo.x_group_groups ADD CONSTRAINT x_group_groups_FK_p_group_id FOREIGN KEY(p_group_id) REFERENCES dbo.x_group (id)
+GO
+ALTER TABLE dbo.x_group_users ADD CONSTRAINT x_group_users_FK_added_by_id FOREIGN KEY(added_by_id) REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_group_users ADD CONSTRAINT x_group_users_FK_p_group_id FOREIGN KEY(p_group_id) REFERENCES dbo.x_group (id)
+GO
+ALTER TABLE dbo.x_group_users ADD CONSTRAINT x_group_users_FK_upd_by_id FOREIGN KEY(upd_by_id) REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_group_users ADD CONSTRAINT x_group_users_FK_user_id FOREIGN KEY(user_id) REFERENCES dbo.x_user (id)
+GO
+ALTER TABLE dbo.x_perm_map ADD CONSTRAINT x_perm_map_FK_added_by_id FOREIGN KEY(added_by_id) REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_perm_map ADD CONSTRAINT x_perm_map_FK_group_id FOREIGN KEY(group_id) REFERENCES dbo.x_group (id)
+GO
+ALTER TABLE dbo.x_perm_map ADD CONSTRAINT x_perm_map_FK_res_id FOREIGN KEY(res_id) REFERENCES dbo.x_resource (id)
+GO
+ALTER TABLE dbo.x_perm_map ADD CONSTRAINT x_perm_map_FK_upd_by_id FOREIGN KEY(upd_by_id) REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_perm_map ADD CONSTRAINT x_perm_map_FK_user_id FOREIGN KEY(user_id) REFERENCES dbo.x_user (id)
+GO
+ALTER TABLE dbo.x_policy_export_audit ADD CONSTRAINT x_policy_export_audit_FK_added_by_id FOREIGN KEY(added_by_id) REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_policy_export_audit ADD CONSTRAINT x_policy_export_audit_FK_upd_by_id FOREIGN KEY(upd_by_id) REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_portal_user ADD CONSTRAINT x_portal_user_FK_added_by_id FOREIGN KEY(added_by_id) REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_portal_user ADD CONSTRAINT x_portal_user_FK_upd_by_id FOREIGN KEY(upd_by_id) REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_portal_user_role ADD CONSTRAINT x_portal_user_role_FK_added_by_id FOREIGN KEY(added_by_id) REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_portal_user_role ADD CONSTRAINT x_portal_user_role_FK_upd_by_id FOREIGN KEY(upd_by_id) REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_portal_user_role ADD CONSTRAINT x_portal_user_role_FK_user_id FOREIGN KEY(user_id) REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_resource ADD CONSTRAINT x_resource_FK_added_by_id FOREIGN KEY(added_by_id) REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_resource ADD CONSTRAINT x_resource_FK_asset_id FOREIGN KEY(asset_id) REFERENCES dbo.x_asset (id)
+GO
+ALTER TABLE dbo.x_resource ADD CONSTRAINT x_resource_FK_parent_id FOREIGN KEY(parent_id) REFERENCES dbo.x_resource (id)
+GO
+ALTER TABLE dbo.x_resource ADD CONSTRAINT x_resource_FK_upd_by_id FOREIGN KEY(upd_by_id) REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_trx_log ADD CONSTRAINT x_trx_log_FK_added_by_id FOREIGN KEY(added_by_id) REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_trx_log ADD CONSTRAINT x_trx_log_FK_upd_by_id FOREIGN KEY(upd_by_id) REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_user ADD CONSTRAINT x_user_FK_added_by_id FOREIGN KEY(added_by_id) REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_user ADD CONSTRAINT x_user_FK_cred_store_id FOREIGN KEY(cred_store_id) REFERENCES dbo.x_cred_store (id)
+GO
+ALTER TABLE dbo.x_user ADD CONSTRAINT x_user_FK_upd_by_id FOREIGN KEY(upd_by_id) REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_service_def ADD CONSTRAINT x_service_def_FK_added_by_id FOREIGN KEY(added_by_id)REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_service_def ADD CONSTRAINT x_service_def_FK_upd_by_id FOREIGN KEY(upd_by_id)REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_service ADD CONSTRAINT x_service_FK_added_by_id FOREIGN KEY(added_by_id)REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_service ADD CONSTRAINT x_service_FK_upd_by_id FOREIGN KEY(upd_by_id)REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_service ADD CONSTRAINT x_service_FK_type FOREIGN KEY(type)REFERENCES dbo.x_service_def (id)
+GO
+ALTER TABLE dbo.x_policy ADD CONSTRAINT x_policy_FK_added_by_id FOREIGN KEY(added_by_id)REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_policy ADD CONSTRAINT x_policy_FK_upd_by_id FOREIGN KEY(upd_by_id)REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_policy ADD CONSTRAINT x_policy_FK_service FOREIGN KEY(service)REFERENCES dbo.x_service (id)
+GO
+ALTER TABLE dbo.x_service_config_def ADD CONSTRAINT x_service_config_def_FK_defid FOREIGN KEY(def_id)REFERENCES dbo.x_service_def (id)
+GO
+ALTER TABLE dbo.x_service_config_def ADD CONSTRAINT x_service_conf_def_FK_added_by FOREIGN KEY(added_by_id)REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_service_config_def ADD CONSTRAINT x_service_conf_def_FK_upd_by FOREIGN KEY(upd_by_id)REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_resource_def ADD CONSTRAINT x_resource_def_FK_parent FOREIGN KEY(parent)REFERENCES dbo.x_resource_def (id)
+GO
+ALTER TABLE dbo.x_resource_def ADD CONSTRAINT x_resource_def_FK_defid FOREIGN KEY(def_id)REFERENCES dbo.x_service_def (id)
+GO
+ALTER TABLE dbo.x_resource_def ADD CONSTRAINT x_resource_def_FK_added_by FOREIGN KEY(added_by_id)REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_resource_def ADD CONSTRAINT x_resource_def_FK_upd_by FOREIGN KEY(upd_by_id)REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_access_type_def ADD CONSTRAINT x_access_type_def_FK_defid FOREIGN KEY(def_id)REFERENCES dbo.x_service_def (id)
+GO
+ALTER TABLE dbo.x_access_type_def ADD CONSTRAINT x_access_type_def_FK_added_by FOREIGN KEY(added_by_id)REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_access_type_def ADD CONSTRAINT x_access_type_def_FK_upd_by FOREIGN KEY(upd_by_id)REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_access_type_def_grants ADD CONSTRAINT x_atd_grants_FK_atdid FOREIGN KEY(atd_id)REFERENCES dbo.x_access_type_def (id)
+GO
+ALTER TABLE dbo.x_access_type_def_grants ADD CONSTRAINT x_access_type_def_grants_FK_added_by FOREIGN KEY(added_by_id)REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_access_type_def_grants ADD CONSTRAINT x_access_type_def_grants_FK_upd_by FOREIGN KEY(upd_by_id)REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_policy_condition_def ADD CONSTRAINT x_policy_condition_def_FK_defid FOREIGN KEY(def_id)REFERENCES dbo.x_service_def (id)
+GO
+ALTER TABLE dbo.x_policy_condition_def ADD CONSTRAINT x_policy_condition_def_FK_added_by FOREIGN KEY(added_by_id)REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_policy_condition_def ADD CONSTRAINT x_policy_condition_def_FK_upd_by FOREIGN KEY(upd_by_id)REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_context_enricher_def ADD CONSTRAINT x_context_enricher_def_FK_defid FOREIGN KEY(def_id)REFERENCES dbo.x_service_def (id)
+GO
+ALTER TABLE dbo.x_context_enricher_def ADD CONSTRAINT x_context_enricher_def_FK_added_by_id FOREIGN KEY(added_by_id)REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_context_enricher_def ADD CONSTRAINT x_context_enricher_def_FK_upd_by_id FOREIGN KEY(upd_by_id)REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_enum_def ADD CONSTRAINT x_enum_def_FK_defid FOREIGN KEY(def_id)REFERENCES dbo.x_service_def (id)
+GO
+ALTER TABLE dbo.x_enum_element_def ADD CONSTRAINT x_enum_element_def_FK_defid FOREIGN KEY(enum_def_id)REFERENCES dbo.x_enum_def (id)
+GO
+ALTER TABLE dbo.x_enum_def ADD CONSTRAINT x_enum_def_FK_added_by FOREIGN KEY(added_by_id)REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_enum_def ADD CONSTRAINT x_enum_def_FK_upd_by FOREIGN KEY(upd_by_id)REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_service_config_map ADD CONSTRAINT x_service_config_map_FK_ FOREIGN KEY(service)REFERENCES dbo.x_service (id)
+GO
+ALTER TABLE dbo.x_service_config_map ADD CONSTRAINT x_service_config_map_FK_added_by FOREIGN KEY(added_by_id)REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_service_config_map ADD CONSTRAINT x_service_config_map_FK_upd_by FOREIGN KEY(upd_by_id)REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_policy_resource ADD CONSTRAINT x_policy_resource_FK_policy_id FOREIGN KEY(policy_id)REFERENCES dbo.x_policy (id)
+GO
+ALTER TABLE dbo.x_policy_resource ADD CONSTRAINT x_policy_resource_FK_res_def_id FOREIGN KEY(res_def_id)REFERENCES dbo.x_resource_def (id)
+GO
+ALTER TABLE dbo.x_policy_resource ADD CONSTRAINT x_policy_resource_FK_added_by FOREIGN KEY(added_by_id)REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_policy_resource ADD CONSTRAINT x_policy_resource_FK_upd_by FOREIGN KEY(upd_by_id)REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_policy_resource_map ADD CONSTRAINT x_policy_resource_map_FK_resource_id FOREIGN KEY(resource_id)REFERENCES dbo.x_policy_resource (id)
+GO
+ALTER TABLE dbo.x_policy_resource_map ADD CONSTRAINT x_policy_resource_map_FK_added_by FOREIGN KEY(added_by_id)REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_policy_resource_map ADD CONSTRAINT x_policy_resource_map_FK_upd_by FOREIGN KEY(upd_by_id)REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_policy_item ADD CONSTRAINT x_policy_item_FK_policy_id FOREIGN KEY(policy_id)REFERENCES dbo.x_policy (id)
+GO
+ALTER TABLE dbo.x_policy_item ADD CONSTRAINT x_policy_item_FK_added_by FOREIGN KEY(added_by_id)REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_policy_item ADD CONSTRAINT x_policy_item_FK_upd_by FOREIGN KEY(upd_by_id)REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_policy_item_access ADD CONSTRAINT x_policy_item_access_FK_pi_id FOREIGN KEY(policy_item_id)REFERENCES dbo.x_policy_item (id)
+GO
+ALTER TABLE dbo.x_policy_item_access ADD CONSTRAINT x_policy_item_access_FK_atd_id FOREIGN KEY(type)REFERENCES dbo.x_access_type_def (id)
+GO
+ALTER TABLE dbo.x_policy_item_access ADD CONSTRAINT x_policy_item_access_FK_added_by FOREIGN KEY(added_by_id)REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_policy_item_access ADD CONSTRAINT x_policy_item_access_FK_upd_by FOREIGN KEY(upd_by_id)REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_policy_item_condition ADD CONSTRAINT x_policy_item_condition_FK_pi_id FOREIGN KEY(policy_item_id)REFERENCES dbo.x_policy_item (id)
+GO
+ALTER TABLE dbo.x_policy_item_condition ADD CONSTRAINT x_policy_item_condition_FK_pcd_id FOREIGN KEY(type)REFERENCES dbo.x_policy_condition_def (id)
+GO
+ALTER TABLE dbo.x_policy_item_condition ADD CONSTRAINT x_policy_item_condition_FK_added_by FOREIGN KEY(added_by_id)REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_policy_item_condition ADD CONSTRAINT x_policy_item_condition_FK_upd_by FOREIGN KEY(upd_by_id)REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_policy_item_user_perm ADD CONSTRAINT x_policy_item_user_perm_FK_pi_id FOREIGN KEY(policy_item_id)REFERENCES dbo.x_policy_item (id)
+GO
+ALTER TABLE dbo.x_policy_item_user_perm ADD CONSTRAINT x_policy_item_user_perm_FK_user_id FOREIGN KEY(user_id)REFERENCES dbo.x_user (id)
+GO
+ALTER TABLE dbo.x_policy_item_user_perm ADD CONSTRAINT x_policy_item_user_perm_FK_added_by FOREIGN KEY(added_by_id)REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_policy_item_user_perm ADD CONSTRAINT x_policy_item_user_perm_FK_upd_by FOREIGN KEY(upd_by_id)REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_policy_item_group_perm ADD CONSTRAINT x_policy_item_group_perm_FK_pi_id FOREIGN KEY(policy_item_id)REFERENCES dbo.x_policy_item (id)
+GO
+ALTER TABLE dbo.x_policy_item_group_perm ADD CONSTRAINT x_policy_item_group_perm_FK_group_id FOREIGN KEY(group_id)REFERENCES dbo.x_group (id)
+GO
+ALTER TABLE dbo.x_policy_item_group_perm ADD CONSTRAINT x_policy_item_group_perm_FK_added_by FOREIGN KEY(added_by_id)REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_policy_item_group_perm ADD CONSTRAINT x_policy_item_group_perm_FK_upd_by FOREIGN KEY(upd_by_id)REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_user_module_perm ADD CONSTRAINT x_user_module_perm_FK_moduleid FOREIGN KEY(module_id) REFERENCES dbo.x_modules_master(id)
+GO
+ALTER TABLE dbo.x_user_module_perm ADD CONSTRAINT x_user_module_perm_FK_userid FOREIGN KEY(user_id) REFERENCES dbo.x_portal_user(id)
+GO
+ALTER TABLE dbo.x_group_module_perm ADD CONSTRAINT x_grp_module_perm_FK_module_id FOREIGN KEY(module_id) REFERENCES dbo.x_modules_master(id)
+GO
+ALTER TABLE dbo.x_group_module_perm ADD CONSTRAINT x_grp_module_perm_FK_group_id FOREIGN KEY(group_id) REFERENCES dbo.x_group(id)
+GO
+CREATE NONCLUSTERED INDEX x_asset_cr_time ON dbo.x_asset(create_time ASC)
+GO
+CREATE NONCLUSTERED INDEX x_asset_FK_added_by_id ON dbo.x_asset(added_by_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_asset_FK_upd_by_id ON dbo.x_asset(upd_by_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_asset_up_time ON dbo.x_asset(update_time ASC)
+GO
+CREATE NONCLUSTERED INDEX x_audit_map_cr_time ON dbo.x_audit_map(create_time ASC)
+GO
+CREATE NONCLUSTERED INDEX x_audit_map_FK_added_by_id ON dbo.x_audit_map(added_by_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_audit_map_FK_group_id ON dbo.x_audit_map(group_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_audit_map_FK_res_id ON dbo.x_audit_map(res_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_audit_map_FK_upd_by_id ON dbo.x_audit_map(upd_by_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_audit_map_FK_user_id ON dbo.x_audit_map(user_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_audit_map_up_time ON dbo.x_audit_map(update_time ASC)
+GO
+CREATE NONCLUSTERED INDEX x_auth_sess_cr_time ON dbo.x_auth_sess(create_time ASC)
+GO
+CREATE NONCLUSTERED INDEX x_auth_sess_FK_added_by_id ON dbo.x_auth_sess(added_by_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_auth_sess_FK_upd_by_id ON dbo.x_auth_sess(upd_by_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_auth_sess_FK_user_id ON dbo.x_auth_sess(user_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_auth_sess_up_time ON dbo.x_auth_sess(update_time ASC)
+GO
+CREATE NONCLUSTERED INDEX x_cred_store_cr_time ON dbo.x_cred_store(create_time ASC)
+GO
+CREATE NONCLUSTERED INDEX x_cred_store_FK_added_by_id ON dbo.x_cred_store(added_by_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_cred_store_FK_upd_by_id ON dbo.x_cred_store(upd_by_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_cred_store_up_time ON dbo.x_cred_store(update_time ASC)
+GO
+CREATE NONCLUSTERED INDEX x_db_base_cr_time ON dbo.x_db_base(create_time ASC)
+GO
+CREATE NONCLUSTERED INDEX x_db_base_FK_added_by_id ON dbo.x_db_base(added_by_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_db_base_FK_upd_by_id ON dbo.x_db_base(upd_by_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_db_base_up_time ON dbo.x_db_base(update_time ASC)
+GO
+CREATE NONCLUSTERED INDEX x_group_cr_time ON dbo.x_group(create_time ASC)
+GO
+CREATE NONCLUSTERED INDEX x_group_FK_added_by_id ON dbo.x_group(added_by_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_group_FK_cred_store_id ON dbo.x_group(cred_store_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_group_FK_upd_by_id ON dbo.x_group(upd_by_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_group_groups_cr_time ON dbo.x_group_groups(create_time ASC)
+GO
+CREATE NONCLUSTERED INDEX x_group_groups_FK_added_by_id ON dbo.x_group_groups(added_by_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_group_groups_FK_group_id ON dbo.x_group_groups(group_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_group_groups_FK_p_group_id ON dbo.x_group_groups(p_group_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_group_groups_FK_upd_by_id ON dbo.x_group_groups(upd_by_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_group_groups_up_time ON dbo.x_group_groups(update_time ASC)
+GO
+CREATE NONCLUSTERED INDEX x_group_up_time ON dbo.x_group(update_time ASC)
+GO
+CREATE NONCLUSTERED INDEX x_group_users_cr_time ON dbo.x_group_users(create_time ASC)
+GO
+CREATE NONCLUSTERED INDEX x_group_users_FK_added_by_id ON dbo.x_group_users(added_by_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_group_users_FK_p_group_id ON dbo.x_group_users(p_group_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_group_users_FK_upd_by_id ON dbo.x_group_users(upd_by_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_group_users_FK_user_id ON dbo.x_group_users(user_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_group_users_up_time ON dbo.x_group_users(update_time ASC)
+GO
+CREATE NONCLUSTERED INDEX x_perm_map_cr_time ON dbo.x_perm_map(create_time ASC)
+GO
+CREATE NONCLUSTERED INDEX x_perm_map_FK_added_by_id ON dbo.x_perm_map(added_by_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_perm_map_FK_group_id ON dbo.x_perm_map(group_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_perm_map_FK_res_id ON dbo.x_perm_map(res_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_perm_map_FK_upd_by_id ON dbo.x_perm_map(upd_by_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_perm_map_FK_user_id ON dbo.x_perm_map(user_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_perm_map_up_time ON dbo.x_perm_map(update_time ASC)
+GO
+CREATE NONCLUSTERED INDEX x_policy_export_audit_cr_time ON dbo.x_policy_export_audit(create_time ASC)
+GO
+CREATE NONCLUSTERED INDEX x_policy_export_audit_FK_added_by_id ON dbo.x_policy_export_audit(added_by_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_policy_export_audit_FK_upd_by_id ON dbo.x_policy_export_audit(upd_by_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_policy_export_audit_up_time ON dbo.x_policy_export_audit(update_time ASC)
+GO
+CREATE NONCLUSTERED INDEX x_portal_user_cr_time ON dbo.x_portal_user(create_time ASC)
+GO
+CREATE NONCLUSTERED INDEX x_portal_user_email ON dbo.x_portal_user(email ASC)
+GO
+CREATE NONCLUSTERED INDEX x_portal_user_FK_added_by_id ON dbo.x_portal_user(added_by_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_portal_user_FK_upd_by_id ON dbo.x_portal_user(upd_by_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_portal_user_name ON dbo.x_portal_user(first_name ASC)
+GO
+CREATE NONCLUSTERED INDEX x_portal_user_role_cr_time ON dbo.x_portal_user_role(create_time ASC)
+GO
+CREATE NONCLUSTERED INDEX x_portal_user_role_FK_added_by_id ON dbo.x_portal_user_role(added_by_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_portal_user_role_FK_upd_by_id ON dbo.x_portal_user_role(upd_by_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_portal_user_role_FK_user_id ON dbo.x_portal_user_role(user_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_portal_user_role_up_time ON dbo.x_portal_user_role(update_time ASC)
+GO
+CREATE NONCLUSTERED INDEX x_portal_user_up_time ON dbo.x_portal_user(update_time ASC)
+GO
+CREATE NONCLUSTERED INDEX x_resource_cr_time ON dbo.x_resource(create_time ASC)
+GO
+CREATE NONCLUSTERED INDEX x_resource_FK_added_by_id ON dbo.x_resource(added_by_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_resource_FK_asset_id ON dbo.x_resource(asset_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_resource_FK_parent_id ON dbo.x_resource(parent_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_resource_FK_upd_by_id ON dbo.x_resource(upd_by_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_resource_up_time ON dbo.x_resource(update_time ASC)
+GO
+CREATE NONCLUSTERED INDEX x_trx_log_cr_time ON dbo.x_trx_log(create_time ASC)
+GO
+CREATE NONCLUSTERED INDEX x_trx_log_FK_added_by_id ON dbo.x_trx_log(added_by_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_trx_log_FK_upd_by_id ON dbo.x_trx_log(upd_by_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_trx_log_up_time ON dbo.x_trx_log(update_time ASC)
+GO
+CREATE NONCLUSTERED INDEX x_user_cr_time ON dbo.x_user(create_time ASC)
+GO
+CREATE NONCLUSTERED INDEX x_user_FK_added_by_id ON dbo.x_user(added_by_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_user_FK_cred_store_id ON dbo.x_user(cred_store_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_user_FK_upd_by_id ON dbo.x_user(upd_by_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_user_up_time ON dbo.x_user(update_time ASC)
+GO
+CREATE NONCLUSTERED INDEX xa_access_audit_cr_time ON dbo.xa_access_audit(create_time ASC)
+GO
+CREATE NONCLUSTERED INDEX xa_access_audit_event_time ON dbo.xa_access_audit(event_time ASC)
+GO
+CREATE NONCLUSTERED INDEX xa_access_audit_added_by_id ON dbo.xa_access_audit(added_by_id ASC)
+GO
+CREATE NONCLUSTERED INDEX xa_access_audit_upd_by_id ON dbo.xa_access_audit(upd_by_id ASC)
+GO
+CREATE NONCLUSTERED INDEX xa_access_audit_up_time ON dbo.xa_access_audit(update_time ASC)
+GO
+CREATE NONCLUSTERED INDEX x_service_def_added_by_id ON dbo.x_service_def(added_by_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_service_def_upd_by_id ON dbo.x_service_def(upd_by_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_service_def_cr_time ON dbo.x_service_def(create_time ASC)
+GO
+CREATE NONCLUSTERED INDEX x_service_def_up_time ON dbo.x_service_def(update_time ASC)
+GO
+CREATE NONCLUSTERED INDEX x_service_added_by_id ON dbo.x_service(added_by_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_service_upd_by_id ON dbo.x_service(upd_by_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_service_cr_time ON dbo.x_service(create_time ASC)
+GO
+CREATE NONCLUSTERED INDEX x_service_up_time ON dbo.x_service(update_time ASC)
+GO
+CREATE NONCLUSTERED INDEX x_service_type ON dbo.x_service(type ASC)
+GO
+CREATE NONCLUSTERED INDEX x_policy_added_by_id ON dbo.x_policy(added_by_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_policy_upd_by_id ON dbo.x_policy(upd_by_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_policy_cr_time ON dbo.x_policy(create_time ASC)
+GO
+CREATE NONCLUSTERED INDEX x_policy_up_time ON dbo.x_policy(update_time ASC)
+GO
+CREATE NONCLUSTERED INDEX x_policy_service ON dbo.x_policy(service ASC)
+GO
+CREATE NONCLUSTERED INDEX x_policy_resource_signature ON dbo.x_policy(resource_signature ASC)
+GO
+CREATE NONCLUSTERED INDEX x_resource_def_parent ON dbo.x_resource_def(parent ASC)
+GO
+CREATE NONCLUSTERED INDEX x_usr_module_perm_idx_moduleid ON dbo.x_user_module_perm(module_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_usr_module_perm_idx_userid ON dbo.x_user_module_perm(user_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_grp_module_perm_idx_groupid ON dbo.x_group_module_perm(group_id ASC)
+GO
+CREATE NONCLUSTERED INDEX x_grp_module_perm_idx_moduleid ON dbo.x_group_module_perm(module_id ASC)
+GO
+insert into x_portal_user (create_time,update_time,first_name,last_name,pub_scr_name,login_id,password,email,status) values (GETDATE(),GETDATE(),'Admin','','Admin','admin','ceb4f32325eda6142bd65215f4c0f371','',1)
+GO
+insert into x_portal_user_role (create_time,update_time,user_id,user_role,status) values (GETDATE(),GETDATE(),1,'ROLE_SYS_ADMIN',1)
+GO
+insert into x_user (create_time,update_time,user_name,status,descr) values (GETDATE(),GETDATE(),'admin',0,'Administrator')
+GO
+insert into x_group (added_by_id,create_time,descr,group_type,group_name,status,update_time,upd_by_id) values (1,GETDATE(),'public group',0,'public',0,GETDATE(),1)
+GO
+INSERT INTO x_modules_master(create_time,update_time,added_by_id,upd_by_id,module,url) VALUES(GETDATE(),GETDATE(),1,1,'Resource Based Policies','')
+GO
+INSERT INTO x_modules_master(create_time,update_time,added_by_id,upd_by_id,module,url) VALUES(GETDATE(),GETDATE(),1,1,'Users/Groups','')
+GO
+INSERT INTO x_modules_master(create_time,update_time,added_by_id,upd_by_id,module,url) VALUES(GETDATE(),GETDATE(),1,1,'Reports','')
+GO
+INSERT INTO x_modules_master(create_time,update_time,added_by_id,upd_by_id,module,url) VALUES(GETDATE(),GETDATE(),1,1,'Audit','')
+GO
+INSERT INTO x_modules_master(create_time,update_time,added_by_id,upd_by_id,module,url) VALUES(GETDATE(),GETDATE(),1,1,'Key Manager','')
+GO
+insert into x_portal_user (create_time,update_time,first_name,last_name,pub_scr_name,login_id,password,email,status) values (GETDATE(),GETDATE(),'rangerusersync','','rangerusersync','rangerusersync','70b8374d3dfe0325aaa5002a688c7e3b','rangerusersync',1)
+GO
+insert into x_portal_user_role (create_time,update_time,user_id,user_role,status) values (GETDATE(),GETDATE(),2,'ROLE_SYS_ADMIN',1)
+GO
+insert into x_user (create_time,update_time,user_name,status,descr) values (GETDATE(),GETDATE(),'rangerusersync',0,'rangerusersync')
+GO
+insert into x_portal_user (create_time,update_time,first_name,last_name,pub_scr_name,login_id,password,email,status) values (GETDATE(),GETDATE(),'keyadmin','','keyadmin','keyadmin','a05f34d2dce2b4688fa82e82a89ba958','keyadmin',1)
+GO
+insert into x_portal_user_role (create_time,update_time,user_id,user_role,status) values (GETDATE(),GETDATE(),3,'ROLE_KEY_ADMIN',1)
+GO
+insert into x_user (create_time,update_time,user_name,status,descr) values (GETDATE(),GETDATE(),'keyadmin',0,'keyadmin')
+GO
+exit
\ No newline at end of file
diff --git a/security-admin/scripts/db_setup.py b/security-admin/scripts/db_setup.py
index 0d6c49b5029..a010e19aa12 100644
--- a/security-admin/scripts/db_setup.py
+++ b/security-admin/scripts/db_setup.py
@@ -1162,6 +1162,260 @@ def execute_java_patches(self, xa_db_host, db_user, db_password, db_name):
log("[E] java patch "+ className +" failed", "error")
sys.exit(1)
+class SqlAnywhereConf(BaseDB):
+ # Constructor
+ def __init__(self, host, SQL_CONNECTOR_JAR, JAVA_BIN):
+ self.host = host
+ self.SQL_CONNECTOR_JAR = SQL_CONNECTOR_JAR
+ self.JAVA_BIN = JAVA_BIN
+
+ def get_jisql_cmd(self, user, password, db_name):
+ path = RANGER_ADMIN_HOME
+ self.JAVA_BIN = self.JAVA_BIN.strip("'")
+ if os_name == "LINUX":
+ jisql_cmd = "%s -cp %s:%s/jisql/lib/* org.apache.util.sql.Jisql -user %s -password %s -driver sapsajdbc4 -cstring jdbc:sqlanywhere:database=%s;host=%s -noheader -trim"%(self.JAVA_BIN, self.SQL_CONNECTOR_JAR, path,user, password,db_name,self.host)
+ elif os_name == "WINDOWS":
+ jisql_cmd = "%s -cp %s;%s\\jisql\\lib\\* org.apache.util.sql.Jisql -user %s -password %s -driver sapsajdbc4 -cstring jdbc:sqlanywhere:database=%s;host=%s -noheader -trim"%(self.JAVA_BIN, self.SQL_CONNECTOR_JAR, path, user, password,db_name,self.host)
+ return jisql_cmd
+
+ def check_connection(self, db_name, db_user, db_password):
+ log("[I] Checking connection", "info")
+ get_cmd = self.get_jisql_cmd(db_user, db_password, db_name)
+ if os_name == "LINUX":
+ query = get_cmd + " -c \; -query \"SELECT 1;\""
+ elif os_name == "WINDOWS":
+ query = get_cmd + " -query \"SELECT 1;\" -c ;"
+ output = check_output(query)
+ if output.strip('1 |'):
+ log("[I] Connection success", "info")
+ return True
+ else:
+ log("[E] Can't establish connection", "error")
+ sys.exit(1)
+
+ def import_db_file(self, db_name, db_user, db_password, file_name):
+ name = basename(file_name)
+ if os.path.isfile(file_name):
+ log("[I] Importing db schema to database " + db_name + " from file: " + name,"info")
+ get_cmd = self.get_jisql_cmd(db_user, db_password, db_name)
+ if os_name == "LINUX":
+ query = get_cmd + " -input %s" %file_name
+ ret = subprocess.call(shlex.split(query))
+ elif os_name == "WINDOWS":
+ query = get_cmd + " -input %s" %file_name
+ ret = subprocess.call(query)
+ if ret == 0:
+ log("[I] "+name + " DB schema imported successfully","info")
+ else:
+ log("[E] "+name + " DB Schema import failed!","error")
+ sys.exit(1)
+
+ def check_table(self, db_name, db_user, db_password, TABLE_NAME):
+ get_cmd = self.get_jisql_cmd(db_user, db_password, db_name)
+ if os_name == "LINUX":
+ query = get_cmd + " -c \; -query \"SELECT name FROM sysobjects where name = '%s' and type='U';\"" %(TABLE_NAME)
+ elif os_name == "WINDOWS":
+ query = get_cmd + " -query \"SELECT name FROM sysobjects where name = '%s' and type='U';\" -c ;" %(TABLE_NAME)
+ output = check_output(query)
+ if output.strip(TABLE_NAME + " |"):
+ log("[I] Table '" + TABLE_NAME + "' already exists in database '" + db_name + "'","info")
+ return True
+ else:
+ log("[I] Table '" + TABLE_NAME + "' does not exist in database '" + db_name + "'","info")
+ return False
+
+ def grant_audit_db_user(self, audit_db_name, db_user, audit_db_user, db_password, audit_db_password,TABLE_NAME):
+ log("[I] Granting permission to audit user '" + audit_db_user + "' on db '" + audit_db_name + "'","info")
+ get_cmd = self.get_jisql_cmd(db_user, db_password,audit_db_name)
+ if os_name == "LINUX":
+ query = get_cmd + " -c \; -query \"GRANT INSERT ON XA_ACCESS_AUDIT to %s;\"" %(audit_db_user)
+ ret = subprocess.call(shlex.split(query))
+ elif os_name == "WINDOWS":
+ query = get_cmd + " -query \"GRANT INSERT ON XA_ACCESS_AUDIT to %s;\" -c ;" %(audit_db_user)
+ ret = subprocess.call(query)
+ if ret != 0 :
+ sys.exit(1)
+ else:
+ log("[I] Permission granted to audit user " + audit_db_user , "info")
+
+ def import_db_patches(self, db_name, db_user, db_password, file_name):
+ name = basename(file_name)
+ if os.path.isfile(file_name):
+ version = name.split('-')[0]
+ log("[I] Executing patch on " + db_name + " from file: " + name,"info")
+ get_cmd = self.get_jisql_cmd(db_user, db_password, db_name)
+ if os_name == "LINUX":
+ query = get_cmd + " -query \"select version from x_db_version_h where version = '%s' and active = 'Y';\"" %(version)
+ elif os_name == "WINDOWS":
+ query = get_cmd + " -query \"select version from x_db_version_h where version = '%s' and active = 'Y';\" -c ;" %(version)
+ output = check_output(query)
+ if output.strip(version + " |"):
+ log("[I] Patch "+ name +" is already applied" ,"info")
+ else:
+ if os_name == "LINUX":
+ query = get_cmd + " -input %s" %file_name
+ ret = subprocess.call(shlex.split(query))
+ elif os_name == "WINDOWS":
+ query = get_cmd + " -input %s" %file_name
+ ret = subprocess.call(query)
+ if ret == 0:
+ log("[I] "+name + " patch applied","info")
+ if os_name == "LINUX":
+ query = get_cmd + " -query \"insert into x_db_version_h (version, inst_at, inst_by, updated_at, updated_by) values ('%s', GETDATE(), '%s@%s', GETDATE(), '%s@%s') ;\" -c \;" %(version,db_user,xa_db_host,db_user,xa_db_host)
+ ret = subprocess.call(shlex.split(query))
+ elif os_name == "WINDOWS":
+ query = get_cmd + " -query \"insert into x_db_version_h (version, inst_at, inst_by, updated_at, updated_by) values ('%s', GETDATE(), '%s@%s', GETDATE(), '%s@%s') ;\" -c ;" %(version,db_user,xa_db_host,db_user,xa_db_host)
+ ret = subprocess.call(query)
+ if ret == 0:
+ log("[I] Patch version updated", "info")
+ else:
+ log("[E] Updating patch version failed", "error")
+ sys.exit(1)
+ else:
+ log("[E] "+name + " import failed!","error")
+ sys.exit(1)
+
+ def import_auditdb_patches(self, xa_sqlObj,xa_db_host, audit_db_host, db_name, audit_db_name, db_user, audit_db_user, db_password, audit_db_password, file_name, TABLE_NAME):
+ log("[I] --------- Checking XA_ACCESS_AUDIT table to apply audit db patches --------- ","info")
+ self.set_options(audit_db_name, db_user, db_password, TABLE_NAME)
+ output = self.check_table(audit_db_name, db_user, db_password, TABLE_NAME)
+ if output == True:
+ name = basename(file_name)
+ if os.path.isfile(file_name):
+ version = name.split('-')[0]
+ log("[I] Executing patch on " + audit_db_name + " from file: " + name,"info")
+ get_cmd1 = xa_sqlObj.get_jisql_cmd(db_user, db_password, db_name)
+ if os_name == "LINUX":
+ query = get_cmd1 + " -query \"select version from x_db_version_h where version = '%s' and active = 'Y';\"" %(version)
+ elif os_name == "WINDOWS":
+ query = get_cmd1 + " -query \"select version from x_db_version_h where version = '%s' and active = 'Y';\" -c ;" %(version)
+ output = check_output(query)
+ if output.strip(version + " |"):
+ log("[I] Patch "+ name +" is already applied" ,"info")
+ else:
+ get_cmd2 = self.get_jisql_cmd(db_user, db_password, audit_db_name)
+ if os_name == "LINUX":
+ query = get_cmd2 + " -input %s" %file_name
+ ret = subprocess.call(shlex.split(query))
+ elif os_name == "WINDOWS":
+ query = get_cmd2 + " -input %s" %file_name
+ ret = subprocess.call(query)
+ if ret == 0:
+ log("[I] "+name + " patch applied","info")
+ if os_name == "LINUX":
+ query = get_cmd1 + " -query \"insert into x_db_version_h (version, inst_at, inst_by, updated_at, updated_by) values ('%s', GETDATE(), '%s@%s', GETDATE(), '%s@%s') ;\" -c \;" %(version,db_user,xa_db_host,db_user,xa_db_host)
+ ret = subprocess.call(shlex.split(query))
+ elif os_name == "WINDOWS":
+ query = get_cmd1 + " -query \"insert into x_db_version_h (version, inst_at, inst_by, updated_at, updated_by) values ('%s', GETDATE(), '%s@%s', GETDATE(), '%s@%s') ;\" -c ;" %(version,db_user,xa_db_host,db_user,xa_db_host)
+ ret = subprocess.call(query)
+ if ret == 0:
+ log("[I] Patch version updated", "info")
+ else:
+ log("[E] Updating patch version failed", "error")
+ sys.exit(1)
+ else:
+ log("[E] "+name + " import failed!","error")
+ sys.exit(1)
+ else:
+ log("[I] Table XA_ACCESS_AUDIT does not exists in " +audit_db_name,"error")
+ sys.exit(1)
+
+ def auditdb_operation(self, xa_db_host, audit_db_host, db_name, audit_db_name,db_user, audit_db_user, db_password, audit_db_password, file_name, TABLE_NAME):
+ log("[I] --------- Check admin user connection --------- ","info")
+ self.check_connection(audit_db_name, db_user, db_password)
+ log("[I] --------- Check audit user connection --------- ","info")
+ self.check_connection(audit_db_name, audit_db_user, audit_db_password)
+ log("[I] --------- Check audit table exists --------- ","info")
+ self.set_options(audit_db_name, db_user, db_password, TABLE_NAME)
+ output = self.check_table(audit_db_name, db_user, db_password, TABLE_NAME)
+ if output == False:
+ self.import_db_file(audit_db_name ,db_user, db_password, file_name)
+ self.grant_audit_db_user( audit_db_name ,db_user, audit_db_user, db_password,audit_db_password,TABLE_NAME)
+
+ def execute_java_patches(self, xa_db_host, db_user, db_password, db_name):
+ my_dict = {}
+ version = ""
+ className = ""
+ app_home = os.path.join(RANGER_ADMIN_HOME,"ews","webapp")
+ ranger_log = os.path.join(RANGER_ADMIN_HOME,"ews","logs")
+ javaFiles = os.path.join(app_home,"WEB-INF","classes","org","apache","ranger","patch")
+
+ if not os.path.exists(javaFiles):
+ log("[I] No java patches to apply!","info")
+ else:
+ files = os.listdir(javaFiles)
+ if files:
+ for filename in files:
+ f = re.match("^Patch.*?.class$",filename)
+ if f:
+ className = re.match("(Patch.*?)_.*.class",filename)
+ className = className.group(1)
+ version = re.match("Patch.*?_(.*).class",filename)
+ version = version.group(1)
+ key3 = int(version.strip("J"))
+ my_dict[key3] = filename
+
+ keylist = my_dict.keys()
+ keylist.sort()
+ for key in keylist:
+ #print "%s: %s" % (key, my_dict[key])
+ version = str(key)
+ className = my_dict[key]
+ className = className.strip(".class")
+ if version != "":
+ get_cmd = self.get_jisql_cmd(db_user, db_password, db_name)
+ if os_name == "LINUX":
+ query = get_cmd + " -query \"select version from x_db_version_h where version = 'J%s' and active = 'Y';\" -c \;" %(version)
+ elif os_name == "WINDOWS":
+ query = get_cmd + " -query \"select version from x_db_version_h where version = 'J%s' and active = 'Y';\" -c ;" %(version)
+ output = check_output(query)
+ if output.strip(version + " |"):
+ log("[I] java patch "+ className +" is already applied" ,"info")
+ else:
+ log ("[I] java patch "+ className +" is being applied..","info")
+ if os_name == "LINUX":
+ path = os.path.join("%s","WEB-INF","classes","conf:%s","WEB-INF","classes","lib","*:%s","WEB-INF",":%s","META-INF",":%s","WEB-INF","lib","*:%s","WEB-INF","classes",":%s","WEB-INF","classes","META-INF:%s" )%(app_home ,app_home ,app_home, app_home, app_home, app_home ,app_home ,self.SQL_CONNECTOR_JAR)
+ elif os_name == "WINDOWS":
+ path = os.path.join("%s","WEB-INF","classes","conf;%s","WEB-INF","classes","lib","*;%s","WEB-INF",";%s","META-INF",";%s","WEB-INF","lib","*;%s","WEB-INF","classes",";%s","WEB-INF","classes","META-INF;%s" )%(app_home ,app_home ,app_home, app_home, app_home, app_home ,app_home ,self.SQL_CONNECTOR_JAR)
+ get_cmd = "%s -Dlogdir=%s -Dlog4j.configuration=db_patch.log4j.xml -cp %s org.apache.ranger.patch.%s"%(self.JAVA_BIN,ranger_log,path,className)
+ if os_name == "LINUX":
+ ret = subprocess.call(shlex.split(get_cmd))
+ elif os_name == "WINDOWS":
+ ret = subprocess.call(get_cmd)
+ if ret == 0:
+ get_cmd = self.get_jisql_cmd(db_user, db_password, db_name)
+ if os_name == "LINUX":
+ query = get_cmd + " -query \"insert into x_db_version_h (version, inst_at, inst_by, updated_at, updated_by) values ('J%s', GETDATE(), '%s@%s', GETDATE(), '%s@%s') ;\" -c \;" %(version,db_user,xa_db_host,db_user,xa_db_host)
+ ret = subprocess.call(shlex.split(query))
+ elif os_name == "WINDOWS":
+ query = get_cmd + " -query \"insert into x_db_version_h (version, inst_at, inst_by, updated_at, updated_by) values ('J%s', GETDATE(), '%s@%s', GETDATE(), '%s@%s') ;\" -c ;" %(version,db_user,xa_db_host,db_user,xa_db_host)
+ ret = subprocess.call(query)
+ if ret == 0:
+ log("[I] java patch "+ className +" applied", "info")
+ else:
+ log("[E] java patch "+ className +" failed", "error")
+ sys.exit(1)
+ else:
+ log("[E] java patch "+ className +" failed", "error")
+ sys.exit(1)
+
+ def set_options(self, db_name, db_user, db_password, TABLE_NAME):
+ get_cmd = self.get_jisql_cmd(db_user, db_password, db_name)
+ if os_name == "LINUX":
+ query = get_cmd + " -c \; -query \"set option public.reserved_keywords='LIMIT';\""
+ elif os_name == "WINDOWS":
+ query = get_cmd + " -query \"set option public.reserved_keywords='LIMIT';\" -c ;"
+ ret = subprocess.call(shlex.split(query))
+ if os_name == "LINUX":
+ query = get_cmd + " -c \; -query \"set option public.max_statement_count=0;\""
+ elif os_name == "WINDOWS":
+ query = get_cmd + " -query \"set option public.max_statement_count=0;\" -c;"
+ ret = subprocess.call(shlex.split(query))
+ if os_name == "LINUX":
+ query = get_cmd + " -c \; -query \"set option public.max_cursor_count=0;\""
+ elif os_name == "WINDOWS":
+ query = get_cmd + " -query \"set option public.max_cursor_count=0;\" -c;"
+ ret = subprocess.call(shlex.split(query))
def main(argv):
populate_global_dict()
@@ -1218,6 +1472,12 @@ def main(argv):
sqlserver_patches = os.path.join('db','sqlserver','patches')
sqlserver_auditdb_patches = os.path.join('db','sqlserver','patches','audit')
+ sqlanywhere_dbversion_catalog = os.path.join('db','sqlanywhere','create_dbversion_catalog.sql')
+ sqlanywhere_core_file = globalDict['sqlanywhere_core_file']
+ sqlanywhere_audit_file = globalDict['sqlanywhere_audit_file']
+ sqlanywhere_patches = os.path.join('db','sqlanywhere','patches')
+ sqlanywhere_auditdb_patches = os.path.join('db','sqlanywhere','patches','audit')
+
db_name = globalDict['db_name']
db_user = globalDict['db_user']
db_password = globalDict['db_password']
@@ -1261,6 +1521,19 @@ def main(argv):
xa_db_core_file = os.path.join(RANGER_ADMIN_HOME , sqlserver_core_file)
xa_patch_file = os.path.join(RANGER_ADMIN_HOME , sqlserver_patches)
audit_patch_file = os.path.join(RANGER_ADMIN_HOME ,sqlserver_auditdb_patches)
+
+ elif XA_DB_FLAVOR == "SQLANYWHERE":
+ if not os_name == "WINDOWS" :
+ if os.environ['LD_LIBRARY_PATH'] == "":
+ log("[E] ---------- LD_LIBRARY_PATH environment property not defined, aborting installation. ----------", "error")
+ sys.exit(1)
+ SQLANYWHERE_CONNECTOR_JAR = globalDict['SQL_CONNECTOR_JAR']
+ xa_sqlObj = SqlAnywhereConf(xa_db_host, SQLANYWHERE_CONNECTOR_JAR, JAVA_BIN)
+ xa_db_version_file = os.path.join(RANGER_ADMIN_HOME ,sqlanywhere_dbversion_catalog)
+ xa_db_core_file = os.path.join(RANGER_ADMIN_HOME , sqlanywhere_core_file)
+ xa_patch_file = os.path.join(RANGER_ADMIN_HOME , sqlanywhere_patches)
+ audit_patch_file = os.path.join(RANGER_ADMIN_HOME ,sqlanywhere_auditdb_patches)
+
else:
log("[E] --------- NO SUCH SUPPORTED DB FLAVOUR!! ---------", "error")
sys.exit(1)
@@ -1284,6 +1557,11 @@ def main(argv):
SQLSERVER_CONNECTOR_JAR = globalDict['SQL_CONNECTOR_JAR']
audit_sqlObj = SqlServerConf(audit_db_host, SQLSERVER_CONNECTOR_JAR, JAVA_BIN)
audit_db_file = os.path.join(RANGER_ADMIN_HOME , sqlserver_audit_file)
+
+ elif AUDIT_DB_FLAVOR == "SQLANYWHERE":
+ SQLANYWHERE_CONNECTOR_JAR = globalDict['SQL_CONNECTOR_JAR']
+ audit_sqlObj = SqlAnywhereConf(audit_db_host, SQLANYWHERE_CONNECTOR_JAR, JAVA_BIN)
+ audit_db_file = os.path.join(RANGER_ADMIN_HOME , sqlanywhere_audit_file)
else:
log("[E] --------- NO SUCH SUPPORTED DB FLAVOUR!! ---------", "error")
sys.exit(1)
diff --git a/security-admin/scripts/dba_script.py b/security-admin/scripts/dba_script.py
index 045990dc625..0d5d573888d 100644
--- a/security-admin/scripts/dba_script.py
+++ b/security-admin/scripts/dba_script.py
@@ -1086,6 +1086,191 @@ def create_auditdb_user(self, xa_db_host, audit_db_host, db_name, audit_db_name,
self.create_user(xa_db_root_user, audit_db_name ,db_user, db_password, xa_db_root_password,dryMode)
self.grant_xa_db_user(audit_db_root_user, audit_db_name, db_user, db_password, audit_db_root_password, is_revoke, dryMode)
+class SqlAnywhereConf(BaseDB):
+ # Constructor
+ def __init__(self, host, SQL_CONNECTOR_JAR, JAVA_BIN):
+ self.host = host
+ self.SQL_CONNECTOR_JAR = SQL_CONNECTOR_JAR
+ self.JAVA_BIN = JAVA_BIN
+
+ def get_jisql_cmd(self, user, password, db_name):
+ path = RANGER_ADMIN_HOME
+ self.JAVA_BIN = self.JAVA_BIN.strip("'")
+ if os_name == "LINUX":
+ jisql_cmd = "%s -cp %s:%s/jisql/lib/* org.apache.util.sql.Jisql -user %s -password %s -driver sapsajdbc4 -cstring jdbc:sqlanywhere:database=%s;host=%s -noheader -trim"%(self.JAVA_BIN, self.SQL_CONNECTOR_JAR, path,user, password,db_name,self.host)
+ elif os_name == "WINDOWS":
+ jisql_cmd = "%s -cp %s;%s\\jisql\\lib\\* org.apache.util.sql.Jisql -user %s -password %s -driver sapsajdbc4 -cstring jdbc:sqlanywhere:database=%s;host=%s -noheader -trim"%(self.JAVA_BIN, self.SQL_CONNECTOR_JAR, path, user, password,db_name,self.host)
+ return jisql_cmd
+
+ def verify_user(self, root_user, db_root_password, db_user,dryMode):
+ if dryMode == False:
+ log("[I] Verifying user " + db_user , "info")
+ get_cmd = self.get_jisql_cmd(root_user, db_root_password, '')
+ if os_name == "LINUX":
+ query = get_cmd + " -c \; -query \"select name from syslogins where name = '%s';\"" %(db_user)
+ elif os_name == "WINDOWS":
+ query = get_cmd + " -query \"select name from syslogins where name = '%s';\" -c ;" %(db_user)
+ output = check_output(query)
+ if output.strip(db_user + " |"):
+ return True
+ else:
+ return False
+
+ def check_connection(self, db_name, db_user, db_password):
+ log("[I] Checking connection", "info")
+ get_cmd = self.get_jisql_cmd(db_user, db_password, db_name)
+ if os_name == "LINUX":
+ query = get_cmd + " -c \; -query \"SELECT 1;\""
+ elif os_name == "WINDOWS":
+ query = get_cmd + " -query \"SELECT 1;\" -c ;"
+ output = check_output(query)
+ if output.strip('1 |'):
+ log("[I] Connection success", "info")
+ return True
+ else:
+ log("[E] Can't establish connection", "error")
+ sys.exit(1)
+
+ def create_rangerdb_user(self, root_user, db_user, db_password, db_root_password,dryMode):
+ if self.check_connection('', root_user, db_root_password):
+ if self.verify_user(root_user, db_root_password, db_user,dryMode):
+ if dryMode == False:
+ log("[I] SQL Anywhere user " + db_user + " already exists.", "info")
+ else:
+ if dryMode == False:
+ get_cmd = self.get_jisql_cmd(root_user, db_root_password, '')
+ log("[I] User does not exists, Creating Login user " + db_user, "info")
+ if os_name == "LINUX":
+ query = get_cmd + " -c \; -query \"CREATE USER %s IDENTIFIED BY '%s';\"" %(db_user,db_password)
+ ret = subprocess.call(shlex.split(query))
+ elif os_name == "WINDOWS":
+ query = get_cmd + " -query \"CREATE USER %s IDENTIFIED BY '%s';\" -c ;" %(db_user,db_password)
+ ret = subprocess.call(query)
+ if ret == 0:
+ if self.verify_user(root_user, db_root_password, db_user,dryMode):
+ log("[I] SQL Anywhere user " + db_user + " created", "info")
+ else:
+ log("[E] SQL Anywhere user " +db_user+" creation failed..", "error")
+ sys.exit(1)
+ else:
+ log("[E] SQL Anywhere user " +db_user+" creation failed..", "error")
+ sys.exit(1)
+ else:
+ logFile("CREATE USER %s IDENTIFIED BY '%s';" %(db_user,db_password))
+
+ def start_db(self,root_user, db_root_password, db_name,dryMode):
+ if dryMode == False:
+ log("[I] Starting database " + db_name, "info")
+ get_cmd = self.get_jisql_cmd(root_user, db_root_password, '')
+ if os_name == "LINUX":
+ query = get_cmd + " -c \; -query \"start database '%s' autostop off;\"" %(db_name)
+ elif os_name == "WINDOWS":
+ query = get_cmd + " -query \"start database '%s' autostop off;\" -c ;" %(db_name)
+ output = check_output(query)
+
+ def verify_db(self, root_user, db_root_password, db_name,dryMode):
+ if dryMode == False:
+ log("[I] Verifying database " + db_name, "info")
+ get_cmd = self.get_jisql_cmd(root_user, db_root_password, '')
+ if os_name == "LINUX":
+ query = get_cmd + " -c \; -query \"select alias from sa_db_info() where alias='%s';\"" %(db_name)
+ elif os_name == "WINDOWS":
+ query = get_cmd + " -query \"select alias from sa_db_info() where alias='%s';\" -c ;" %(db_name)
+ output = check_output(query)
+ if output.strip(db_name + " |"):
+ return True
+ else:
+ return False
+
+ def create_db(self, root_user, db_root_password, db_name, db_user, db_password,dryMode):
+ if self.verify_db(root_user, db_root_password, db_name,dryMode):
+ if dryMode == False:
+ log("[I] Database " + db_name + " already exists.","info")
+ else:
+ if dryMode == False:
+ log("[I] Database does not exist. Creating database : " + db_name,"info")
+ get_cmd = self.get_jisql_cmd(root_user, db_root_password, '')
+ if os_name == "LINUX":
+ query = get_cmd + " -c \; -query \"create database '%s' dba user '%s' dba password '%s' database size 100MB;\"" %(db_name,db_user, db_password)
+ ret = subprocess.call(shlex.split(query))
+ elif os_name == "WINDOWS":
+ query = get_cmd + " -query \"create database '%s' dba user '%s' dba password '%s' database size 100MB;\" -c ;" %(db_name,db_user, db_password)
+ ret = subprocess.call(query)
+ if ret != 0:
+ log("[E] Database creation failed..","error")
+ sys.exit(1)
+ else:
+ self.start_db(root_user, db_root_password, db_name,dryMode)
+ if self.verify_db(root_user, db_root_password, db_name,dryMode):
+ self.create_user(root_user, db_name ,db_user, db_password, db_root_password,dryMode)
+ log("[I] Creating database " + db_name + " succeeded", "info")
+ return True
+ else:
+ log("[E] Database creation failed..","error")
+ sys.exit(1)
+ else:
+ logFile("create database %s dba user '%s' dba password '%s' database size 100MB;" %(db_name,db_user, db_password))
+
+ def create_user(self, root_user, db_name ,db_user, db_password, db_root_password,dryMode):
+ get_cmd = self.get_jisql_cmd(root_user, db_root_password, '')
+ if os_name == "LINUX":
+ query = get_cmd + " -c \; -query \"select name from syslogins where name ='%s';\"" %(db_user)
+ elif os_name == "WINDOWS":
+ query = get_cmd + " -query \"select name from syslogins where name ='%s';\" -c ;" %(db_user)
+ output = check_output(query)
+ if output.strip(db_user + " |"):
+ if dryMode == False:
+ log("[I] User "+db_user+" exist ","info")
+ else:
+ if dryMode == False:
+ if os_name == "LINUX":
+ query = get_cmd + " -c \; -query \"CREATE USER %s IDENTIFIED BY '%s';\"" %(db_user, db_password)
+ ret = subprocess.call(shlex.split(query))
+ elif os_name == "WINDOWS":
+ query = get_cmd + " -query \"CREATE USER %s IDENTIFIED BY '%s';\" -c ;" %(db_user, db_password)
+ ret = subprocess.call(query)
+ if ret == 0:
+ if os_name == "LINUX":
+ query = get_cmd + " -c \; -query \"select name from syslogins where name ='%s';\"" %(db_user)
+ elif os_name == "WINDOWS":
+ query = get_cmd + " -query \"select name from syslogins where name ='%s';\" -c ;" %(db_user)
+ output = check_output(query)
+ if output.strip(db_user + " |"):
+ log("[I] User "+db_user+" exist ","info")
+ else:
+ log("[E] Database creation failed..","error")
+ sys.exit(1)
+ else:
+ log("[E] Database creation failed..","error")
+ sys.exit(1)
+ else:
+ logFile("CREATE USER %s IDENTIFIED BY '%s';" %(db_user, db_password))
+
+ def grant_xa_db_user(self, root_user, db_name, db_user, db_password, db_root_password, is_revoke,dryMode):
+ if dryMode == False:
+ log("[I] Granting permission to user '" + db_user + "' on db '" + db_name + "'" , "info")
+ get_cmd = self.get_jisql_cmd(root_user, db_root_password, db_name)
+ if os_name == "LINUX":
+ query = get_cmd + " -c \; -query \" GRANT CONNECT to %s IDENTIFIED BY '%s';\"" %(db_user,db_password)
+ ret = subprocess.call(shlex.split(query))
+ elif os_name == "WINDOWS":
+ query = get_cmd + " -query \" GRANT CONNECT to %s IDENTIFIED BY '%s';\"" %(db_user,db_password)
+ ret = subprocess.call(query)
+ if ret != 0:
+ sys.exit(1)
+ else:
+ logFile("GRANT CONNECT to %s IDENTIFIED BY '%s';" %(db_user, db_password))
+
+ def create_auditdb_user(self, xa_db_host, audit_db_host, db_name, audit_db_name, xa_db_root_user, audit_db_root_user, db_user, audit_db_user, xa_db_root_password, audit_db_root_password, db_password, audit_db_password, DBA_MODE,dryMode):
+ is_revoke=False
+ if DBA_MODE == "TRUE":
+ if dryMode == False:
+ log("[I] ---------- Setup audit user ---------- ","info")
+ self.create_rangerdb_user(audit_db_root_user, db_user, db_password, audit_db_root_password,dryMode)
+ self.create_rangerdb_user(audit_db_root_user, audit_db_user, audit_db_password, audit_db_root_password,dryMode)
+ self.create_db(audit_db_root_user, audit_db_root_password ,audit_db_name, db_user, db_password,dryMode)
+ self.create_user(xa_db_root_user, audit_db_name ,db_user, db_password, xa_db_root_password,dryMode)
+ self.grant_xa_db_user(db_user, audit_db_name, audit_db_user, audit_db_password, db_password, is_revoke, dryMode)
def main(argv):
@@ -1167,7 +1352,7 @@ def main(argv):
else:
XA_DB_FLAVOR=''
while XA_DB_FLAVOR == "":
- log("Enter db flavour{MYSQL|ORACLE|POSTGRES|MSSQL} :","info")
+ log("Enter db flavour{MYSQL|ORACLE|POSTGRES|MSSQL|SQLANYWHERE} :","info")
XA_DB_FLAVOR=raw_input()
AUDIT_DB_FLAVOR = XA_DB_FLAVOR
@@ -1296,6 +1481,11 @@ def main(argv):
sqlserver_audit_file = os.path.join('db','sqlserver','xa_audit_db_sqlserver.sql')
sqlserver_patches = os.path.join('db','sqlserver','patches')
+ sqlanywhere_dbversion_catalog = os.path.join('db','sqlanywhere','create_dbversion_catalog.sql')
+ sqlanywhere_core_file = os.path.join('db','sqlanywhere','xa_core_db_sqlanywhere.sql')
+ sqlanywhere_audit_file = os.path.join('db','sqlanywhere','xa_audit_db_sqlanywhere.sql')
+ sqlanywhere_patches = os.path.join('db','sqlanywhere','patches')
+
x_db_version = 'x_db_version_h'
xa_access_audit = 'xa_access_audit'
x_user = 'x_portal_user'
@@ -1339,6 +1529,17 @@ def main(argv):
xa_db_version_file = os.path.join(RANGER_ADMIN_HOME,sqlserver_dbversion_catalog)
xa_db_core_file = os.path.join(RANGER_ADMIN_HOME,sqlserver_core_file)
xa_patch_file = os.path.join(RANGER_ADMIN_HOME,sqlserver_patches)
+
+ elif XA_DB_FLAVOR == "SQLANYWHERE":
+ if not os_name == "WINDOWS" :
+ if os.environ['LD_LIBRARY_PATH'] == "":
+ log("[E] ---------- LD_LIBRARY_PATH environment property not defined, aborting installation. ----------", "error")
+ sys.exit(1)
+ SQLANYWHERE_CONNECTOR_JAR=CONNECTOR_JAR
+ xa_sqlObj = SqlAnywhereConf(xa_db_host, SQLANYWHERE_CONNECTOR_JAR, JAVA_BIN)
+ xa_db_version_file = os.path.join(RANGER_ADMIN_HOME,sqlanywhere_dbversion_catalog)
+ xa_db_core_file = os.path.join(RANGER_ADMIN_HOME,sqlanywhere_core_file)
+ xa_patch_file = os.path.join(RANGER_ADMIN_HOME,sqlanywhere_patches)
else:
log("[E] ---------- NO SUCH SUPPORTED DB FLAVOUR.. ----------", "error")
sys.exit(1)
@@ -1374,6 +1575,11 @@ def main(argv):
SQLSERVER_CONNECTOR_JAR=CONNECTOR_JAR
audit_sqlObj = SqlServerConf(audit_db_host, SQLSERVER_CONNECTOR_JAR, JAVA_BIN)
audit_db_file = os.path.join(RANGER_ADMIN_HOME,sqlserver_audit_file)
+
+ elif AUDIT_DB_FLAVOR == "SQLANYWHERE":
+ SQLANYWHERE_CONNECTOR_JAR=CONNECTOR_JAR
+ audit_sqlObj = SqlAnywhereConf(audit_db_host, SQLANYWHERE_CONNECTOR_JAR, JAVA_BIN)
+ audit_db_file = os.path.join(RANGER_ADMIN_HOME,sqlanywhere_audit_file)
else:
log("[E] ---------- NO SUCH SUPPORTED DB FLAVOUR.. ----------", "error")
sys.exit(1)
@@ -1394,7 +1600,8 @@ def main(argv):
logFile("===============================================\n")
xa_sqlObj.create_rangerdb_user(xa_db_root_user, db_user, db_password, xa_db_root_password,dryMode)
xa_sqlObj.create_db(xa_db_root_user, xa_db_root_password, db_name, db_user, db_password,dryMode)
- xa_sqlObj.grant_xa_db_user(xa_db_root_user, db_name, db_user, db_password, xa_db_root_password, is_revoke,dryMode)
+ if not XA_DB_FLAVOR == "SQLANYWHERE":
+ xa_sqlObj.grant_xa_db_user(xa_db_root_user, db_name, db_user, db_password, xa_db_root_password, is_revoke,dryMode)
audit_sqlObj.create_auditdb_user(xa_db_host, audit_db_host, db_name, audit_db_name, xa_db_root_user, audit_db_root_user, db_user, audit_db_user, xa_db_root_password, audit_db_root_password, db_password, audit_db_password, DBA_MODE,dryMode)
logFile("===============================================\n")
if (dryMode==False):
@@ -1403,7 +1610,8 @@ def main(argv):
log("[I] ---------- Creating Ranger Admin database ----------","info")
xa_sqlObj.create_db(xa_db_root_user, xa_db_root_password, db_name, db_user, db_password,dryMode)
log("[I] ---------- Granting permission to Ranger Admin db user ----------","info")
- xa_sqlObj.grant_xa_db_user(xa_db_root_user, db_name, db_user, db_password, xa_db_root_password, is_revoke,dryMode)
+ if not XA_DB_FLAVOR == "SQLANYWHERE":
+ xa_sqlObj.grant_xa_db_user(xa_db_root_user, db_name, db_user, db_password, xa_db_root_password, is_revoke,dryMode)
# Ranger Admin DB Host AND Ranger Audit DB Host are Different OR Same
if audit_store == "db":
log("[I] ---------- Verifying/Creating audit user --------- ","info")
diff --git a/security-admin/scripts/install.properties b/security-admin/scripts/install.properties
index 820d9c7fdcd..294b0e8df74 100644
--- a/security-admin/scripts/install.properties
+++ b/security-admin/scripts/install.properties
@@ -14,7 +14,7 @@
# limitations under the License.
#
-# This file provides list of deployment variables for the Policy Manager Web Application
+# This file provides list of deployment variables for the Policy Manager Web Application
#
#------------------------- DB CONFIG - BEGIN ----------------------------------
@@ -23,10 +23,10 @@
PYTHON_COMMAND_INVOKER=python
-#DB_FLAVOR=MYSQL|ORACLE|POSTGRES|MSSQL
+#DB_FLAVOR=MYSQL|ORACLE|POSTGRES|MSSQL|SQLANYWHERE
DB_FLAVOR=MYSQL
#
-# The executable path to be used to invoke command-line MYSQL
+# The executable path to be used to invoke command-line MYSQL
#
#SQL_COMMAND_INVOKER='mysql'
#SQL_COMMAND_INVOKER='sqlplus'
@@ -39,17 +39,18 @@ SQL_COMMAND_INVOKER='mysql'
#SQL_CONNECTOR_JAR=/usr/share/java/mysql-connector-java.jar
#SQL_CONNECTOR_JAR=/usr/share/java/postgresql.jar
#SQL_CONNECTOR_JAR=/usr/share/java/sqljdbc4.jar
+#SQL_CONNECTOR_JAR=/opt/sqlanywhere17/java/sajdbc4.jar
SQL_CONNECTOR_JAR=/usr/share/java/mysql-connector-java.jar
#
# DB password for the DB admin user-id
# **************************************************************************
-# ** If the password is left empty or not-defined here,
-# ** it will be prompted to enter the password during installation process
+# ** If the password is left empty or not-defined here,
+# ** it will be prompted to enter the password during installation process
# **************************************************************************
#
-#db_root_user=root|SYS|postgres|sa
+#db_root_user=root|SYS|postgres|sa|dba
db_root_user=root
db_root_password=
db_host=localhost
@@ -61,7 +62,7 @@ db_name=ranger
db_user=rangeradmin
db_password=
-#Source for Audit DB
+#Source for Audit DB
# * audit_db is solr or db
audit_store=db
@@ -74,9 +75,9 @@ audit_solr_zookeepers=
#
# DB UserId for storing auditlog infromation
-#
+#
# * audit_db can be same as the Ranger schema db
-# * audit_db must exists in the same ${db_host} as Ranger database ${db_name}
+# * audit_db must exists in the same ${db_host} as Ranger database ${db_name}
# * audit_user must be a different user than db_user (as audit user has access to only audit tables)
#
audit_db_name=ranger_audit
@@ -197,4 +198,7 @@ postgres_core_file=db/postgres/xa_core_db_postgres.sql
postgres_audit_file=db/postgres/xa_audit_db_postgres.sql
sqlserver_core_file=db/sqlserver/xa_core_db_sqlserver.sql
sqlserver_audit_file=db/sqlserver/xa_audit_db_sqlserver.sql
+#
+sqlanywhere_core_file=db/sqlanywhere/xa_core_db_sqlanywhere.sql
+sqlanywhere_audit_file=db/sqlanywhere/xa_audit_db_sqlanywhere.sql
cred_keystore_filename=$app_home/WEB-INF/classes/conf/.jceks/rangeradmin.jceks
diff --git a/security-admin/scripts/setup.sh b/security-admin/scripts/setup.sh
index b79cba47545..a88b264d81a 100755
--- a/security-admin/scripts/setup.sh
+++ b/security-admin/scripts/setup.sh
@@ -303,6 +303,19 @@ sanity_check_files() {
log "[E] ${sqlserver_core_file} does not exists" ; exit 1;
fi
fi
+ if [ "${DB_FLAVOR}" == "SQLANYWHERE" ]
+ then
+ if [ "${LD_LIBRARY_PATH}" == "" ]
+ then
+ log "[E] LD_LIBRARY_PATH environment property not defined, aborting installation."
+ exit 1
+ fi
+ if test -f ${sqlanywhere_core_file}; then
+ log "[I] ${sqlanywhere_core_file} file found"
+ else
+ log "[E] ${sqlanywhere_core_file} does not exists" ; exit 1;
+ fi
+ fi
}
create_rollback_point() {
@@ -874,6 +887,33 @@ update_properties() {
updatePropertyToFilePy $propertyName $newPropertyValue $to_file_ranger
fi
+ if [ "${DB_FLAVOR}" == "SQLANYWHERE" ]
+ then
+ propertyName=ranger.jpa.jdbc.url
+ newPropertyValue="jdbc:sqlanywhere:database=${db_name};host=${DB_HOST}"
+ updatePropertyToFilePy $propertyName $newPropertyValue $to_file_ranger
+
+ propertyName=ranger.jpa.audit.jdbc.url
+ newPropertyValue="jdbc:sqlanywhere:database=${audit_db_name};host=${DB_HOST}"
+ updatePropertyToFilePy $propertyName $newPropertyValue $to_file_ranger
+
+ propertyName=ranger.jpa.jdbc.dialect
+ newPropertyValue="org.eclipse.persistence.platform.database.SQLAnywherePlatform"
+ updatePropertyToFilePy $propertyName $newPropertyValue $to_file_default
+
+ propertyName=ranger.jpa.jdbc.dialect
+ newPropertyValue="org.eclipse.persistence.platform.database.SQLAnywherePlatform"
+ updatePropertyToFilePy $propertyName $newPropertyValue $to_file_default
+
+ propertyName=ranger.jpa.jdbc.driver
+ newPropertyValue="sap.jdbc4.sqlanywhere.IDriver"
+ updatePropertyToFilePy $propertyName $newPropertyValue $to_file_ranger
+
+ propertyName=ranger.jpa.audit.jdbc.driver
+ newPropertyValue="sap.jdbc4.sqlanywhere.IDriver"
+ updatePropertyToFilePy $propertyName $newPropertyValue $to_file_ranger
+ fi
+
if [ "${audit_store}" == "solr" ]
then
propertyName=ranger.audit.solr.urls
diff --git a/security-admin/src/main/java/org/apache/ranger/biz/RangerBizUtil.java b/security-admin/src/main/java/org/apache/ranger/biz/RangerBizUtil.java
index 6ffcd665c7c..a536a1a3462 100644
--- a/security-admin/src/main/java/org/apache/ranger/biz/RangerBizUtil.java
+++ b/security-admin/src/main/java/org/apache/ranger/biz/RangerBizUtil.java
@@ -1366,6 +1366,10 @@ public static int getDBFlavor() {
return AppConstants.DB_FLAVOR_POSTGRES;
} else if (StringUtils.containsIgnoreCase(propertyValue, "sqlserver")) {
return AppConstants.DB_FLAVOR_SQLSERVER;
+ } else if (StringUtils.containsIgnoreCase(propertyValue, "mssql")) {
+ return AppConstants.DB_FLAVOR_SQLSERVER;
+ } else if (StringUtils.containsIgnoreCase(propertyValue, "sqlanywhere")) {
+ return AppConstants.DB_FLAVOR_SQLANYWHERE;
} else {
if(logger.isDebugEnabled()) {
logger.debug("DB Falvor could not be determined from property - " + propertyName + "=" + propertyValue);
diff --git a/security-admin/src/main/java/org/apache/ranger/biz/SessionMgr.java b/security-admin/src/main/java/org/apache/ranger/biz/SessionMgr.java
index bcbb2af6593..ccb18550dcc 100644
--- a/security-admin/src/main/java/org/apache/ranger/biz/SessionMgr.java
+++ b/security-admin/src/main/java/org/apache/ranger/biz/SessionMgr.java
@@ -20,6 +20,7 @@
package org.apache.ranger.biz;
import java.util.ArrayList;
+import java.util.Calendar;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
@@ -135,16 +136,18 @@ public UserSessionBase processSuccessLogin(int authType, String userAgent,
userSession.setXXPortalUser(gjUser);
userSession.setXXAuthSession(gjAuthSession);
resetUserSessionForProfiles(userSession);
-
+ Calendar cal = Calendar.getInstance();
if (details != null) {
logger.info("Login Success: loginId=" + currentLoginId
+ ", sessionId=" + gjAuthSession.getId()
+ ", sessionId=" + details.getSessionId()
- + ", requestId=" + details.getRemoteAddress());
+ + ", requestId=" + details.getRemoteAddress()
+ + ", epoch=" + cal.getTimeInMillis());
} else {
logger.info("Login Success: loginId=" + currentLoginId
+ ", sessionId=" + gjAuthSession.getId()
- + ", details is null");
+ + ", details is null"
+ + ", epoch=" + cal.getTimeInMillis());
}
}
diff --git a/security-admin/src/main/java/org/apache/ranger/common/AppConstants.java b/security-admin/src/main/java/org/apache/ranger/common/AppConstants.java
index 491726f9b42..5de18f6fb33 100644
--- a/security-admin/src/main/java/org/apache/ranger/common/AppConstants.java
+++ b/security-admin/src/main/java/org/apache/ranger/common/AppConstants.java
@@ -372,6 +372,7 @@ public class AppConstants extends RangerCommonEnums {
* DB Favor SQLServer
*/
public static final int DB_FLAVOR_SQLSERVER = 4;
+ public static final int DB_FLAVOR_SQLANYWHERE = 5;
/***************************************************************
diff --git a/security-admin/src/main/java/org/apache/ranger/security/listener/SpringEventListener.java b/security-admin/src/main/java/org/apache/ranger/security/listener/SpringEventListener.java
index ebdabed0574..5876445f663 100644
--- a/security-admin/src/main/java/org/apache/ranger/security/listener/SpringEventListener.java
+++ b/security-admin/src/main/java/org/apache/ranger/security/listener/SpringEventListener.java
@@ -19,6 +19,7 @@
package org.apache.ranger.security.listener;
+import java.util.Calendar;
import org.apache.log4j.Logger;
import org.apache.ranger.biz.SessionMgr;
import org.apache.ranger.entity.XXAuthSession;
@@ -66,9 +67,10 @@ protected void process(AuthenticationSuccessEvent authSuccessEvent) {
: "";
String sessionId = details != null ? details.getSessionId() : "";
- logger.info("Login Successful:" + auth.getName() + " | Ip Address:"
- + remoteAddress + " | sessionId=" + sessionId);
-
+ Calendar cal = Calendar.getInstance();
+ logger.info("Login Successful:" + auth.getName() + " | Ip Address:"
+ + remoteAddress + " | sessionId=" + sessionId + " | Epoch=" +cal.getTimeInMillis() );
+
// success logins are processed further in
// AKASecurityContextFormationFilter
}
diff --git a/storm-agent/scripts/install.sh b/storm-agent/scripts/install.sh
index d0063794749..5b7674a3bf5 100644
--- a/storm-agent/scripts/install.sh
+++ b/storm-agent/scripts/install.sh
@@ -258,6 +258,18 @@ then
newPropertyValue="com.microsoft.sqlserver.jdbc.SQLServerDriver"
updatePropertyToFile $propertyName $newPropertyValue $to_file
fi
+if [ "${DB_FLAVOR}" == "SQLANYWHERE" ]
+then
+ audit_db_hostname=`grep '^XAAUDIT.DB.HOSTNAME' ${install_dir}/install.properties | awk -F= '{ print $2 }'`
+ audit_db_name=`grep '^XAAUDIT.DB.DATABASE_NAME' ${install_dir}/install.properties | awk -F= '{ print $2 }'`
+ propertyName=XAAUDIT.DB.JDBC_URL
+ newPropertyValue="jdbc:sqlanywhere:database=${audit_db_name};host=${audit_db_hostname}"
+ updatePropertyToFile $propertyName $newPropertyValue $to_file
+
+ propertyName=XAAUDIT.DB.JDBC_DRIVER
+ newPropertyValue="sap.jdbc4.sqlanywhere.IDriver"
+ updatePropertyToFile $propertyName $newPropertyValue $to_file
+fi
for f in ${install_dir}/installer/conf/*-changes.cfg
do
if [ -f ${f} ]
From a451e028e14711fb2fe83103d8eab6f8a6d47f1f Mon Sep 17 00:00:00 2001
From: Alok Lal
Date: Thu, 20 Aug 2015 18:04:35 -0700
Subject: [PATCH 026/202] RANGER-622 Hive plugin - add jar via beeline throws
NPE in ranger code
---
.../hive/authorizer/RangerHiveAuthorizer.java | 8 ++++++++
1 file changed, 8 insertions(+)
diff --git a/hive-agent/src/main/java/org/apache/ranger/authorization/hive/authorizer/RangerHiveAuthorizer.java b/hive-agent/src/main/java/org/apache/ranger/authorization/hive/authorizer/RangerHiveAuthorizer.java
index 9075b574f00..7aaf8a18884 100644
--- a/hive-agent/src/main/java/org/apache/ranger/authorization/hive/authorizer/RangerHiveAuthorizer.java
+++ b/hive-agent/src/main/java/org/apache/ranger/authorization/hive/authorizer/RangerHiveAuthorizer.java
@@ -241,6 +241,10 @@ public void checkPrivileges(HiveOperationType hiveOpType,
for(HivePrivilegeObject hiveObj : inputHObjs) {
RangerHiveResource resource = getHiveResource(hiveOpType, hiveObj);
+ if (resource == null) { // possible if input object/object is of a kind that we don't currently authorize
+ continue;
+ }
+
if(resource.getObjectType() == HiveObjectType.URI) {
String path = hiveObj.getObjectName();
FsAction permission = FsAction.READ;
@@ -270,6 +274,10 @@ public void checkPrivileges(HiveOperationType hiveOpType,
for(HivePrivilegeObject hiveObj : outputHObjs) {
RangerHiveResource resource = getHiveResource(hiveOpType, hiveObj);
+ if (resource == null) { // possible if input object/object is of a kind that we don't currently authorize
+ continue;
+ }
+
if(resource.getObjectType() == HiveObjectType.URI) {
String path = hiveObj.getObjectName();
FsAction permission = FsAction.WRITE;
From 3b3b8d95ec42089548a128d26c213f1bc0071508 Mon Sep 17 00:00:00 2001
From: Alok Lal
Date: Thu, 13 Aug 2015 08:48:14 -0700
Subject: [PATCH 027/202] RANGER-615 Audit to db: Truncate all string values of
audit record so that writing of audit does not fail
---
.../audit/destination/DBAuditDestination.java | 5 +-
.../audit/entity/AuthzAuditEventDbObj.java | 143 ++++++++++++++++--
.../ranger/audit/model/AuditEventBase.java | 14 +-
.../ranger/audit/model/AuthzAuditEvent.java | 12 +-
.../audit/provider/DbAuditProvider.java | 4 +
5 files changed, 144 insertions(+), 34 deletions(-)
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/destination/DBAuditDestination.java b/agents-audit/src/main/java/org/apache/ranger/audit/destination/DBAuditDestination.java
index 3d31c06406c..376e724cff5 100644
--- a/agents-audit/src/main/java/org/apache/ranger/audit/destination/DBAuditDestination.java
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/destination/DBAuditDestination.java
@@ -33,6 +33,7 @@
import javax.persistence.Persistence;
import org.apache.ranger.audit.dao.DaoManager;
+import org.apache.ranger.audit.entity.AuthzAuditEventDbObj;
import org.apache.ranger.audit.model.AuditEventBase;
import org.apache.ranger.audit.provider.MiscUtil;
@@ -63,9 +64,11 @@ public DBAuditDestination() {
public void init(Properties props, String propPrefix) {
logger.info("init() called");
super.init(props, propPrefix);
-
// Initial connect
connect();
+
+ // initialize the database related classes
+ AuthzAuditEventDbObj.init(props);
}
/*
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/entity/AuthzAuditEventDbObj.java b/agents-audit/src/main/java/org/apache/ranger/audit/entity/AuthzAuditEventDbObj.java
index 435393e40fe..d52a60ae1e2 100644
--- a/agents-audit/src/main/java/org/apache/ranger/audit/entity/AuthzAuditEventDbObj.java
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/entity/AuthzAuditEventDbObj.java
@@ -21,6 +21,7 @@
import java.io.Serializable;
import java.util.Date;
+import java.util.Properties;
import javax.persistence.Column;
import javax.persistence.Entity;
@@ -32,8 +33,11 @@
import javax.persistence.TemporalType;
import javax.persistence.SequenceGenerator;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
import org.apache.ranger.audit.model.EnumRepositoryType;
import org.apache.ranger.audit.model.AuthzAuditEvent;
+import org.apache.ranger.audit.provider.MiscUtil;
/**
* Entity implementation class for Entity: AuthzAuditEventDbObj
@@ -42,8 +46,25 @@
@Entity
@Table(name="xa_access_audit")
public class AuthzAuditEventDbObj implements Serializable {
+
+ private static final Log LOG = LogFactory.getLog(AuthzAuditEventDbObj.class);
+
private static final long serialVersionUID = 1L;
+ static int MaxValueLengthAccessType = 255;
+ static int MaxValueLengthAclEnforcer = 255;
+ static int MaxValueLengthAgentId = 255;
+ static int MaxValueLengthClientIp = 255;
+ static int MaxValueLengthClientType = 255;
+ static int MaxValueLengthRepoName = 255;
+ static int MaxValueLengthResultReason = 255;
+ static int MaxValueLengthSessionId = 255;
+ static int MaxValueLengthRequestUser = 255;
+ static int MaxValueLengthAction = 2000;
+ static int MaxValueLengthRequestData = 4000;
+ static int MaxValueLengthResourcePath = 4000;
+ static int MaxValueLengthResourceType = 255;
+
private long auditId;
private int repositoryType;
private String repositoryName;
@@ -63,6 +84,60 @@ public class AuthzAuditEventDbObj implements Serializable {
private String clientIP;
private String requestData;
+ public static void init(Properties props)
+ {
+ LOG.info("AuthzAuditEventDbObj.init()");
+
+ final String AUDIT_DB_MAX_COLUMN_VALUE = "xasecure.audit.destination.db.max.column.length";
+ MaxValueLengthAccessType = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "access_type", MaxValueLengthAccessType);
+ logMaxColumnValue("access_type", MaxValueLengthAccessType);
+
+ MaxValueLengthAclEnforcer = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "acl_enforcer", MaxValueLengthAclEnforcer);
+ logMaxColumnValue("acl_enforcer", MaxValueLengthAclEnforcer);
+
+ MaxValueLengthAction = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "action", MaxValueLengthAction);
+ logMaxColumnValue("action", MaxValueLengthAction);
+
+ MaxValueLengthAgentId = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "agent_id", MaxValueLengthAgentId);
+ logMaxColumnValue("agent_id", MaxValueLengthAgentId);
+
+ MaxValueLengthClientIp = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "client_id", MaxValueLengthClientIp);
+ logMaxColumnValue("client_id", MaxValueLengthClientIp);
+
+ MaxValueLengthClientType = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "client_type", MaxValueLengthClientType);
+ logMaxColumnValue("client_type", MaxValueLengthClientType);
+
+ MaxValueLengthRepoName = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "repo_name", MaxValueLengthRepoName);
+ logMaxColumnValue("repo_name", MaxValueLengthRepoName);
+
+ MaxValueLengthResultReason = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "result_reason", MaxValueLengthResultReason);
+ logMaxColumnValue("result_reason", MaxValueLengthResultReason);
+
+ MaxValueLengthSessionId = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "session_id", MaxValueLengthSessionId);
+ logMaxColumnValue("session_id", MaxValueLengthSessionId);
+
+ MaxValueLengthRequestUser = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "request_user", MaxValueLengthRequestUser);
+ logMaxColumnValue("request_user", MaxValueLengthRequestUser);
+
+ MaxValueLengthRequestData = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "request_data", MaxValueLengthRequestData);
+ logMaxColumnValue("request_data", MaxValueLengthRequestData);
+
+ MaxValueLengthResourcePath = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "resource_path", MaxValueLengthResourcePath);
+ logMaxColumnValue("resource_path", MaxValueLengthResourcePath);
+
+ MaxValueLengthResourceType = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "resource_type", MaxValueLengthResourceType);
+ logMaxColumnValue("resource_type", MaxValueLengthResourceType);
+ }
+
+ public static void logMaxColumnValue(String columnName, int configuredMaxValueLength) {
+ LOG.info("Setting max column value for column[" + columnName + "] to [" + configuredMaxValueLength + "].");
+ if (configuredMaxValueLength == 0) {
+ LOG.info("Max length of column[" + columnName + "] was 0! Column will NOT be emitted in the audit.");
+ } else if (configuredMaxValueLength < 0) {
+ LOG.info("Max length of column[" + columnName + "] was less than 0! Column value will never be truncated.");
+ }
+ }
+
public AuthzAuditEventDbObj() {
super();
@@ -113,7 +188,7 @@ public void setRepositoryType(int repositoryType) {
@Column(name = "repo_name")
public String getRepositoryName() {
- return this.repositoryName;
+ return truncate(this.repositoryName, MaxValueLengthRepoName, "repo_name");
}
public void setRepositoryName(String repositoryName) {
@@ -122,7 +197,7 @@ public void setRepositoryName(String repositoryName) {
@Column(name = "request_user")
public String getUser() {
- return this.user;
+ return truncate(this.user, MaxValueLengthRequestUser, "request_user");
}
public void setUser(String user) {
@@ -141,7 +216,7 @@ public void setTimeStamp(Date timeStamp) {
@Column(name = "access_type")
public String getAccessType() {
- return this.accessType;
+ return truncate(this.accessType, MaxValueLengthAccessType, "access_type");
}
public void setAccessType(String accessType) {
@@ -150,7 +225,7 @@ public void setAccessType(String accessType) {
@Column(name = "resource_path")
public String getResourcePath() {
- return this.resourcePath;
+ return truncate(this.resourcePath, MaxValueLengthResourcePath, "resource_path");
}
public void setResourcePath(String resourcePath) {
@@ -159,7 +234,7 @@ public void setResourcePath(String resourcePath) {
@Column(name = "resource_type")
public String getResourceType() {
- return this.resourceType;
+ return truncate(this.resourceType, MaxValueLengthResourceType, "resource_type");
}
public void setResourceType(String resourceType) {
@@ -168,7 +243,7 @@ public void setResourceType(String resourceType) {
@Column(name = "action")
public String getAction() {
- return this.action;
+ return truncate(this.action, MaxValueLengthAction, "action");
}
public void setAction(String action) {
@@ -186,7 +261,7 @@ public void setAccessResult(int accessResult) {
@Column(name = "agent_id")
public String getAgentId() {
- return agentId;
+ return truncate(this.agentId, MaxValueLengthAgentId, "agent_id");
}
public void setAgentId(String agentId) {
@@ -204,7 +279,7 @@ public void setPolicyId(long policyId) {
@Column(name = "result_reason")
public String getResultReason() {
- return this.resultReason;
+ return truncate(this.resultReason, MaxValueLengthResultReason, "result_reason");
}
public void setResultReason(String resultReason) {
@@ -213,7 +288,7 @@ public void setResultReason(String resultReason) {
@Column(name = "acl_enforcer")
public String getAclEnforcer() {
- return this.aclEnforcer;
+ return truncate(this.aclEnforcer, MaxValueLengthAclEnforcer, "acl_enforcer");
}
public void setAclEnforcer(String aclEnforcer) {
@@ -222,7 +297,7 @@ public void setAclEnforcer(String aclEnforcer) {
@Column(name = "session_id")
public String getSessionId() {
- return this.sessionId;
+ return truncate(this.sessionId, MaxValueLengthSessionId, "session_id");
}
public void setSessionId(String sessionId) {
@@ -231,7 +306,7 @@ public void setSessionId(String sessionId) {
@Column(name = "client_type")
public String getClientType() {
- return this.clientType;
+ return truncate(this.clientType, MaxValueLengthClientType, "client_type");
}
public void setClientType(String clientType) {
@@ -240,7 +315,7 @@ public void setClientType(String clientType) {
@Column(name = "client_ip")
public String getClientIP() {
- return this.clientIP;
+ return truncate(this.clientIP, MaxValueLengthClientIp, "client_ip");
}
public void setClientIP(String clientIP) {
@@ -249,10 +324,52 @@ public void setClientIP(String clientIP) {
@Column(name = "request_data")
public String getRequestData() {
- return this.requestData;
+ return truncate(this.requestData, MaxValueLengthRequestData, "request_data");
}
public void setRequestData(String requestData) {
this.requestData = requestData;
}
+ static final String TruncationMarker = "...";
+ static final int TruncationMarkerLength = TruncationMarker.length();
+
+ protected String truncate(String value, int limit, String columnName) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug(String.format("==> getTrunctedValue(%s, %d, %s)", value, limit, columnName));
+ }
+
+ String result = value;
+ if (value != null) {
+ if (limit < 0) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug(String.format("Truncation is suppressed for column[%s]: old value [%s], new value[%s]", columnName, value, result));
+ }
+ } else if (limit == 0) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug(String.format("Column[%s] is to be excluded from audit: old value [%s], new value[%s]", columnName, value, result));
+ }
+ result = null;
+ } else {
+ if (value.length() > limit) {
+ if (limit <= TruncationMarkerLength) {
+ // NOTE: If value is to be truncated to a size that is less than of equal to the Truncation Marker then we won't put the marker in!!
+ result = value.substring(0, limit);
+ } else {
+ StringBuilder sb = new StringBuilder(value.substring(0, limit - TruncationMarkerLength));
+ sb.append(TruncationMarker);
+ result = sb.toString();
+ }
+ if (LOG.isDebugEnabled()) {
+ LOG.debug(String.format("Truncating value for column[%s] to [%d] characters: old value [%s], new value[%s]", columnName, limit, value, result));
+ }
+ }
+ }
+ }
+
+ if (LOG.isDebugEnabled()) {
+ LOG.debug(String.format("<== getTrunctedValue(%s, %d, %s): %s", value, limit, columnName, result));
+ }
+ return result;
+ }
+
}
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/model/AuditEventBase.java b/agents-audit/src/main/java/org/apache/ranger/audit/model/AuditEventBase.java
index 2c6a87f3413..2a07e94af46 100644
--- a/agents-audit/src/main/java/org/apache/ranger/audit/model/AuditEventBase.java
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/model/AuditEventBase.java
@@ -21,6 +21,8 @@
import java.util.Date;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
import org.apache.ranger.audit.dao.DaoManager;
public abstract class AuditEventBase {
@@ -34,16 +36,4 @@ protected AuditEventBase() {
public abstract Date getEventTime ();
public abstract void setEventCount(long eventCount);
public abstract void setEventDurationMS(long eventDurationMS);
-
- protected String trim(String str, int len) {
- String ret = str;
- if (str != null) {
- if (str.length() > len) {
- ret = str.substring(0, len);
- }
- }
- return ret;
- }
-
-
}
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/model/AuthzAuditEvent.java b/agents-audit/src/main/java/org/apache/ranger/audit/model/AuthzAuditEvent.java
index d648de32cd2..2a8d79249b0 100644
--- a/agents-audit/src/main/java/org/apache/ranger/audit/model/AuthzAuditEvent.java
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/model/AuthzAuditEvent.java
@@ -190,8 +190,8 @@ public Date getEventTime() {
}
/**
- * @param timeStamp
- * the timeStamp to set
+ * @param eventTime
+ * the eventTime to set
*/
public void setEventTime(Date eventTime) {
this.eventTime = eventTime;
@@ -245,9 +245,7 @@ public void setResourceType(String resourceType) {
/**
* @return the action
*/
- public String getAction() {
- return trim(action, MAX_ACTION_FIELD_SIZE);
- }
+ public String getAction() { return action; }
/**
* @param action
@@ -380,9 +378,7 @@ public void setClientIP(String clientIP) {
/**
* @return the requestData
*/
- public String getRequestData() {
- return trim(requestData, MAX_REQUEST_DATA_FIELD_SIZE);
- }
+ public String getRequestData() { return requestData; }
/**
* @param requestData
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/provider/DbAuditProvider.java b/agents-audit/src/main/java/org/apache/ranger/audit/provider/DbAuditProvider.java
index 98da1c2d814..f23f17d21e9 100644
--- a/agents-audit/src/main/java/org/apache/ranger/audit/provider/DbAuditProvider.java
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/provider/DbAuditProvider.java
@@ -32,6 +32,7 @@
import org.apache.commons.logging.LogFactory;
import org.apache.ranger.audit.dao.DaoManager;
import org.apache.ranger.audit.destination.AuditDestination;
+import org.apache.ranger.audit.entity.AuthzAuditEventDbObj;
import org.apache.ranger.audit.model.AuditEventBase;
import org.apache.ranger.audit.model.AuthzAuditEvent;
import org.apache.ranger.authorization.hadoop.utils.RangerCredentialProvider;
@@ -91,6 +92,9 @@ public void init(Properties props) {
if(jdbcPassword != null && !jdbcPassword.isEmpty()) {
mDbProperties.put(AUDIT_JPA_JDBC_PASSWORD, jdbcPassword);
}
+
+ // initialize the database related classes
+ AuthzAuditEventDbObj.init(props);
}
@Override
From fc66b15f2c037c4763a47017211471eb6096b175 Mon Sep 17 00:00:00 2001
From: Gautam Borad
Date: Sat, 22 Aug 2015 03:42:47 +0530
Subject: [PATCH 028/202] RANGER-624 : Fix Windows installation issue after
SQLAnywhere support
Signed-off-by: Velmurugan Periasamy
---
security-admin/src/bin/ranger_install.py | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/security-admin/src/bin/ranger_install.py b/security-admin/src/bin/ranger_install.py
index 42142fe7c10..2970715219f 100644
--- a/security-admin/src/bin/ranger_install.py
+++ b/security-admin/src/bin/ranger_install.py
@@ -310,6 +310,8 @@ def init_variables(switch):
conf_dict['postgres_audit_file']=os.path.join(db_dir,'postgres','xa_audit_db_postgres.sql')
conf_dict['sqlserver_core_file']=os.path.join(db_dir,'sqlserver','xa_core_db_sqlserver.sql')
conf_dict['sqlserver_audit_file']=os.path.join(db_dir,'sqlserver','xa_audit_db_sqlserver.sql')
+ conf_dict['sqlanywhere_core_file']= os.path.join(db_dir,'sqlanywhere','xa_core_db_sqlanywhere.sql')
+ conf_dict['sqlanywhere_audit_file']= os.path.join(db_dir, 'sqlanywhere','xa_audit_db_sqlanywhere.sql')
#conf_dict['db_core_file'] = os.path.join(db_dir, "xa_core_db.sql")
#conf_dict['db_create_user_file'] = os.path.join(db_dir, "create_dev_user.sql")
#conf_dict['db_audit_file'] = os.path.join(db_dir, "xa_audit_db.sql")
@@ -1281,4 +1283,4 @@ def configure():
# copy_mysql_connector()
#log(" --------- Creatin Audit DB --------- ","info")
setup_admin_db_user()
- setup_audit_user_db()
\ No newline at end of file
+ setup_audit_user_db()
From 4a5a4f29bb8a0cc6ecda51cdc9031bb6d510a6b3 Mon Sep 17 00:00:00 2001
From: Velmurugan Periasamy
Date: Mon, 24 Aug 2015 21:05:11 -0700
Subject: [PATCH 029/202] RANGER-625:Change db flavor input parameter value
from SQLAnywhere to SQLA
---
agents-common/scripts/enable-agent.sh | 2 +-
hbase-agent/scripts/install.sh | 2 +-
hdfs-agent/scripts/install.sh | 2 +-
hive-agent/scripts/install.sh | 2 +-
jisql/src/main/java/org/apache/util/sql/Jisql.java | 1 +
kms/scripts/db_setup.py | 2 +-
kms/scripts/dba_script.py | 4 ++--
kms/scripts/install.properties | 2 +-
kms/scripts/setup.sh | 4 ++--
knox-agent/scripts/install.sh | 2 +-
security-admin/scripts/db_setup.py | 7 +++----
security-admin/scripts/dba_script.py | 10 +++++-----
security-admin/scripts/install.properties | 2 +-
security-admin/scripts/setup.sh | 4 ++--
.../main/java/org/apache/ranger/biz/RangerBizUtil.java | 6 ++++--
storm-agent/scripts/install.sh | 2 +-
16 files changed, 28 insertions(+), 26 deletions(-)
diff --git a/agents-common/scripts/enable-agent.sh b/agents-common/scripts/enable-agent.sh
index 6adb2c44e90..9f677098c3c 100755
--- a/agents-common/scripts/enable-agent.sh
+++ b/agents-common/scripts/enable-agent.sh
@@ -382,7 +382,7 @@ then
then
export XAAUDIT_DB_JDBC_URL="jdbc:sqlserver://${audit_db_hostname};databaseName=${audit_db_name}"
export XAAUDIT_DB_JDBC_DRIVER="com.microsoft.sqlserver.jdbc.SQLServerDriver"
- elif [ "${db_flavor}" = "SQLANYWHERE" ]
+ elif [ "${db_flavor}" = "SQLA" ]
then
export XAAUDIT_DB_JDBC_URL="jdbc:sqlanywhere:database=${audit_db_name};host=${audit_db_hostname}"
export XAAUDIT_DB_JDBC_DRIVER="sap.jdbc4.sqlanywhere.IDriver"
diff --git a/hbase-agent/scripts/install.sh b/hbase-agent/scripts/install.sh
index 116beab58e8..a7b67f3ef20 100644
--- a/hbase-agent/scripts/install.sh
+++ b/hbase-agent/scripts/install.sh
@@ -312,7 +312,7 @@ then
newPropertyValue="com.microsoft.sqlserver.jdbc.SQLServerDriver"
updatePropertyToFile $propertyName $newPropertyValue $to_file
fi
-if [ "${DB_FLAVOR}" == "SQLANYWHERE" ]
+if [ "${DB_FLAVOR}" == "SQLA" ]
then
audit_db_hostname=`grep '^XAAUDIT.DB.HOSTNAME' ${install_dir}/install.properties | awk -F= '{ print $2 }'`
audit_db_name=`grep '^XAAUDIT.DB.DATABASE_NAME' ${install_dir}/install.properties | awk -F= '{ print $2 }'`
diff --git a/hdfs-agent/scripts/install.sh b/hdfs-agent/scripts/install.sh
index e9215fdc720..9eef8dabaf7 100644
--- a/hdfs-agent/scripts/install.sh
+++ b/hdfs-agent/scripts/install.sh
@@ -319,7 +319,7 @@ then
newPropertyValue="com.microsoft.sqlserver.jdbc.SQLServerDriver"
updatePropertyToFile $propertyName $newPropertyValue $to_file
fi
-if [ "${DB_FLAVOR}" == "SQLANYWHERE" ]
+if [ "${DB_FLAVOR}" == "SQLA" ]
then
audit_db_hostname=`grep '^XAAUDIT.DB.HOSTNAME' ${install_dir}/install.properties | awk -F= '{ print $2 }'`
audit_db_name=`grep '^XAAUDIT.DB.DATABASE_NAME' ${install_dir}/install.properties | awk -F= '{ print $2 }'`
diff --git a/hive-agent/scripts/install.sh b/hive-agent/scripts/install.sh
index 74c6e568a87..cf7180dd3e4 100644
--- a/hive-agent/scripts/install.sh
+++ b/hive-agent/scripts/install.sh
@@ -296,7 +296,7 @@ then
newPropertyValue="com.microsoft.sqlserver.jdbc.SQLServerDriver"
updatePropertyToFile $propertyName $newPropertyValue $to_file
fi
-if [ "${DB_FLAVOR}" == "SQLANYWHERE" ]
+if [ "${DB_FLAVOR}" == "SQLA" ]
then
audit_db_hostname=`grep '^XAAUDIT.DB.HOSTNAME' ${install_dir}/install.properties | awk -F= '{ print $2 }'`
audit_db_name=`grep '^XAAUDIT.DB.DATABASE_NAME' ${install_dir}/install.properties | awk -F= '{ print $2 }'`
diff --git a/jisql/src/main/java/org/apache/util/sql/Jisql.java b/jisql/src/main/java/org/apache/util/sql/Jisql.java
index cf7563c7130..9c743564a44 100644
--- a/jisql/src/main/java/org/apache/util/sql/Jisql.java
+++ b/jisql/src/main/java/org/apache/util/sql/Jisql.java
@@ -755,6 +755,7 @@ private void printAllExceptions(SQLException sqle) {
+ sqle.getErrorCode());
sqle = sqle.getNextException();
}
+ System.out.println("java.library.path:"+System.getProperty("java.library.path"));
}
/**
diff --git a/kms/scripts/db_setup.py b/kms/scripts/db_setup.py
index 9dbeb04c471..61940cca3ce 100644
--- a/kms/scripts/db_setup.py
+++ b/kms/scripts/db_setup.py
@@ -557,7 +557,7 @@ def main(argv):
xa_sqlObj = SqlServerConf(xa_db_host, SQLSERVER_CONNECTOR_JAR, JAVA_BIN)
xa_db_core_file = os.path.join(RANGER_KMS_HOME , sqlserver_core_file)
- elif XA_DB_FLAVOR == "SQLANYWHERE":
+ elif XA_DB_FLAVOR == "SQLA":
if not os_name == "WINDOWS" :
if os.environ['LD_LIBRARY_PATH'] == "":
log("[E] ---------- LD_LIBRARY_PATH environment property not defined, aborting installation. ----------", "error")
diff --git a/kms/scripts/dba_script.py b/kms/scripts/dba_script.py
index 0830af4e6fb..03e0a19e193 100644
--- a/kms/scripts/dba_script.py
+++ b/kms/scripts/dba_script.py
@@ -1138,7 +1138,7 @@ def main(argv):
else:
XA_DB_FLAVOR=''
while XA_DB_FLAVOR == "":
- log("Enter db flavour{MYSQL|ORACLE|POSTGRES|MSSQL|SQLANYWHERE} :","info")
+ log("Enter db flavour{MYSQL|ORACLE|POSTGRES|MSSQL|SQLA} :","info")
XA_DB_FLAVOR=raw_input()
XA_DB_FLAVOR = XA_DB_FLAVOR.upper()
@@ -1242,7 +1242,7 @@ def main(argv):
xa_sqlObj = SqlServerConf(xa_db_host, SQLSERVER_CONNECTOR_JAR, JAVA_BIN)
xa_db_core_file = os.path.join(RANGER_KMS_HOME,sqlserver_core_file)
- elif XA_DB_FLAVOR == "SQLANYWHERE":
+ elif XA_DB_FLAVOR == "SQLA":
if not os_name == "WINDOWS" :
if os.environ['LD_LIBRARY_PATH'] == "":
log("[E] ---------- LD_LIBRARY_PATH environment property not defined, aborting installation. ----------", "error")
diff --git a/kms/scripts/install.properties b/kms/scripts/install.properties
index bad7f204626..563a0e08165 100755
--- a/kms/scripts/install.properties
+++ b/kms/scripts/install.properties
@@ -23,7 +23,7 @@
PYTHON_COMMAND_INVOKER=python
-#DB_FLAVOR=MYSQL|ORACLE|POSTGRES|MSSQL|SQLANYWHERE
+#DB_FLAVOR=MYSQL|ORACLE|POSTGRES|MSSQL|SQLA
DB_FLAVOR=MYSQL
#
# The executable path to be used to invoke command-line MYSQL
diff --git a/kms/scripts/setup.sh b/kms/scripts/setup.sh
index 1410f460c21..2e7dd8ecd65 100755
--- a/kms/scripts/setup.sh
+++ b/kms/scripts/setup.sh
@@ -277,7 +277,7 @@ sanity_check_files() {
log "[E] ${sqlserver_core_file} does not exists" ; exit 1;
fi
fi
- if [ "${DB_FLAVOR}" == "SQLANYWHERE" ]
+ if [ "${DB_FLAVOR}" == "SQLA" ]
then
if [ "${LD_LIBRARY_PATH}" == "" ]
then
@@ -410,7 +410,7 @@ update_properties() {
updatePropertyToFilePy $propertyName $newPropertyValue $to_file
fi
- if [ "${DB_FLAVOR}" == "SQLANYWHERE" ]
+ if [ "${DB_FLAVOR}" == "SQLA" ]
then
propertyName=ranger.ks.jpa.jdbc.url
newPropertyValue="jdbc:sqlanywhere:database=${db_name};host=${DB_HOST}"
diff --git a/knox-agent/scripts/install.sh b/knox-agent/scripts/install.sh
index 163dbc56677..271a2d44e1c 100644
--- a/knox-agent/scripts/install.sh
+++ b/knox-agent/scripts/install.sh
@@ -215,7 +215,7 @@ then
newPropertyValue="com.microsoft.sqlserver.jdbc.SQLServerDriver"
updatePropertyToFile $propertyName $newPropertyValue $to_file
fi
-if [ "${DB_FLAVOR}" == "SQLANYWHERE" ]
+if [ "${DB_FLAVOR}" == "SQLA" ]
then
audit_db_hostname=`grep '^XAAUDIT.DB.HOSTNAME' ${install_dir}/install.properties | awk -F= '{ print $2 }'`
audit_db_name=`grep '^XAAUDIT.DB.DATABASE_NAME' ${install_dir}/install.properties | awk -F= '{ print $2 }'`
diff --git a/security-admin/scripts/db_setup.py b/security-admin/scripts/db_setup.py
index a010e19aa12..1edc628d96d 100644
--- a/security-admin/scripts/db_setup.py
+++ b/security-admin/scripts/db_setup.py
@@ -1211,6 +1211,7 @@ def import_db_file(self, db_name, db_user, db_password, file_name):
sys.exit(1)
def check_table(self, db_name, db_user, db_password, TABLE_NAME):
+ self.set_options(db_name, db_user, db_password, TABLE_NAME)
get_cmd = self.get_jisql_cmd(db_user, db_password, db_name)
if os_name == "LINUX":
query = get_cmd + " -c \; -query \"SELECT name FROM sysobjects where name = '%s' and type='U';\"" %(TABLE_NAME)
@@ -1277,7 +1278,6 @@ def import_db_patches(self, db_name, db_user, db_password, file_name):
def import_auditdb_patches(self, xa_sqlObj,xa_db_host, audit_db_host, db_name, audit_db_name, db_user, audit_db_user, db_password, audit_db_password, file_name, TABLE_NAME):
log("[I] --------- Checking XA_ACCESS_AUDIT table to apply audit db patches --------- ","info")
- self.set_options(audit_db_name, db_user, db_password, TABLE_NAME)
output = self.check_table(audit_db_name, db_user, db_password, TABLE_NAME)
if output == True:
name = basename(file_name)
@@ -1326,7 +1326,6 @@ def auditdb_operation(self, xa_db_host, audit_db_host, db_name, audit_db_name,db
log("[I] --------- Check audit user connection --------- ","info")
self.check_connection(audit_db_name, audit_db_user, audit_db_password)
log("[I] --------- Check audit table exists --------- ","info")
- self.set_options(audit_db_name, db_user, db_password, TABLE_NAME)
output = self.check_table(audit_db_name, db_user, db_password, TABLE_NAME)
if output == False:
self.import_db_file(audit_db_name ,db_user, db_password, file_name)
@@ -1522,7 +1521,7 @@ def main(argv):
xa_patch_file = os.path.join(RANGER_ADMIN_HOME , sqlserver_patches)
audit_patch_file = os.path.join(RANGER_ADMIN_HOME ,sqlserver_auditdb_patches)
- elif XA_DB_FLAVOR == "SQLANYWHERE":
+ elif XA_DB_FLAVOR == "SQLA":
if not os_name == "WINDOWS" :
if os.environ['LD_LIBRARY_PATH'] == "":
log("[E] ---------- LD_LIBRARY_PATH environment property not defined, aborting installation. ----------", "error")
@@ -1558,7 +1557,7 @@ def main(argv):
audit_sqlObj = SqlServerConf(audit_db_host, SQLSERVER_CONNECTOR_JAR, JAVA_BIN)
audit_db_file = os.path.join(RANGER_ADMIN_HOME , sqlserver_audit_file)
- elif AUDIT_DB_FLAVOR == "SQLANYWHERE":
+ elif AUDIT_DB_FLAVOR == "SQLA":
SQLANYWHERE_CONNECTOR_JAR = globalDict['SQL_CONNECTOR_JAR']
audit_sqlObj = SqlAnywhereConf(audit_db_host, SQLANYWHERE_CONNECTOR_JAR, JAVA_BIN)
audit_db_file = os.path.join(RANGER_ADMIN_HOME , sqlanywhere_audit_file)
diff --git a/security-admin/scripts/dba_script.py b/security-admin/scripts/dba_script.py
index 0d5d573888d..90ae5615e71 100644
--- a/security-admin/scripts/dba_script.py
+++ b/security-admin/scripts/dba_script.py
@@ -1352,7 +1352,7 @@ def main(argv):
else:
XA_DB_FLAVOR=''
while XA_DB_FLAVOR == "":
- log("Enter db flavour{MYSQL|ORACLE|POSTGRES|MSSQL|SQLANYWHERE} :","info")
+ log("Enter db flavour{MYSQL|ORACLE|POSTGRES|MSSQL|SQLA} :","info")
XA_DB_FLAVOR=raw_input()
AUDIT_DB_FLAVOR = XA_DB_FLAVOR
@@ -1530,7 +1530,7 @@ def main(argv):
xa_db_core_file = os.path.join(RANGER_ADMIN_HOME,sqlserver_core_file)
xa_patch_file = os.path.join(RANGER_ADMIN_HOME,sqlserver_patches)
- elif XA_DB_FLAVOR == "SQLANYWHERE":
+ elif XA_DB_FLAVOR == "SQLA":
if not os_name == "WINDOWS" :
if os.environ['LD_LIBRARY_PATH'] == "":
log("[E] ---------- LD_LIBRARY_PATH environment property not defined, aborting installation. ----------", "error")
@@ -1576,7 +1576,7 @@ def main(argv):
audit_sqlObj = SqlServerConf(audit_db_host, SQLSERVER_CONNECTOR_JAR, JAVA_BIN)
audit_db_file = os.path.join(RANGER_ADMIN_HOME,sqlserver_audit_file)
- elif AUDIT_DB_FLAVOR == "SQLANYWHERE":
+ elif AUDIT_DB_FLAVOR == "SQLA":
SQLANYWHERE_CONNECTOR_JAR=CONNECTOR_JAR
audit_sqlObj = SqlAnywhereConf(audit_db_host, SQLANYWHERE_CONNECTOR_JAR, JAVA_BIN)
audit_db_file = os.path.join(RANGER_ADMIN_HOME,sqlanywhere_audit_file)
@@ -1600,7 +1600,7 @@ def main(argv):
logFile("===============================================\n")
xa_sqlObj.create_rangerdb_user(xa_db_root_user, db_user, db_password, xa_db_root_password,dryMode)
xa_sqlObj.create_db(xa_db_root_user, xa_db_root_password, db_name, db_user, db_password,dryMode)
- if not XA_DB_FLAVOR == "SQLANYWHERE":
+ if not XA_DB_FLAVOR == "SQLA":
xa_sqlObj.grant_xa_db_user(xa_db_root_user, db_name, db_user, db_password, xa_db_root_password, is_revoke,dryMode)
audit_sqlObj.create_auditdb_user(xa_db_host, audit_db_host, db_name, audit_db_name, xa_db_root_user, audit_db_root_user, db_user, audit_db_user, xa_db_root_password, audit_db_root_password, db_password, audit_db_password, DBA_MODE,dryMode)
logFile("===============================================\n")
@@ -1610,7 +1610,7 @@ def main(argv):
log("[I] ---------- Creating Ranger Admin database ----------","info")
xa_sqlObj.create_db(xa_db_root_user, xa_db_root_password, db_name, db_user, db_password,dryMode)
log("[I] ---------- Granting permission to Ranger Admin db user ----------","info")
- if not XA_DB_FLAVOR == "SQLANYWHERE":
+ if not XA_DB_FLAVOR == "SQLA":
xa_sqlObj.grant_xa_db_user(xa_db_root_user, db_name, db_user, db_password, xa_db_root_password, is_revoke,dryMode)
# Ranger Admin DB Host AND Ranger Audit DB Host are Different OR Same
if audit_store == "db":
diff --git a/security-admin/scripts/install.properties b/security-admin/scripts/install.properties
index 294b0e8df74..4618ee3b44a 100644
--- a/security-admin/scripts/install.properties
+++ b/security-admin/scripts/install.properties
@@ -23,7 +23,7 @@
PYTHON_COMMAND_INVOKER=python
-#DB_FLAVOR=MYSQL|ORACLE|POSTGRES|MSSQL|SQLANYWHERE
+#DB_FLAVOR=MYSQL|ORACLE|POSTGRES|MSSQL|SQLA
DB_FLAVOR=MYSQL
#
# The executable path to be used to invoke command-line MYSQL
diff --git a/security-admin/scripts/setup.sh b/security-admin/scripts/setup.sh
index a88b264d81a..4fc1cef5428 100755
--- a/security-admin/scripts/setup.sh
+++ b/security-admin/scripts/setup.sh
@@ -303,7 +303,7 @@ sanity_check_files() {
log "[E] ${sqlserver_core_file} does not exists" ; exit 1;
fi
fi
- if [ "${DB_FLAVOR}" == "SQLANYWHERE" ]
+ if [ "${DB_FLAVOR}" == "SQLA" ]
then
if [ "${LD_LIBRARY_PATH}" == "" ]
then
@@ -887,7 +887,7 @@ update_properties() {
updatePropertyToFilePy $propertyName $newPropertyValue $to_file_ranger
fi
- if [ "${DB_FLAVOR}" == "SQLANYWHERE" ]
+ if [ "${DB_FLAVOR}" == "SQLA" ]
then
propertyName=ranger.jpa.jdbc.url
newPropertyValue="jdbc:sqlanywhere:database=${db_name};host=${DB_HOST}"
diff --git a/security-admin/src/main/java/org/apache/ranger/biz/RangerBizUtil.java b/security-admin/src/main/java/org/apache/ranger/biz/RangerBizUtil.java
index a536a1a3462..689e16596be 100644
--- a/security-admin/src/main/java/org/apache/ranger/biz/RangerBizUtil.java
+++ b/security-admin/src/main/java/org/apache/ranger/biz/RangerBizUtil.java
@@ -123,7 +123,7 @@ public RangerBizUtil() {
auditDBType = PropertiesUtil.getProperty("ranger.audit.source.type",
auditDBType).toLowerCase();
-
+ logger.info("java.library.path is " + System.getProperty("java.library.path"));
logger.info("Audit datasource is " + auditDBType);
random = new Random();
}
@@ -1370,7 +1370,9 @@ public static int getDBFlavor() {
return AppConstants.DB_FLAVOR_SQLSERVER;
} else if (StringUtils.containsIgnoreCase(propertyValue, "sqlanywhere")) {
return AppConstants.DB_FLAVOR_SQLANYWHERE;
- } else {
+ } else if (StringUtils.containsIgnoreCase(propertyValue, "sqla")) {
+ return AppConstants.DB_FLAVOR_SQLANYWHERE;
+ }else {
if(logger.isDebugEnabled()) {
logger.debug("DB Falvor could not be determined from property - " + propertyName + "=" + propertyValue);
}
diff --git a/storm-agent/scripts/install.sh b/storm-agent/scripts/install.sh
index 5b7674a3bf5..ab57bb996ee 100644
--- a/storm-agent/scripts/install.sh
+++ b/storm-agent/scripts/install.sh
@@ -258,7 +258,7 @@ then
newPropertyValue="com.microsoft.sqlserver.jdbc.SQLServerDriver"
updatePropertyToFile $propertyName $newPropertyValue $to_file
fi
-if [ "${DB_FLAVOR}" == "SQLANYWHERE" ]
+if [ "${DB_FLAVOR}" == "SQLA" ]
then
audit_db_hostname=`grep '^XAAUDIT.DB.HOSTNAME' ${install_dir}/install.properties | awk -F= '{ print $2 }'`
audit_db_name=`grep '^XAAUDIT.DB.DATABASE_NAME' ${install_dir}/install.properties | awk -F= '{ print $2 }'`
From c2a6eb62f1b4a18852a5dc51804bce20b4e11d17 Mon Sep 17 00:00:00 2001
From: Gautam Borad
Date: Thu, 30 Jul 2015 10:57:04 +0530
Subject: [PATCH 030/202] RANGER-587 : fixed issue: ranger-admin-site.xml not
getting updated when ranger.authentication.method is changed
Signed-off-by: Velmurugan Periasamy
---
security-admin/scripts/setup.sh | 16 ++++++++++++++++
1 file changed, 16 insertions(+)
diff --git a/security-admin/scripts/setup.sh b/security-admin/scripts/setup.sh
index 4fc1cef5428..e0b14c5ae23 100755
--- a/security-admin/scripts/setup.sh
+++ b/security-admin/scripts/setup.sh
@@ -1254,6 +1254,11 @@ do_unixauth_setup() {
ldap_file=$app_home/WEB-INF/classes/conf/ranger-admin-site.xml
if test -f $ldap_file; then
log "[I] $ldap_file file found"
+
+ propertyName=ranger.authentication.method
+ newPropertyValue="${authentication_method}"
+ updatePropertyToFilePy $propertyName $newPropertyValue $ldap_file
+
propertyName=ranger.unixauth.remote.login.enabled
newPropertyValue="${remoteLoginEnabled}"
updatePropertyToFilePy $propertyName $newPropertyValue $ldap_file
@@ -1454,6 +1459,17 @@ do_authentication_setup(){
if [ $authentication_method = "UNIX" ] ; then
do_unixauth_setup
fi
+
+ if [ $authentication_method = "NONE" ] ; then
+ newPropertyValue='NONE'
+ ldap_file=$app_home/WEB-INF/classes/conf/ranger-admin-site.xml
+ if test -f $ldap_file; then
+ propertyName=ranger.authentication.method
+ newPropertyValue="${authentication_method}"
+ updatePropertyToFilePy $propertyName $newPropertyValue $ldap_file
+ fi
+ fi
+
log "[I] Finished setup based on user authentication method=$authentication_method";
}
From 5ed0e6ef75748aba6f8b95d030179b90bff692fe Mon Sep 17 00:00:00 2001
From: Velmurugan Periasamy
Date: Fri, 7 Aug 2015 14:09:21 -0400
Subject: [PATCH 031/202] RANGER-598: Update Ranger config migration script to
work with Ranger 0.5
---
.../bin/import_ranger_to_ambari.py | 0
.../bin/ranger_admin_install.properties | 0
.../doc/README.TXT | 0
.../bin/import_ranger_to_ambari.py | 2253 +++++++++++++++++
.../bin/ranger_admin_install.properties | 33 +
.../doc/README.TXT | 78 +
6 files changed, 2364 insertions(+)
rename migration-util/{ => ambari2.0-hdp2.2-ranger0.40}/bin/import_ranger_to_ambari.py (100%)
mode change 100644 => 100755
rename migration-util/{ => ambari2.0-hdp2.2-ranger0.40}/bin/ranger_admin_install.properties (100%)
rename migration-util/{ => ambari2.0-hdp2.2-ranger0.40}/doc/README.TXT (100%)
mode change 100644 => 100755
create mode 100755 migration-util/ambari2.1-hdp2.3-ranger0.50/bin/import_ranger_to_ambari.py
create mode 100755 migration-util/ambari2.1-hdp2.3-ranger0.50/bin/ranger_admin_install.properties
create mode 100755 migration-util/ambari2.1-hdp2.3-ranger0.50/doc/README.TXT
diff --git a/migration-util/bin/import_ranger_to_ambari.py b/migration-util/ambari2.0-hdp2.2-ranger0.40/bin/import_ranger_to_ambari.py
old mode 100644
new mode 100755
similarity index 100%
rename from migration-util/bin/import_ranger_to_ambari.py
rename to migration-util/ambari2.0-hdp2.2-ranger0.40/bin/import_ranger_to_ambari.py
diff --git a/migration-util/bin/ranger_admin_install.properties b/migration-util/ambari2.0-hdp2.2-ranger0.40/bin/ranger_admin_install.properties
similarity index 100%
rename from migration-util/bin/ranger_admin_install.properties
rename to migration-util/ambari2.0-hdp2.2-ranger0.40/bin/ranger_admin_install.properties
diff --git a/migration-util/doc/README.TXT b/migration-util/ambari2.0-hdp2.2-ranger0.40/doc/README.TXT
old mode 100644
new mode 100755
similarity index 100%
rename from migration-util/doc/README.TXT
rename to migration-util/ambari2.0-hdp2.2-ranger0.40/doc/README.TXT
diff --git a/migration-util/ambari2.1-hdp2.3-ranger0.50/bin/import_ranger_to_ambari.py b/migration-util/ambari2.1-hdp2.3-ranger0.50/bin/import_ranger_to_ambari.py
new file mode 100755
index 00000000000..bc06a65a50f
--- /dev/null
+++ b/migration-util/ambari2.1-hdp2.3-ranger0.50/bin/import_ranger_to_ambari.py
@@ -0,0 +1,2253 @@
+import os
+import sys
+import urllib2
+import base64
+import httplib
+import json
+import time
+from xml.etree import ElementTree as ET
+import datetime
+from subprocess import Popen, PIPE
+import re
+
+
+def port_ranger_admin_installation_to_ambari():
+ print('preparing advanged configurations for ranger')
+ flag_ranger_admin_present, ranger_admin_properties_from_file = get_ranger_admin_install_properties()
+ if flag_ranger_admin_present:
+ print('ranger admin service is installed, making configurations as required by ambari.')
+ if create_ranger_service_in_ambari():
+ print('ranger service is added sucessfully in ambari')
+ if create_ranger_service_components_in_ambari('RANGER_ADMIN'):
+ print('ranger service component is added successfully in ambari')
+ if register_ranger_admin_host_in_ambari():
+ print('ranger admin host is registered successfully in ambari')
+ if add_advanced_ranger_configurations(1, ranger_admin_properties_from_file):
+ print('ranger-admin advanced configurations added successfully in ambari, kindly run ranger-usersync to complete ranger service install')
+ else:
+ print('ranger advanced configurations added failed in ambari')
+ else:
+ print('ranger admin host registration failed in ambari')
+ else:
+ print('ranger service component add failed in ambari')
+ else:
+ print('ranger service add failed in ambari')
+ else:
+ print('ranger admin and usersync services are not installed, not importing configurations to ambari.')
+
+
+def port_ranger_usersync_installation_to_ambari():
+ print ('preparing configurations for ranger user-sync')
+ flag_ranger_usersync_present, ranger_usersync_properties_from_file = get_ranger_usersync_install_properties()
+ if flag_ranger_usersync_present:
+ print('ranger usersync service is installed, making configurations as required by ambari.')
+ if create_ranger_service_components_in_ambari('RANGER_USERSYNC'):
+ print('ranger service component is added successfully in ambari')
+ if register_ranger_usersync_host_in_ambari():
+ print('ranger usersync host is registered successfully in ambari')
+ if add_advanced_ranger_configurations(2, ranger_usersync_properties_from_file):
+ print('ranger advanced configurations added successfully in ambari')
+ if call_ranger_installed():
+ print('ranger service installed successfully in ambari.')
+ else:
+ print('ranger service install failed in ambari')
+ else:
+ print('ranger advanced configurations added failed in ambari')
+ else:
+ print('ranger usersync host registration failed in ambari')
+ else:
+ print('ranger service add failed in ambari')
+ else:
+ print('ranger admin and usersync services are not installed, not importing configurations to ambari.')
+
+
+def port_ranger_kms_installation_to_ambari():
+ print('preparing advanged configurations for ranger-kms')
+ flag_ranger_kms_present, ranger_kms_properties_from_file = get_ranger_kms_install_properties()
+ if flag_ranger_kms_present:
+ print('ranger kms service is installed, making configurations as required by ambari.')
+ if create_ranger_kms_service_in_ambari():
+ print('ranger kms service is added sucessfully in ambari')
+ if create_kms_service_components_in_ambari('RANGER_KMS_SERVER'):
+ print('ranger kms service component is added successfully in ambari')
+ if register_ranger_kms_host_in_ambari():
+ print('ranger kms host is registered successfully in ambari')
+ if add_advanced_ranger_kms_configurations(ranger_kms_properties_from_file):
+ print('ranger kms advanced configurations added successfully in ambari')
+ if call_ranger_kms_installed():
+ print('ranger kms service installed successfully in ambari.')
+ else:
+ print('ranger kms service install failed in ambari')
+ else:
+ print('ranger kms advanced configurations added failed in ambari')
+ else:
+ print('ranger kms host registration failed in ambari')
+ else:
+ print('ranger kms service component add failed in ambari')
+ else:
+ print('ranger kms service add failed in ambari')
+ else:
+ print('ranger kms service is not installed, not importing configurations to ambari.')
+
+
+def create_ranger_service_in_ambari():
+ print('creating ranger admin service in ambari')
+ ranger_create_url = ambari_service_url + '/' + ranger_service_name
+ request_result = call_ambari_api(ranger_create_url, 'POST', ambari_username_password, '')
+ if request_result is not None:
+ response_code = request_result.getcode()
+ response = json.loads(json.JSONEncoder().encode(request_result.read()))
+ if (response_code == 201 and response is not None):
+ print('ranger service created successfully in ambari.')
+ return True
+ elif (response_code == 409 and response is not None):
+ print('ranger service is already created in ambari.')
+ return True
+ else:
+ print('ranger service creation failed in ambari.')
+ return False
+
+
+def create_ranger_kms_service_in_ambari():
+ print('creating ranger kms service in ambari')
+ ranger_create_url = ambari_service_url + '/RANGER_KMS'
+ request_result = call_ambari_api(ranger_create_url, 'POST', ambari_username_password, '')
+ if request_result is not None:
+ response_code = request_result.getcode()
+ response = json.loads(json.JSONEncoder().encode(request_result.read()))
+ if (response_code == 201 and response is not None):
+ print('ranger service created successfully in ambari.')
+ return True
+ elif (response_code == 409 and response is not None):
+ print('ranger service is already created in ambari.')
+ return True
+ else:
+ print('ranger service creation failed in ambari.')
+ return False
+
+def create_ranger_service_components_in_ambari(ranger_service_component_name):
+ print('adding ranger service components in ambari')
+ ranger_service_components = '{"components":[{"ServiceComponentInfo":{"component_name":"' + ranger_service_component_name + '"}}]}'
+ print('creating ranger service in ambari')
+ ranger_service_component_create_url = ambari_service_url + '?ServiceInfo/service_name=' + ranger_service_name
+ request_result = call_ambari_api(ranger_service_component_create_url, 'POST', ambari_username_password, ranger_service_components)
+ if request_result is not None:
+ response_code = request_result.getcode()
+ response = json.loads(json.JSONEncoder().encode(request_result.read()))
+ if (response_code == 201 and response is not None):
+ print('ranger service component : ' + ranger_service_component_name + ', created successfully in ambari.')
+ return True
+ elif (response_code == 409 and response is not None):
+ print('ranger service component : ' + ranger_service_component_name + ', is already present in ambari.')
+ return True
+ else:
+ print('ranger service component creation for : ' + ranger_service_component_name + ', failed in ambari.')
+ return False
+
+def create_kms_service_components_in_ambari(ranger_service_component_name):
+ print('adding ranger service components in ambari')
+ ranger_service_components = '{"components":[{"ServiceComponentInfo":{"component_name":"' + ranger_service_component_name + '"}}]}'
+ print('creating ranger kms service in ambari -> ' + str(ranger_service_components))
+ ranger_service_component_create_url = ambari_service_url + '?ServiceInfo/service_name=RANGER_KMS'
+ print('ranger_service_component_create_url -> ' + str(ranger_service_component_create_url))
+ request_result = call_ambari_api(ranger_service_component_create_url, 'POST', ambari_username_password, ranger_service_components)
+ if request_result is not None:
+ response_code = request_result.getcode()
+ response = json.loads(json.JSONEncoder().encode(request_result.read()))
+ if (response_code == 201 and response is not None):
+ print('ranger service component : ' + ranger_service_component_name + ', created successfully in ambari.')
+ return True
+ elif (response_code == 409 and response is not None):
+ print('ranger service component : ' + ranger_service_component_name + ', is already present in ambari.')
+ return True
+ else:
+ print('ranger service component creation for : ' + ranger_service_component_name + ', failed in ambari.')
+ return False
+
+def register_ranger_admin_host_in_ambari():
+ print('adding ranger servcie components in ambari')
+ print('creating ranger admin service in ambari')
+ ranger_service_component_create_url = ambari_cluster_url + '/hosts/' + ranger_admin_fqdn + '/host_components/' + admin_component_name
+ request_result = call_ambari_api(ranger_service_component_create_url, 'POST', ambari_username_password, '')
+ if request_result is not None:
+ response_code = request_result.getcode()
+ response = json.loads(json.JSONEncoder().encode(request_result.read()))
+ if response_code == 201 and response is not None:
+ print('ranger admin host registered successfully in ambari.')
+ return True
+ elif (response_code == 409 and response is not None):
+ print('ranger admin host is already registered ambari.')
+ return True
+ else:
+ print('ranger admin host registration failed in ambari.')
+ return False
+
+
+def register_ranger_usersync_host_in_ambari():
+ print('adding ranger servcie components in ambari')
+ print('creating ranger admin service in ambari')
+ ranger_host_register_url = ambari_cluster_url + '/hosts/' + ranger_admin_fqdn + '/host_components/' + usersync_component_name
+ request_result = call_ambari_api(ranger_host_register_url, 'POST', ambari_username_password, '')
+ if request_result is not None:
+ response_code = request_result.getcode()
+ response = json.loads(json.JSONEncoder().encode(request_result.read()))
+ if (response_code == 201 and response is not None):
+ print('ranger usersync host registered successfully in ambari.')
+ return True
+ elif (response_code == 409 and response is not None):
+ print('ranger usersync host is already registered ambari.')
+ return True
+ else:
+ print('ranger usersync host registration failed in ambari.')
+ return False
+
+def register_ranger_kms_host_in_ambari():
+ print('adding ranger kms host in ambari')
+ print('creating ranger kms service in ambari')
+ ranger_service_component_create_url = ambari_cluster_url + '/hosts/' + ranger_admin_fqdn + '/host_components/' + "RANGER_KMS_SERVER"
+ request_result = call_ambari_api(ranger_service_component_create_url, 'POST', ambari_username_password, '')
+ if request_result is not None:
+ response_code = request_result.getcode()
+ response = json.loads(json.JSONEncoder().encode(request_result.read()))
+ if response_code == 201 and response is not None:
+ print('ranger kms host registered successfully in ambari.')
+ return True
+ elif (response_code == 409 and response is not None):
+ print('ranger kms host is already registered ambari.')
+ return True
+ else:
+ print('ranger kms host registration failed in ambari.')
+ return False
+
+
+def add_advanced_ranger_configurations(add_admin_or_usersync, ranger_service_properties_from_file):
+ print('creating advanced configurations to be added to ambari.')
+ ranger_config_data = ''
+ advanced_admin_properties = dict()
+ advanced_ranger_site_properties = dict()
+ advanced_ranger_env_properties = dict()
+ advanced_user_sync_properties = dict()
+ advanced_ranger_admin_site_properties = dict()
+ date_time_stamp = getDateTimeNow()
+
+ if (add_admin_or_usersync == 1):
+ if not ((str(ranger_service_properties_from_file['db_root_password']).strip() == '') or
+ (str(ranger_service_properties_from_file['db_root_user']).strip() == '' )) :
+ advanced_admin_properties['DB_FLAVOR'] = ranger_service_properties_from_file['DB_FLAVOR']
+ advanced_admin_properties['SQL_CONNECTOR_JAR'] = ranger_service_properties_from_file['SQL_CONNECTOR_JAR']
+ advanced_admin_properties['db_root_user'] = ranger_service_properties_from_file['db_root_user']
+ advanced_admin_properties['db_root_password'] = ranger_service_properties_from_file['db_root_password']
+ advanced_admin_properties['db_host'] = ranger_service_properties_from_file['db_host']
+ advanced_admin_properties['db_name'] = ranger_service_properties_from_file['db_name']
+ advanced_admin_properties['db_user'] = ranger_service_properties_from_file['ranger.jpa.jdbc.user']
+ advanced_admin_properties['db_password'] = ranger_service_properties_from_file['ranger.jpa.jdbc.password']
+ advanced_admin_properties['audit_db_name'] = ranger_service_properties_from_file['audit_db_name']
+ advanced_admin_properties['audit_db_user'] = ranger_service_properties_from_file['ranger.jpa.audit.jdbc.user']
+ advanced_admin_properties['audit_db_password'] = ranger_service_properties_from_file['ranger.jpa.audit.jdbc.password']
+ advanced_admin_properties['policymgr_external_url'] = ranger_service_properties_from_file['ranger.externalurl']
+
+ advanced_ranger_env_properties['ranger_user'] = 'ranger'
+ advanced_ranger_env_properties['ranger_group'] = 'ranger'
+ advanced_ranger_env_properties['ranger_admin_log_dir'] = '/var/log/ranger/admin'
+ advanced_ranger_env_properties['ranger_usersync_log_dir'] = '/var/log/ranger/usersync'
+ advanced_ranger_env_properties['ranger_admin_username'] = 'amb_ranger_admin'
+ advanced_ranger_env_properties['ranger_admin_password'] = 'ambari123'
+ advanced_ranger_env_properties['admin_username'] = 'admin'
+ advanced_ranger_env_properties['admin_password'] = 'admin'
+ advanced_ranger_env_properties['ranger_pid_dir'] = '/var/run/ranger'
+ advanced_ranger_env_properties['create_db_dbuser'] = 'true'
+ advanced_ranger_env_properties['xml_configurations_supported'] = 'true'
+
+ advanced_ranger_admin_site_properties['ranger.service.host'] = ranger_service_properties_from_file['ranger.service.host']
+ advanced_ranger_admin_site_properties['ranger.service.http.enabled'] = ranger_service_properties_from_file.get('ranger.service.http.enabled','true')
+ advanced_ranger_admin_site_properties['ranger.service.http.port'] = ranger_service_properties_from_file.get('ranger.service.http.port','6080')
+ advanced_ranger_admin_site_properties['ranger.service.https.port'] = ranger_service_properties_from_file.get('ranger.service.https.port','6182')
+ advanced_ranger_admin_site_properties['ranger.service.https.attrib.ssl.enabled'] = ranger_service_properties_from_file.get('ranger.service.https.attrib.ssl.enabled','false')
+ advanced_ranger_admin_site_properties['ranger.service.https.attrib.clientAuth'] = ranger_service_properties_from_file.get('ranger.service.https.attrib.clientAuth','want')
+ advanced_ranger_admin_site_properties['ranger.service.https.attrib.keystore.keyalias'] = ranger_service_properties_from_file.get('ranger.service.https.attrib.keystore.keyalias','rangeradmin')
+ advanced_ranger_admin_site_properties['ranger.service.https.attrib.keystore.pass'] = ranger_service_properties_from_file.get('ranger.service.https.attrib.keystore.pass','xasecure')
+ advanced_ranger_admin_site_properties['ranger.https.attrib.keystore.file'] = ranger_service_properties_from_file.get('ranger.https.attrib.keystore.file','/etc/ranger/admin/conf/ranger-admin-keystore.jks')
+ advanced_ranger_admin_site_properties['ranger.externalurl'] = ranger_service_properties_from_file.get('ranger.externalurl','http://localhost:6080')
+ advanced_ranger_admin_site_properties['ranger.jpa.jdbc.driver'] = ranger_service_properties_from_file.get('ranger.jpa.jdbc.driver','com.mysql.jdbc.Driver')
+ advanced_ranger_admin_site_properties['ranger.jpa.jdbc.url'] = ranger_service_properties_from_file.get('ranger.jpa.jdbc.url','jdbc:mysql://localhost')
+ advanced_ranger_admin_site_properties['ranger.jpa.jdbc.user'] = ranger_service_properties_from_file['ranger.jpa.jdbc.user']
+ advanced_ranger_admin_site_properties['ranger.jpa.jdbc.password'] = ranger_service_properties_from_file['ranger.jpa.jdbc.password']
+ advanced_ranger_admin_site_properties['ranger.jpa.jdbc.credential.alias'] = ranger_service_properties_from_file.get('ranger.jpa.jdbc.credential.alias','rangeradmin')
+ advanced_ranger_admin_site_properties['ranger.credential.provider.path'] = ranger_service_properties_from_file.get('ranger.credential.provider.path','/etc/ranger/admin/rangeradmin.jceks')
+ advanced_ranger_admin_site_properties['ranger.audit.source.type'] = ranger_service_properties_from_file.get('ranger.audit.source.type','db')
+ advanced_ranger_admin_site_properties['ranger.audit.solr.urls'] = ranger_service_properties_from_file.get('ranger.audit.solr.urls','http://solr_host:6083/solr/ranger_audits')
+ advanced_ranger_admin_site_properties['ranger.authentication.method'] = ranger_service_properties_from_file.get('ranger.authentication.method','UNIX')
+ advanced_ranger_admin_site_properties['ranger.ldap.url'] = ranger_service_properties_from_file.get('ranger.ldap.url','ldap://71.127.43.33:389')
+ advanced_ranger_admin_site_properties['ranger.ldap.user.dnpattern'] = ranger_service_properties_from_file.get('ranger.ldap.user.dnpattern','uid={0},ou=users,dc=xasecure,dc=net')
+ advanced_ranger_admin_site_properties['ranger.ldap.group.searchbase'] = ranger_service_properties_from_file.get('ranger.ldap.group.searchbase','ou=groups,dc=xasecure,dc=net')
+ advanced_ranger_admin_site_properties['ranger.ldap.group.searchfilter'] = ranger_service_properties_from_file.get('ranger.ldap.group.searchfilter','(member=uid={0},ou=users,dc=xasecure,dc=net)')
+ advanced_ranger_admin_site_properties['ranger.ldap.group.roleattribute'] = ranger_service_properties_from_file.get('ranger.ldap.group.roleattribute','cn')
+ advanced_ranger_admin_site_properties['ranger.ldap.ad.domain'] = ranger_service_properties_from_file.get('ranger.ldap.ad.domain','localhost')
+ advanced_ranger_admin_site_properties['ranger.ldap.ad.url'] = ranger_service_properties_from_file.get('ranger.ldap.ad.url','ldap://ad.xasecure.net:389')
+ advanced_ranger_admin_site_properties['ranger.jpa.audit.jdbc.driver'] = ranger_service_properties_from_file.get('ranger.jpa.audit.jdbc.driver','{{ranger_jdbc_driver}}')
+ advanced_ranger_admin_site_properties['ranger.jpa.audit.jdbc.url'] = ranger_service_properties_from_file.get('ranger.jpa.audit.jdbc.url','{{audit_jdbc_url}}')
+ advanced_ranger_admin_site_properties['ranger.jpa.audit.jdbc.user'] = ranger_service_properties_from_file.get('ranger.jpa.audit.jdbc.user','{{ranger_audit_db_user}}')
+ advanced_ranger_admin_site_properties['ranger.jpa.audit.jdbc.password'] = ranger_service_properties_from_file.get('ranger.jpa.audit.jdbc.password','_')
+ advanced_ranger_admin_site_properties['ranger.jpa.audit.jdbc.credential.alias'] = ranger_service_properties_from_file.get('ranger.jpa.audit.jdbc.credential.alias','rangeraudit')
+ advanced_ranger_admin_site_properties['ranger.unixauth.remote.login.enabled'] = ranger_service_properties_from_file.get('ranger.unixauth.remote.login.enabled','true')
+ advanced_ranger_admin_site_properties['ranger.unixauth.service.hostname'] = ranger_service_properties_from_file.get('ranger.unixauth.service.hostname','localhost')
+ advanced_ranger_admin_site_properties['ranger.unixauth.service.port'] = ranger_service_properties_from_file.get('ranger.unixauth.service.port','5151')
+ advanced_ranger_admin_site_properties['ranger.jpa.jdbc.dialect'] = ranger_service_properties_from_file.get('ranger.jpa.jdbc.dialect','{{jdbc_dialect}}')
+ advanced_ranger_admin_site_properties['ranger.jpa.audit.jdbc.dialect'] = ranger_service_properties_from_file.get('ranger.jpa.audit.jdbc.dialect','{{jdbc_dialect}')
+ advanced_ranger_admin_site_properties['ranger.audit.solr.zookeepers'] = ranger_service_properties_from_file.get('ranger.audit.solr.zookeepers','NONE')
+ advanced_ranger_admin_site_properties['ranger.audit.solr.username'] = ranger_service_properties_from_file.get('ranger.audit.solr.username','ranger_solr')
+ advanced_ranger_admin_site_properties['ranger.audit.solr.password'] = ranger_service_properties_from_file.get('ranger.audit.solr.password','NONE')
+
+ ranger_config_data = '[{"Clusters":{"desired_config":[{"type":"admin-properties", "service_config_version_note": "Initial configuration for Ranger Admin service" ,"tag":"' + str(
+ date_time_stamp) + '","properties":' + json.dumps(
+ advanced_admin_properties) + ', "properties_attributes": {"final": "true"}},{"type":"ranger-site", "service_config_version_note": "Initial configuration for Ranger Admin service" ,"tag":"' + str(
+ date_time_stamp) + '","properties":' + json.dumps(
+ advanced_ranger_site_properties) + ', "properties_attributes": {"final": "false"}},{"type":"ranger-env", "service_config_version_note": "Initial configuration for Ranger Admin service" ,"tag":"' + str(
+ date_time_stamp) + '","properties":' + json.dumps(advanced_ranger_env_properties) + ', "properties_attributes": {"final": "false"}},{"type":"ranger-admin-site", "service_config_version_note": "Initial configuration for Ranger Admin service" ,"tag":"' + str(
+ date_time_stamp) + '","properties":' + json.dumps(
+ advanced_ranger_admin_site_properties) + ', "properties_attributes": {"final": "false"}}]}}]'
+
+
+ print ('####################### admin_properties configuration :')
+ for each_key in advanced_admin_properties:
+ print str(each_key) + ' = ' + str(advanced_admin_properties[each_key])
+
+ print ('####################### ranger_site_properties configuration :')
+ for each_key in advanced_ranger_site_properties:
+ print str(each_key) + ' = ' + str(advanced_ranger_site_properties[each_key])
+
+ print ('####################### ranger_env_properties configuration :')
+ for each_key in advanced_ranger_env_properties:
+ print str(each_key) + ' = ' + str(advanced_ranger_env_properties[each_key])
+
+ print ('####################### ranger_admin_site_properties configuration :')
+ for each_key in advanced_ranger_env_properties:
+ print str(each_key) + ' = ' + str(advanced_ranger_env_properties[each_key])
+
+
+ else:
+ print('either db_root_user or db_root_password value is missing from ranger_admin_install.properties file, please set appropriate value and run the script again.')
+ sys.exit(1)
+
+ elif (add_admin_or_usersync == 2):
+ advanced_user_sync_properties['ranger.usersync.port'] = ranger_service_properties_from_file['ranger.usersync.port']
+ advanced_user_sync_properties['ranger.usersync.ssl'] = ranger_service_properties_from_file['ranger.usersync.ssl']
+ advanced_user_sync_properties['ranger.usersync.keystore.file'] = ranger_service_properties_from_file['ranger.usersync.keystore.file']
+ advanced_user_sync_properties['ranger.usersync.keystore.password'] = ranger_service_properties_from_file.get('ranger.usersync.keystore.password','UnIx529p')
+ advanced_user_sync_properties['ranger.usersync.truststore.file'] = ranger_service_properties_from_file.get('ranger.usersync.truststore.file','/usr/hdp/current/ranger-usersync/conf/mytruststore.jks')
+ advanced_user_sync_properties['ranger.usersync.truststore.password'] = ranger_service_properties_from_file.get('ranger.usersync.truststore.password','changeit')
+ advanced_user_sync_properties['ranger.usersync.passwordvalidator.path'] = ranger_service_properties_from_file['ranger.usersync.passwordvalidator.path']
+ advanced_user_sync_properties['ranger.usersync.sink.impl.class'] = ranger_service_properties_from_file['ranger.usersync.sink.impl.class']
+ advanced_user_sync_properties['ranger.usersync.policymanager.baseURL'] = ranger_service_properties_from_file['ranger.usersync.policymanager.baseURL']
+ advanced_user_sync_properties['ranger.usersync.policymanager.maxrecordsperapicall'] = ranger_service_properties_from_file['ranger.usersync.policymanager.maxrecordsperapicall']
+ advanced_user_sync_properties['ranger.usersync.policymanager.mockrun'] = ranger_service_properties_from_file['ranger.usersync.policymanager.mockrun']
+ advanced_user_sync_properties['ranger.usersync.unix.minUserId'] = ranger_service_properties_from_file['ranger.usersync.unix.minUserId']
+ advanced_user_sync_properties['ranger.usersync.sleeptimeinmillisbetweensynccycle'] = ranger_service_properties_from_file['ranger.usersync.sleeptimeinmillisbetweensynccycle']
+ advanced_user_sync_properties['ranger.usersync.source.impl.class'] = ranger_service_properties_from_file['ranger.usersync.source.impl.class']
+ advanced_user_sync_properties['ranger.usersync.filesource.file'] = ranger_service_properties_from_file.get('ranger.usersync.filesource.file','/tmp/usergroup.txt')
+ advanced_user_sync_properties['ranger.usersync.filesource.text.delimiter'] = ranger_service_properties_from_file.get('ranger.usersync.filesource.text.delimiter',',')
+ advanced_user_sync_properties['ranger.usersync.ldap.url'] = ranger_service_properties_from_file.get('ranger.usersync.ldap.url','ldap://localhost:389')
+ advanced_user_sync_properties['ranger.usersync.ldap.binddn'] = ranger_service_properties_from_file.get('ranger.usersync.ldap.binddn','cn=admin,dc=xasecure,dc=net')
+ advanced_user_sync_properties['ranger.usersync.ldap.ldapbindpassword'] = ranger_service_properties_from_file['ranger.usersync.ldap.ldapbindpassword']
+ advanced_user_sync_properties['ranger.usersync.ldap.bindalias'] = ranger_service_properties_from_file.get('ranger.usersync.ldap.bindalias','testldapalias')
+ advanced_user_sync_properties['ranger.usersync.ldap.bindkeystore'] = ranger_service_properties_from_file.get('ranger.usersync.ldap.bindkeystore','')
+ advanced_user_sync_properties['ranger.usersync.ldap.searchBase'] = ranger_service_properties_from_file.get('ranger.usersync.ldap.searchBase','dc=hadoop,dc=apache,dc=org')
+ advanced_user_sync_properties['ranger.usersync.ldap.user.searchbase'] = ranger_service_properties_from_file.get('ranger.usersync.ldap.user.searchbase','ou=users,dc=xasecure,dc=net')
+ advanced_user_sync_properties['ranger.usersync.ldap.user.searchscope'] = ranger_service_properties_from_file.get('ranger.usersync.ldap.user.searchscope','sub')
+ advanced_user_sync_properties['ranger.usersync.ldap.user.objectclass'] = ranger_service_properties_from_file.get('ranger.usersync.ldap.user.objectclass','person')
+ advanced_user_sync_properties['ranger.usersync.ldap.user.searchfilter'] = ranger_service_properties_from_file.get('ranger.usersync.ldap.user.searchfilter','empty')
+ advanced_user_sync_properties['ranger.usersync.ldap.user.nameattribute'] = ranger_service_properties_from_file.get('ranger.usersync.ldap.user.nameattribute','cn')
+ advanced_user_sync_properties['ranger.usersync.ldap.user.groupnameattribute'] = ranger_service_properties_from_file.get('ranger.usersync.ldap.user.groupnameattribute','memberof, ismemberof')
+ advanced_user_sync_properties['ranger.usersync.ldap.username.caseconversion'] = ranger_service_properties_from_file.get('ranger.usersync.ldap.username.caseconversion','lower')
+ advanced_user_sync_properties['ranger.usersync.ldap.groupname.caseconversion'] = ranger_service_properties_from_file.get('ranger.usersync.ldap.groupname.caseconversion','lower')
+ advanced_user_sync_properties['ranger.usersync.logdir'] = ranger_service_properties_from_file.get('ranger.usersync.logdir','/var/log/ranger/usersync')
+ advanced_user_sync_properties['ranger.usersync.group.searchenabled'] = ranger_service_properties_from_file.get('ranger.usersync.group.searchenabled','false')
+ advanced_user_sync_properties['ranger.usersync.group.usermapsyncenabled'] = ranger_service_properties_from_file.get('ranger.usersync.group.usermapsyncenabled','false')
+ advanced_user_sync_properties['ranger.usersync.group.searchbase'] = ranger_service_properties_from_file.get('ranger.usersync.group.searchbase',' ')
+ advanced_user_sync_properties['ranger.usersync.group.searchscope'] = ranger_service_properties_from_file.get('ranger.usersync.group.searchscope',' ')
+ advanced_user_sync_properties['ranger.usersync.group.objectclass'] = ranger_service_properties_from_file.get('ranger.usersync.group.objectclass',' ')
+ advanced_user_sync_properties['ranger.usersync.group.searchfilter'] = ranger_service_properties_from_file.get('ranger.usersync.group.searchfilter',' ')
+ advanced_user_sync_properties['ranger.usersync.group.nameattribute'] = ranger_service_properties_from_file.get('ranger.usersync.group.nameattribute',' ')
+ advanced_user_sync_properties['ranger.usersync.group.memberattributename'] = ranger_service_properties_from_file.get('ranger.usersync.group.memberattributename',' ')
+ advanced_user_sync_properties['ranger.usersync.pagedresultsenabled'] = ranger_service_properties_from_file.get('ranger.usersync.pagedresultsenabled','true')
+ advanced_user_sync_properties['ranger.usersync.pagedresultssize'] = ranger_service_properties_from_file.get('ranger.usersync.pagedresultssize','500')
+ advanced_user_sync_properties['ranger.usersync.credstore.filename'] = ranger_service_properties_from_file.get('ranger.usersync.credstore.filename','/usr/hdp/current/ranger-usersync/conf/ugsync.jceks')
+
+ ranger_config_data = '[{"Clusters":{"desired_config":[{"type":"ranger-ugsync-site", "service_config_version_note": "Initial configuration for Ranger Usersync service" ,"tag":"' + str(
+ date_time_stamp) + '","properties":' + json.dumps(advanced_user_sync_properties) + ', "properties_attributes": {"final": "false"}}]}}]'
+
+
+ print ('####################### user_sync_properties configuration :')
+ for each_key in advanced_user_sync_properties:
+ print str(each_key) + ' = ' + str(advanced_user_sync_properties[each_key])
+
+ else:
+ print ('invalid option for to add configuration to ranger.')
+ sys.exit(1)
+
+
+ confirm_configurations = raw_input('please confirm the above configuration values y/n (n) : ')
+ if(confirm_configurations == ''):
+ confirm_configurations = 'n'
+ print ('input registered as ' + str(confirm_configurations))
+
+ if(confirm_configurations.lower() == 'y'):
+ ranger_config_request_url = ambari_cluster_url
+ request_result = call_ambari_api(ranger_config_request_url, 'PUT', ambari_username_password, str(ranger_config_data))
+ if request_result is not None:
+ response_code = request_result.getcode()
+ response = json.loads(json.JSONEncoder().encode(request_result.read()))
+ if response_code == 200 and response is not None:
+ print('ranger advanced configuration added successfully in ambari.')
+ return True
+ else:
+ print('ranger advanced configuration add failed in ambari.')
+ return False
+ else:
+ print('ranger advanced configuration add failed in ambari.')
+ return False
+ else:
+ print ('exiting installation without configuration !')
+ sys.exit(0)
+
+
+def add_advanced_ranger_kms_configurations(ranger_kms_properties_from_file):
+ print('creating advanced configurations to be added to ')
+ advanced_kms_env_properties = dict()
+ advanced_kms_properties = dict()
+ advanced_dbks_site_properties = dict()
+ advanced_kms_site_properties = dict()
+ advanced_ranger_kms_site_properties = dict()
+ advanced_ranger_kms_audit_properties = dict()
+ advanced_ranger_kms_policymgr_ssl_properties = dict()
+ advanced_ranger_kms_security_properties = dict()
+ advanced_kms_log4j_properties = dict()
+ date_time_stamp = getDateTimeNow()
+
+ advanced_kms_env_properties['kms_user'] = 'kms'
+ advanced_kms_env_properties['kms_group'] = 'kms'
+ advanced_kms_env_properties['kms_log_dir'] = '/var/log/ranger/kms'
+ advanced_kms_env_properties['kms_port'] = '9292'
+
+ advanced_kms_properties['REPOSITORY_CONFIG_USERNAME'] = 'keyadmin'
+ advanced_kms_properties['REPOSITORY_CONFIG_PASSWORD'] = 'keyadmin'
+ advanced_kms_properties['DB_FLAVOR'] = ranger_kms_properties_from_file.get('DB_FLAVOR','MYSQL')
+ advanced_kms_properties['SQL_CONNECTOR_JAR'] = ranger_kms_properties_from_file.get('SQL_CONNECTOR_JAR','/usr/share/java/mysql-connector-java.jar')
+ advanced_kms_properties['db_root_user'] = ranger_kms_properties_from_file.get('db_root_user','root')
+ advanced_kms_properties['db_root_password'] = ranger_kms_properties_from_file.get('db_root_password','')
+ advanced_kms_properties['db_host'] = ranger_kms_properties_from_file.get('db_host','localhost')
+ advanced_kms_properties['db_name'] = ranger_kms_properties_from_file.get('db_name','rangerkms')
+ advanced_kms_properties['db_user'] = ranger_kms_properties_from_file.get('ranger.ks.jpa.jdbc.user','rangerkms')
+ advanced_kms_properties['db_password'] = ranger_kms_properties_from_file.get('ranger.ks.jpa.jdbc.password','')
+ advanced_kms_properties['KMS_MASTER_KEY_PASSWD'] = ranger_kms_properties_from_file.get('KMS_MASTER_KEY_PASSWD','')
+
+
+ advanced_dbks_site_properties['hadoop.kms.blacklist.DECRYPT_EEK'] = ranger_kms_properties_from_file.get('hadoop.kms.blacklist.DECRYPT_EEK','hdfs')
+ advanced_dbks_site_properties['ranger.db.encrypt.key.password'] = ranger_kms_properties_from_file.get('ranger.db.encrypt.key.password','_')
+ advanced_dbks_site_properties['ranger.ks.jpa.jdbc.url'] = ranger_kms_properties_from_file.get('ranger.ks.jpa.jdbc.url','{{db_jdbc_url}}')
+ advanced_dbks_site_properties['ranger.ks.jpa.jdbc.user'] = ranger_kms_properties_from_file.get('ranger.ks.jpa.jdbc.user','{{db_user}}')
+ advanced_dbks_site_properties['ranger.ks.jpa.jdbc.password'] = ranger_kms_properties_from_file.get('ranger.ks.jpa.jdbc.password','_')
+ advanced_dbks_site_properties['ranger.ks.jpa.jdbc.credential.provider.path'] = ranger_kms_properties_from_file.get('ranger.ks.jpa.jdbc.credential.provider.path','/etc/ranger/kms/rangerkms.jceks')
+ advanced_dbks_site_properties['ranger.ks.jpa.jdbc.credential.alias'] = ranger_kms_properties_from_file.get('ranger.ks.jpa.jdbc.credential.alias','ranger.ks.jdbc.password')
+ advanced_dbks_site_properties['ranger.ks.masterkey.credential.alias'] = ranger_kms_properties_from_file.get('ranger.ks.masterkey.credential.alias','ranger.ks.masterkey.password')
+ advanced_dbks_site_properties['ranger.ks.jpa.jdbc.dialect'] = ranger_kms_properties_from_file.get('ranger.ks.jpa.jdbc.dialect','{{jdbc_dialect}}')
+ advanced_dbks_site_properties['ranger.ks.jpa.jdbc.driver'] = ranger_kms_properties_from_file.get('ranger.ks.jpa.jdbc.driver','{{db_jdbc_driver}}')
+ advanced_dbks_site_properties['ranger.ks.jdbc.sqlconnectorjar'] = ranger_kms_properties_from_file.get('ranger.ks.jdbc.sqlconnectorjar','{{driver_curl_target}}')
+
+
+ advanced_kms_site_properties['hadoop.kms.key.provider.uri'] = ranger_kms_properties_from_file.get('hadoop.kms.key.provider.uri','dbks://http@localhost:9292/kms')
+ advanced_kms_site_properties['hadoop.security.keystore.JavaKeyStoreProvider.password'] = ranger_kms_properties_from_file.get('hadoop.security.keystore.JavaKeyStoreProvider.password','none')
+ advanced_kms_site_properties['hadoop.kms.cache.enable'] = ranger_kms_properties_from_file.get('hadoop.kms.cache.enable','true')
+ advanced_kms_site_properties['hadoop.kms.cache.timeout.ms'] = ranger_kms_properties_from_file.get('hadoop.kms.cache.timeout.ms','600000')
+ advanced_kms_site_properties['hadoop.kms.current.key.cache.timeout.ms'] = ranger_kms_properties_from_file.get('hadoop.kms.current.key.cache.timeout.ms','30000')
+ advanced_kms_site_properties['hadoop.kms.audit.aggregation.window.ms'] = ranger_kms_properties_from_file.get('hadoop.kms.audit.aggregation.window.ms','10000')
+ advanced_kms_site_properties['hadoop.kms.authentication.type'] = ranger_kms_properties_from_file.get('hadoop.kms.authentication.type','simple')
+ advanced_kms_site_properties['hadoop.kms.authentication.kerberos.keytab'] = ranger_kms_properties_from_file.get('hadoop.kms.authentication.kerberos.keytab','${user.home}/kms.keytab')
+ advanced_kms_site_properties['hadoop.kms.authentication.kerberos.principal'] = ranger_kms_properties_from_file.get('hadoop.kms.authentication.kerberos.principal','HTTP/localhost')
+ advanced_kms_site_properties['hadoop.kms.authentication.kerberos.name.rules'] = ranger_kms_properties_from_file.get('hadoop.kms.authentication.kerberos.name.rules','DEFAULT')
+ advanced_kms_site_properties['hadoop.kms.authentication.signer.secret.provider'] = ranger_kms_properties_from_file.get('hadoop.kms.authentication.signer.secret.provider','random')
+ advanced_kms_site_properties['hadoop.kms.authentication.signer.secret.provider.zookeeper.path'] = ranger_kms_properties_from_file.get('hadoop.kms.authentication.signer.secret.provider.zookeeper.path','/hadoop-kms/hadoop-auth-signature-secret')
+ advanced_kms_site_properties['hadoop.kms.authentication.signer.secret.provider.zookeeper.auth.type'] = ranger_kms_properties_from_file.get('hadoop.kms.authentication.signer.secret.provider.zookeeper.auth.type','kerberos')
+ advanced_kms_site_properties['hadoop.kms.authentication.signer.secret.provider.zookeeper.kerberos.keytab'] = ranger_kms_properties_from_file.get('/etc/hadoop/conf/kms.keytab','/etc/hadoop/conf/kms.keytab')
+ advanced_kms_site_properties['hadoop.kms.authentication.signer.secret.provider.zookeeper.kerberos.principal'] = ranger_kms_properties_from_file.get('hadoop.kms.authentication.signer.secret.provider.zookeeper.kerberos.principal','kms/#HOSTNAME#')
+ advanced_kms_site_properties['hadoop.kms.security.authorization.manager'] = ranger_kms_properties_from_file.get('hadoop.kms.security.authorization.manager','org.apache.ranger.authorization.kms.authorizer.RangerKmsAuthorizer')
+
+
+ advanced_ranger_kms_site_properties['ranger.service.host'] = ranger_kms_properties_from_file.get('ranger.service.host','{{kms_host}}')
+ advanced_ranger_kms_site_properties['ranger.service.http.port'] = ranger_kms_properties_from_file.get('ranger.service.http.port','{{kms_port}}')
+ advanced_ranger_kms_site_properties['ranger.service.https.port'] = ranger_kms_properties_from_file.get('ranger.service.https.port','9393')
+ advanced_ranger_kms_site_properties['ranger.service.shutdown.port'] = ranger_kms_properties_from_file.get('ranger.service.shutdown.port','7085')
+ advanced_ranger_kms_site_properties['ranger.contextName'] = ranger_kms_properties_from_file.get('ranger.contextName','/kms')
+ advanced_ranger_kms_site_properties['xa.webapp.dir'] = ranger_kms_properties_from_file.get('xa.webapp.dir','./webapp')
+ advanced_ranger_kms_site_properties['ranger.service.https.attrib.ssl.enabled'] = ranger_kms_properties_from_file.get('ranger.service.https.attrib.ssl.enabled','false')
+
+
+ advanced_ranger_kms_audit_properties['xasecure.audit.is.enabled'] = ranger_kms_properties_from_file.get('xasecure.audit.is.enabled','true')
+ advanced_ranger_kms_audit_properties['xasecure.audit.destination.db'] = ranger_kms_properties_from_file.get('xasecure.audit.db.is.enabled','false')
+ advanced_ranger_kms_audit_properties['xasecure.audit.destination.db.jdbc.url'] = ranger_kms_properties_from_file.get('xasecure.audit.jpa.javax.persistence.jdbc.url','{{audit_jdbc_url}}')
+ advanced_ranger_kms_audit_properties['xasecure.audit.destination.db.user'] = ranger_kms_properties_from_file.get('xasecure.audit.jpa.javax.persistence.jdbc.user','{{xa_audit_db_user}}')
+ advanced_ranger_kms_audit_properties['xasecure.audit.destination.db.password'] = ranger_kms_properties_from_file.get('xasecure.audit.jpa.javax.persistence.jdbc.password','crypted')
+ advanced_ranger_kms_audit_properties['xasecure.audit.destination.db.jdbc.driver'] = ranger_kms_properties_from_file.get('xasecure.audit.jpa.javax.persistence.jdbc.driver','{{jdbc_driver}}')
+ advanced_ranger_kms_audit_properties['xasecure.audit.credential.provider.file'] = ranger_kms_properties_from_file.get('xasecure.audit.credential.provider.file','jceks://file{{credential_file}}')
+ advanced_ranger_kms_audit_properties['xasecure.audit.destination.db.batch.filespool.dir'] = ranger_kms_properties_from_file.get('xasecure.audit.destination.db.batch.filespool.dir','/var/log/ranger/kms/audit/db/spool')
+ advanced_ranger_kms_audit_properties['xasecure.audit.destination.hdfs'] = ranger_kms_properties_from_file.get('xasecure.audit.destination.hdfs','true')
+ advanced_ranger_kms_audit_properties['xasecure.audit.destination.hdfs.dir'] = ranger_kms_properties_from_file.get('xasecure.audit.destination.hdfs.dir','hdfs://NAMENODE_HOSTNAME:8020/ranger/audit')
+ advanced_ranger_kms_audit_properties['xasecure.audit.destination.hdfs.batch.filespool.dir'] = ranger_kms_properties_from_file.get('xasecure.audit.destination.hdfs.batch.filespool.dir','/var/log/ranger/kms/audit/hdfs/spool')
+ advanced_ranger_kms_audit_properties['xasecure.audit.destination.solr'] = ranger_kms_properties_from_file.get('xasecure.audit.destination.solr','true')
+ advanced_ranger_kms_audit_properties['xasecure.audit.destination.solr.urls'] = ranger_kms_properties_from_file.get('xasecure.audit.destination.solr.urls','{{ranger_audit_solr_urls}}')
+ advanced_ranger_kms_audit_properties['xasecure.audit.destination.solr.zookeepers'] = ranger_kms_properties_from_file.get('xasecure.audit.destination.solr.zookeepers','none')
+ advanced_ranger_kms_audit_properties['xasecure.audit.destination.solr.batch.filespool.dir'] = ranger_kms_properties_from_file.get('xasecure.audit.destination.solr.batch.filespool.dir','/var/log/ranger/kms/audit/solr/spool')
+ advanced_ranger_kms_audit_properties['xasecure.audit.provider.summary.enabled'] = ranger_kms_properties_from_file.get('xasecure.audit.provider.summary.enabled','false')
+
+
+ advanced_ranger_kms_policymgr_ssl_properties['xasecure.policymgr.clientssl.keystore'] = ranger_kms_properties_from_file.get('xasecure.policymgr.clientssl.keystore','/usr/hdp/current/ranger-kms/conf/ranger-plugin-keystore.jks')
+ advanced_ranger_kms_policymgr_ssl_properties['xasecure.policymgr.clientssl.keystore.password'] = ranger_kms_properties_from_file.get('xasecure.policymgr.clientssl.keystore.password','myKeyFilePassword')
+ advanced_ranger_kms_policymgr_ssl_properties['xasecure.policymgr.clientssl.truststore'] = ranger_kms_properties_from_file.get('xasecure.policymgr.clientssl.truststore','/usr/hdp/current/ranger-kms/conf/ranger-plugin-truststore.jks')
+ advanced_ranger_kms_policymgr_ssl_properties['xasecure.policymgr.clientssl.truststore.password'] = ranger_kms_properties_from_file.get('xasecure.policymgr.clientssl.truststore.password','changeit')
+ advanced_ranger_kms_policymgr_ssl_properties['xasecure.policymgr.clientssl.keystore.credential.file'] = ranger_kms_properties_from_file.get('xasecure.policymgr.clientssl.keystore.credential.file','jceks://file{{credential_file}}')
+ advanced_ranger_kms_policymgr_ssl_properties['xasecure.policymgr.clientssl.truststore.credential.file'] = ranger_kms_properties_from_file.get('xasecure.policymgr.clientssl.truststore.credential.file','jceks://file{{credential_file}}')
+
+
+ advanced_ranger_kms_security_properties['ranger.plugin.kms.service.name'] = ranger_kms_properties_from_file.get('ranger.plugin.kms.service.name','{{repo_name}}')
+ advanced_ranger_kms_security_properties['ranger.plugin.kms.policy.source.impl'] = ranger_kms_properties_from_file.get('ranger.plugin.kms.policy.source.impl','org.apache.ranger.admin.client.RangerAdminRESTClient')
+ advanced_ranger_kms_security_properties['ranger.plugin.kms.policy.rest.url'] = ranger_kms_properties_from_file.get('ranger.plugin.kms.policy.rest.url','{{policymgr_mgr_url}}')
+ advanced_ranger_kms_security_properties['ranger.plugin.kms.policy.rest.ssl.config.file'] = ranger_kms_properties_from_file.get('ranger.plugin.kms.policy.rest.ssl.config.file','/etc/ranger/kms/conf/ranger-policymgr-ssl.xml')
+ advanced_ranger_kms_security_properties['ranger.plugin.kms.policy.pollIntervalMs'] = ranger_kms_properties_from_file.get('ranger.plugin.kms.policy.pollIntervalMs','30000')
+ advanced_ranger_kms_security_properties['ranger.plugin.kms.policy.cache.dir'] = ranger_kms_properties_from_file.get('ranger.plugin.kms.policy.cache.dir','/etc/ranger/{{repo_name}}/policycache')
+
+ advanced_kms_log4j_properties['content'] = ranger_kms_properties_from_file.get('kms.log4j.properties','')
+
+
+ kms_config_data = '[{"Clusters":{"desired_config":[{"type":"kms-properties", "service_config_version_note": "Initial configuration for Ranger KMS service" ,"tag":"' + str(
+ date_time_stamp) + '","properties":' + json.dumps(
+ advanced_kms_properties) + ', "properties_attributes": {"final": "true"}},{"type":"kms-site", "service_config_version_note": "Initial configuration for Ranger KMS service" ,"tag":"' + str(
+ date_time_stamp) + '","properties":' + json.dumps(
+ advanced_kms_site_properties) + ', "properties_attributes": {"final": "false"}},{"type":"kms-env", "service_config_version_note": "Initial configuration for Ranger KMS service" ,"tag":"' + str(
+ date_time_stamp) + '","properties":' + json.dumps(advanced_kms_env_properties) + ', "properties_attributes": {"final": "false"}},{"type":"dbks-site", "service_config_version_note": "Initial configuration for Ranger KMS service" ,"tag":"' + str(
+ date_time_stamp) + '","properties":' + json.dumps(advanced_dbks_site_properties) + ', "properties_attributes": {"final": "false"}},{"type":"ranger-kms-site", "service_config_version_note": "Initial configuration for Ranger KMS service" ,"tag":"' + str(
+ date_time_stamp) + '","properties":' + json.dumps(advanced_ranger_kms_site_properties) + ', "properties_attributes": {"final": "false"}},{"type":"ranger-kms-audit", "service_config_version_note": "Initial configuration for Ranger KMS service" ,"tag":"' + str(
+ date_time_stamp) + '","properties":' + json.dumps(advanced_ranger_kms_audit_properties) + ', "properties_attributes": {"final": "false"}},{"type":"ranger-kms-policymgr-ssl", "service_config_version_note": "Initial configuration for Ranger KMS service" ,"tag":"' + str(
+ date_time_stamp) + '","properties":' + json.dumps(advanced_ranger_kms_policymgr_ssl_properties) + ', "properties_attributes": {"final": "false"}},{"type":"kms-log4j", "service_config_version_note": "Initial configuration for Ranger KMS service" ,"tag":"' + str(
+ date_time_stamp) + '","properties":' + json.dumps(advanced_kms_log4j_properties) + ', "properties_attributes": {"final": "false"}},{"type":"ranger-kms-security", "service_config_version_note": "Initial configuration for Ranger KMS service" ,"tag":"' + str(
+ date_time_stamp) + '","properties":' + json.dumps(advanced_ranger_kms_security_properties) + ', "properties_attributes": {"final": "false"}}]}}]'
+
+
+ print ('####################### kms_properties configuration :')
+ for each_key in advanced_kms_properties:
+ print str(each_key) + ' = ' + str(advanced_kms_properties[each_key])
+
+ print ('####################### kms_site_properties configuration :')
+ for each_key in advanced_kms_site_properties:
+ print str(each_key) + ' = ' + str(advanced_kms_site_properties[each_key])
+
+ print ('####################### kms_env_properties configuration :')
+ for each_key in advanced_kms_env_properties:
+ print str(each_key) + ' = ' + str(advanced_kms_env_properties[each_key])
+
+ print ('####################### ranger_kms_site_properties configuration :')
+ for each_key in advanced_ranger_kms_site_properties:
+ print str(each_key) + ' = ' + str(advanced_ranger_kms_site_properties[each_key])
+
+ print ('####################### kms_dbks_site_properties configuration :')
+ for each_key in advanced_dbks_site_properties:
+ print str(each_key) + ' = ' + str(advanced_dbks_site_properties[each_key])
+
+ print ('####################### ranger_kms_audit_properties configuration :')
+ for each_key in advanced_ranger_kms_audit_properties:
+ print str(each_key) + ' = ' + str(advanced_ranger_kms_audit_properties[each_key])
+
+ print ('####################### ranger_kms_policymgr_ssl_properties configuration :')
+ for each_key in advanced_ranger_kms_policymgr_ssl_properties:
+ print str(each_key) + ' = ' + str(advanced_ranger_kms_policymgr_ssl_properties[each_key])
+
+
+ print ('####################### ranger_kms_security_properties configuration :')
+ for each_key in advanced_ranger_kms_security_properties:
+ print str(each_key) + ' = ' + str(advanced_ranger_kms_security_properties[each_key])
+
+ print ('####################### ranger_kms_log4j_properties configuration :')
+ for each_key in advanced_kms_log4j_properties:
+ print str(each_key) + ' = ' + str(advanced_kms_log4j_properties[each_key])
+
+
+ confirm_configurations = raw_input('please confirm the above configuration values y/n (n) : ')
+ if(confirm_configurations == ''):
+ confirm_configurations = 'n'
+ print ('input registered as ' + str(confirm_configurations))
+
+ if(confirm_configurations.lower() == 'y'):
+ ranger_config_request_url = ambari_cluster_url
+ request_result = call_ambari_api(ranger_config_request_url, 'PUT', ambari_username_password, str(kms_config_data))
+ if request_result is not None:
+ response_code = request_result.getcode()
+ response = json.loads(json.JSONEncoder().encode(request_result.read()))
+ if response_code == 200 and response is not None:
+ print('ranger kms advanced configuration added successfully in ambari.')
+ return True
+ else:
+ print('ranger kms advanced configuration add failed in ambari.')
+ return False
+ else:
+ print('ranger kms advanced configuration add failed in ambari.')
+ return False
+ else:
+ print ('exiting installation without configuration !')
+ sys.exit(0)
+
+
+
+def call_ranger_installed():
+ print('changing state of ranger services from init to installed.')
+ ranger_state_change_request = '{"RequestInfo":{"context":"Install Ranger Service","operation_level":{"level":"CLUSTER","cluster_name":"' + str(
+ cluster_name) + '"}},"Body":{"ServiceInfo":{"state":"INSTALLED"}}}'
+ ranger_state_change_url = ambari_service_url + '?ServiceInfo/state=INIT'
+ request_result = call_ambari_api(ranger_state_change_url, 'PUT', ambari_username_password, ranger_state_change_request)
+ if request_result is not None:
+ response_code = request_result.getcode()
+ response = json.loads(json.JSONEncoder().encode(request_result.read()))
+ if (response_code == 200 and response is not None):
+ print('ranger state changed to install successfully in ambari.')
+ return True
+ if (response_code == 409 and response is not None):
+ print('ranger is already installed in ambari.')
+ return True
+ if response_code == 202 and response is not None:
+ print('ranger state changed to install posted in ambari, checking for updated status waiting for 30 seconds')
+ parsed_response = json.loads(response)
+ response_href_url = parsed_response['href']
+ response_request_id = parsed_response['Requests']['id']
+ response_status = parsed_response['Requests']['status']
+ if response_status != 'Installed':
+ print('Received response but status is not installed, verifying installation to be successful.')
+ flag_ranger_installed = True
+ time.sleep(30)
+ while flag_ranger_installed:
+ print('checking request status')
+ ambari_request_url = ambari_cluster_url + '/requests/' + str(response_request_id)
+ request_status_result = call_ambari_api(ambari_request_url, 'GET', ambari_username_password, '')
+ if request_status_result is not None:
+ response_code = request_status_result.getcode()
+ response_status = json.loads(json.JSONEncoder().encode(request_status_result.read()))
+ if (response_code == 200 and 'FAILED' in response_status):
+ print('ranger install failed in ambari.')
+ flag_ranger_installed = True
+ if (response_code == 200 ):
+ print('ranger install is pending in ambari.')
+ flag_ranger_installed = True
+ if (response_code == 200 and ('PENDING' in response_status or 'INTERNAL_REQUEST' in response_status)):
+ print('ranger install is pending in ambari.')
+ flag_ranger_installed = True
+ if (response_code == 200 and 'COMPLETED' in response_status):
+ print('ranger installed successfully in ambari.')
+ flag_ranger_installed = False
+ else:
+ flag_ranger_installed = True
+ return not flag_ranger_installed
+ else:
+ print('ranger state changed to install failed in ambari.')
+ return False
+
+def call_ranger_kms_installed():
+ print('changing state of ranger services from init to installed.')
+ ranger_state_change_request = '{"RequestInfo":{"context":"Install Ranger KMS Service","operation_level":{"level":"CLUSTER","cluster_name":"' + str(
+ cluster_name) + '"}},"Body":{"ServiceInfo":{"state":"INSTALLED"}}}'
+ ranger_state_change_url = ambari_service_url + '?ServiceInfo/state=INIT'
+ request_result = call_ambari_api(ranger_state_change_url, 'PUT', ambari_username_password, ranger_state_change_request)
+ if request_result is not None:
+ response_code = request_result.getcode()
+ response = json.loads(json.JSONEncoder().encode(request_result.read()))
+ if (response_code == 200 and response is not None):
+ print('ranger state changed to install successfully in ambari.')
+ return True
+ if (response_code == 409 and response is not None):
+ print('ranger is already installed in ambari.')
+ return True
+ if response_code == 202 and response is not None:
+ print('ranger state changed to install posted in ambari, checking for updated status waiting for 30 seconds')
+ parsed_response = json.loads(response)
+ response_href_url = parsed_response['href']
+ response_request_id = parsed_response['Requests']['id']
+ response_status = parsed_response['Requests']['status']
+ if response_status != 'Installed':
+ print('Received response but status is not installed, verifying installation to be successful.')
+ flag_ranger_installed = True
+ time.sleep(30)
+ while flag_ranger_installed:
+ print('checking request status')
+ ambari_request_url = ambari_cluster_url + '/requests/' + str(response_request_id)
+ request_status_result = call_ambari_api(ambari_request_url, 'GET', ambari_username_password, '')
+ if request_status_result is not None:
+ response_code = request_status_result.getcode()
+ response_status = json.loads(json.JSONEncoder().encode(request_status_result.read()))
+ if (response_code == 200 and 'FAILED' in response_status):
+ print('ranger install failed in ambari.')
+ flag_ranger_installed = True
+ if (response_code == 200 ):
+ print('ranger kms install is pending in ambari.')
+ flag_ranger_installed = True
+ if (response_code == 200 and ('PENDING' in response_status or 'INTERNAL_REQUEST' in response_status)):
+ print('ranger kms install is pending in ambari.')
+ flag_ranger_installed = True
+ if (response_code == 200 and 'COMPLETED' in response_status):
+ print('ranger kms installed successfully in ambari.')
+ flag_ranger_installed = False
+ else:
+ flag_ranger_installed = True
+ return not flag_ranger_installed
+ else:
+ print('ranger kms state changed to install failed in ambari.')
+ return False
+
+
+def get_ranger_usersync_install_properties():
+ print('preparing advanced configurations for ranger User-sync')
+ flag_hadoop_present = check_hadoop_dir_present(hdp_current_dir)
+ flag_ranger_usersync_present = False
+ ranger_usersync_current_dir = os.path.join(hdp_current_dir, 'ranger-usersync')
+ ranger_usersync_properties_from_file = dict()
+ print('checking for ranger-usersync service to be present')
+ flag_ranger_usersync_present, ranger_usersync__installed_version = check_ranger_usersync_install(ranger_usersync_current_dir)
+ if flag_ranger_usersync_present:
+ print('ranger usersync is installed, getting existing properties for ambari import')
+ print('got ranger usersync values from install.properties file, need to configure ambari for ranger service.')
+ ranger_usersync_properties_from_file = get_additional_properties_for_usersync(ranger_usersync_properties_from_file)
+ return flag_ranger_usersync_present, ranger_usersync_properties_from_file
+
+
+def get_ranger_admin_install_properties():
+ ranger_admin_current_dir = os.path.join(hdp_current_dir, 'ranger-admin')
+ flag_hadoop_present = check_hadoop_dir_present(hdp_current_dir)
+ flag_ranger_admin_present = False
+ ranger_admin_properties_from_file = dict()
+
+ if flag_hadoop_present:
+ print('hadoop directory is present, checking ranger admin installation.')
+ flag_ranger_admin_present, ranger_admin_installed_version = check_ranger_admin_install(ranger_admin_current_dir)
+
+ if flag_ranger_admin_present:
+ print('ranger admin is present.getting existing configurations to port to ambari.')
+ if os.path.isfile("ranger_admin_install.properties"):
+ print('ranger_install_properties_path exists, getting existing properties for ambari port')
+ ranger_admin_properties_from_file = import_properties_from_file("ranger_admin_install.properties")
+ if not (ranger_admin_properties_from_file['db_root_user'] == '' or ranger_admin_properties_from_file['db_root_password'] == ''):
+ print 'db_root_username and db_root_password are not blank.'
+ print 'value for db_root_user = ' + str(ranger_admin_properties_from_file['db_root_user'])
+ print 'value for db_root_password = ' + str(ranger_admin_properties_from_file['db_root_password'])
+ else:
+ print 'db_root_username or db_root_password are blank, please provide proper values in ranger_admin_install.properties. exiting installation without any changes.'
+ sys.exit(1)
+
+ print('got ranger admin values from ranger_admin_install.properties file, need to configure ambari for ranger service.')
+ print('getting additional properties required by ranger services')
+ ranger_admin_properties_from_file = get_additional_properties_for_admin(ranger_admin_properties_from_file)
+
+ return flag_ranger_admin_present, ranger_admin_properties_from_file
+
+def get_ranger_kms_install_properties():
+ ranger_kms_current_dir = os.path.join(hdp_current_dir, 'ranger-kms')
+ flag_hadoop_present = check_hadoop_dir_present(hdp_current_dir)
+ flag_ranger_kms_present = False
+ ranger_kms_properties_from_file = dict()
+
+ if flag_hadoop_present:
+ print('hadoop directory is present, checking ranger kms installation.')
+ flag_ranger_kms_present, ranger_kms_installed_version = check_ranger_kms_install(ranger_kms_current_dir)
+
+ if flag_ranger_kms_present:
+ print('ranger kms is present.getting existing configurations to port to ambari.')
+ if os.path.isfile("ranger_admin_install.properties"):
+ print('ranger_install_properties_path exists, getting existing properties for ambari port')
+ ranger_kms_properties_from_file = import_properties_from_file("ranger_admin_install.properties")
+ if not (ranger_kms_properties_from_file['db_root_user'] == '' or ranger_kms_properties_from_file['db_root_password'] == ''):
+ print 'db_root_username and db_root_password are not blank.'
+ print 'value for db_root_user = ' + str(ranger_kms_properties_from_file['db_root_user'])
+ print 'value for db_root_password = ' + str(ranger_kms_properties_from_file['db_root_password'])
+ else:
+ print 'db_root_username or db_root_password are blank, please provide proper values in ranger_admin_install.properties. exiting installation without any changes.'
+ sys.exit(1)
+
+ print('got ranger admin values from ranger_admin_install.properties file, need to configure ambari for ranger service.')
+ print('getting additional properties required by ranger services')
+ ranger_kms_properties_from_file = get_additional_properties_for_kms(ranger_kms_properties_from_file)
+
+ return flag_ranger_kms_present, ranger_kms_properties_from_file
+
+
+def check_hadoop_dir_present(hdp_current_dir_path):
+ flag_hadoop_dir_present = False
+ if os.path.isdir(hdp_current_dir_path):
+ print('hadoop is installed.')
+ flag_hadoop_dir_present = True
+ return flag_hadoop_dir_present
+
+
+def check_ranger_admin_install(ranger_admin_current_dir):
+ flag_ranger_dir_present = False
+ ranger_current_installed_version = ''
+ print('checking ranger service path folder')
+ if os.path.isdir(ranger_admin_current_dir):
+ print('ranger admin is installed.')
+ if os.path.islink(ranger_admin_current_dir):
+ flag_ranger_dir_present = True
+ print('ranger admin link found getting current version from link.')
+ ranger_home_path = os.path.realpath(ranger_admin_current_dir)
+ ranger_current_installed_version = ranger_home_path.split('/')[4]
+ return flag_ranger_dir_present, ranger_current_installed_version
+
+
+def check_ranger_usersync_install(ranger_usersync_current_dir):
+ flag_ranger_dir_present = False
+ ranger_current_installed_version = ''
+ print('checking ranger service path folder')
+ if os.path.isdir(ranger_usersync_current_dir):
+ print('ranger user-sync is installed.')
+ if os.path.islink(ranger_usersync_current_dir):
+ flag_ranger_dir_present = True
+ print('ranger admin link found getting current version from link.')
+ ranger_home_path = os.path.realpath(ranger_usersync_current_dir)
+ ranger_current_installed_version = ranger_home_path.split('/')[4]
+ return flag_ranger_dir_present, ranger_current_installed_version
+
+
+def check_ranger_kms_install(ranger_kms_current_dir):
+ flag_ranger_dir_present = False
+ ranger_current_installed_version = ''
+ print('checking ranger kms service path folder')
+ if os.path.isdir(ranger_kms_current_dir):
+ print('ranger kms is installed.')
+ if os.path.islink(ranger_kms_current_dir):
+ flag_ranger_dir_present = True
+ print('ranger kms link found getting current version from link.')
+ ranger_home_path = os.path.realpath(ranger_kms_current_dir)
+ ranger_current_installed_version = ranger_home_path.split('/')[4]
+ return flag_ranger_dir_present, ranger_current_installed_version
+
+
+def get_additional_properties_for_admin(ranger_admin_properties_from_file):
+ ranger_conf_path = '/etc/ranger/admin/conf'
+ ranger_admin_default_site_xml_properties = os.path.join(ranger_conf_path,'ranger-admin-default-site.xml')
+ ranger_admin_site_xml_properties = os.path.join(ranger_conf_path,'ranger-admin-site.xml')
+ try:
+
+ ranger_admin_properties_from_file = import_properties_from_xml(ranger_admin_default_site_xml_properties, ranger_admin_properties_from_file)
+ ranger_admin_properties_from_file = import_properties_from_xml(ranger_admin_site_xml_properties, ranger_admin_properties_from_file)
+ except Exception, e:
+ print "Error loading ranger-admin properties from xml files : ", str(e)
+
+ print('getting db flavor, library and command invoker')
+ ranger_jpa_jdbc_dialect = ranger_admin_properties_from_file['ranger.jpa.jdbc.dialect']
+ print('ranger_jpa_jdbc_dialect = ' + ranger_jpa_jdbc_dialect)
+ ranger_jpa_jdbc_url = ranger_admin_properties_from_file['ranger.jpa.jdbc.url']
+ print('ranger_jpa_jdbc_url = ' + ranger_jpa_jdbc_url)
+ if ('mysql'.lower() in ranger_jpa_jdbc_dialect.lower() and 'mysql'.lower() in ranger_jpa_jdbc_url.lower()):
+ print('db dialect and jdbc url are set as MYSQL setting db_flavour and sql command invoker as mysql')
+ ranger_admin_properties_from_file['DB_FLAVOR'] = 'MYSQL'
+ ranger_admin_properties_from_file['SQL_CONNECTOR_JAR'] = '/usr/share/java/mysql-connector-java.jar'
+ elif ('oracle'.lower() in ranger_jpa_jdbc_dialect and 'oracle'.lower() in ranger_jpa_jdbc_url.lower()):
+ print('db dialect and jdbc url are set as Oracle setting db_flavour and sql command invoker as oracle')
+ ranger_admin_properties_from_file['DB_FLAVOR'] = 'ORACLE'
+ ranger_admin_properties_from_file['SQL_CONNECTOR_JAR'] = '/usr/share/java/ojdbc6.jar'
+ elif ('postgres'.lower() in ranger_jpa_jdbc_dialect and 'postgres'.lower() in ranger_jpa_jdbc_url.lower()):
+ print('db dialect and jdbc url are set as postgres setting db_flavour and sql command invoker as postgres')
+ ranger_admin_properties_from_file['DB_FLAVOR'] = 'POSTGRES'
+ ranger_admin_properties_from_file['SQL_CONNECTOR_JAR'] = '/usr/share/java/postgresql.jar'
+ else:
+ print('found unsupported DB_FLAVOUR, please configure as MYSQL, ORACLE or Postgres which are supported for now.exitting for now')
+ sys.exit(1)
+
+ ranger_jpa_jdbc_url = ranger_admin_properties_from_file['ranger.jpa.jdbc.url']
+ print('found jdbc url configured as : ' + str(ranger_jpa_jdbc_url) + ' , getting db host from configured jdbc url')
+ ranger_database_host_name = ranger_jpa_jdbc_url.split(':')
+ ranger_database_host = ranger_database_host_name[3].split('/')[2]
+ ranger_database_name = ranger_database_host_name[3].split('/')[3]
+ print('found db host as : ' + str(ranger_database_host))
+ print('found db name as : ' + str(ranger_database_name))
+ ranger_admin_properties_from_file['db_host'] = ranger_database_host
+ ranger_admin_properties_from_file['db_name'] = ranger_database_name
+
+ ranger_audit_jdbc_url = ranger_admin_properties_from_file['ranger.jpa.audit.jdbc.url']
+ print('found audit jdbc url configured as : ' + str(ranger_audit_jdbc_url) + ' , getting db host from configured jdbc url')
+ ranger_audit_database_host_name = ranger_audit_jdbc_url.split(':')
+
+ ranger_audit_database_host = ranger_audit_database_host_name[3].split('/')[2]
+ ranger_audit_database_name = ranger_audit_database_host_name[3].split('/')[3]
+ print('found ranger_audit_database_name as : ' + str(ranger_audit_database_name))
+ ranger_admin_properties_from_file['audit_db_host'] = ranger_audit_database_host
+ ranger_admin_properties_from_file['audit_db_name'] = ranger_audit_database_name
+
+ ranger_db_password = ''
+ ranger_audit_db_password = ''
+
+ libpath = os.path.join(hdp_version_dir, 'ranger-admin', 'cred', 'lib', '*')
+ aliasKey = 'ranger.db.password'
+ aliasValue = ''
+ filepath = ranger_admin_properties_from_file['ranger.credential.provider.path']
+ if (filepath is None or len(filepath) == 0):
+ filepath = os.path.join(hdp_version_dir, 'ranger-admin', 'ews', 'webapp', 'WEB-INF', 'classes', 'conf', '.jceks', 'rangeradmin.jceks')
+
+ getorcreateorlist = 'get'
+
+ statuscode, value = call_keystore(libpath, aliasKey, aliasValue, filepath, getorcreateorlist)
+ if statuscode == 0:
+ ranger_db_password = value.strip()
+
+ aliasKey = 'ranger.auditdb.password'
+ statuscode, value = call_keystore(libpath, aliasKey, aliasValue, filepath, getorcreateorlist)
+ if statuscode == 0:
+ ranger_audit_db_password = value.strip()
+
+ if str(ranger_admin_properties_from_file['ranger.jpa.jdbc.password']) == '_' or str(ranger_admin_properties_from_file['ranger.jpa.jdbc.password']).lower() == 'crypted':
+ ranger_admin_properties_from_file['ranger.jpa.jdbc.password'] = ranger_db_password
+ if str(ranger_admin_properties_from_file['ranger.jpa.audit.jdbc.password']) == '_' or str(ranger_admin_properties_from_file['ranger.jpa.audit.jdbc.password']).lower() == 'crypted':
+ ranger_admin_properties_from_file['ranger.jpa.audit.jdbc.password'] = ranger_audit_db_password
+
+ return ranger_admin_properties_from_file
+
+
+def get_additional_properties_for_kms(ranger_kms_properties_from_file):
+ ranger_conf_path = '/etc/ranger/kms/conf'
+ kms_dbks_site_properties = os.path.join(ranger_conf_path,'dbks-site.xml')
+ ranger_kms_properties_from_file = import_properties_from_xml(kms_dbks_site_properties, ranger_kms_properties_from_file)
+ kms_site_properties = os.path.join(ranger_conf_path,'kms-site.xml')
+ ranger_kms_properties_from_file = import_properties_from_xml(kms_site_properties, ranger_kms_properties_from_file)
+ ranger_kms_site_properties = os.path.join(ranger_conf_path,'ranger-kms-site.xml')
+ ranger_kms_properties_from_file = import_properties_from_xml(ranger_kms_site_properties, ranger_kms_properties_from_file)
+ ranger_kms_audit_properties = os.path.join(ranger_conf_path,'ranger-kms-audit.xml')
+ ranger_kms_properties_from_file = import_properties_from_xml(ranger_kms_audit_properties, ranger_kms_properties_from_file)
+ ranger_kms_security_properties = os.path.join(ranger_conf_path,'ranger-kms-security.xml')
+ ranger_kms_properties_from_file = import_properties_from_xml(ranger_kms_security_properties, ranger_kms_properties_from_file)
+ ranger_policy_mgr_ssl_properties = os.path.join(ranger_conf_path,'ranger-policymgr-ssl.xml')
+ ranger_kms_properties_from_file = import_properties_from_xml(ranger_policy_mgr_ssl_properties, ranger_kms_properties_from_file)
+ kms_log4j_properties = os.path.join(ranger_conf_path,'kms-log4j.properties')
+ ranger_kms_properties_from_file['kms.log4j.properties'] = read_properties_file(kms_log4j_properties)
+
+ kms_jpa_jdbc_dialect = ranger_kms_properties_from_file['ranger.ks.jpa.jdbc.dialect']
+ print('kms_jpa_jdbc_dialect = ' + str(kms_jpa_jdbc_dialect))
+ kms_jpa_jdbc_url = ranger_kms_properties_from_file['ranger.ks.jpa.jdbc.url']
+ if ('mysql'.lower() in kms_jpa_jdbc_dialect.lower() and 'mysql'.lower() in kms_jpa_jdbc_url.lower()):
+ print('db dialect and jdbc url are set as MYSQL setting db_flavour and sql command invoker as mysql')
+ ranger_kms_properties_from_file['DB_FLAVOR'] = 'MYSQL'
+ ranger_kms_properties_from_file['SQL_CONNECTOR_JAR'] = '/usr/share/java/mysql-connector-java.jar'
+ elif ('oracle'.lower() in kms_jpa_jdbc_dialect and 'oracle'.lower() in kms_jpa_jdbc_url.lower()):
+ print('db dialect and jdbc url are set as Oracle setting db_flavour and sql command invoker as oracle')
+ ranger_kms_properties_from_file['DB_FLAVOR'] = 'ORACLE'
+ ranger_kms_properties_from_file['SQL_CONNECTOR_JAR'] = '/usr/share/java/ojdbc6.jar'
+ elif ('postgres'.lower() in kms_jpa_jdbc_dialect and 'postgres'.lower() in kms_jpa_jdbc_url.lower()):
+ print('db dialect and jdbc url are set as postgres setting db_flavour and sql command invoker as postgres')
+ ranger_kms_properties_from_file['DB_FLAVOR'] = 'POSTGRES'
+ ranger_kms_properties_from_file['SQL_CONNECTOR_JAR'] = '/usr/share/java/postgresql.jar'
+ else:
+ print('found unsupported DB_FLAVOUR, please configure as MYSQL, ORACLE or Postgres which are supported for now.exitting for now')
+ sys.exit(1)
+
+ kms_jpa_db_hostname = kms_jpa_jdbc_url.split(':')
+
+ kms_jpa_jdbc_hostname = kms_jpa_db_hostname[3].split('/')[2]
+ kms_jpa_jdbc_db_name = kms_jpa_db_hostname[3].split('/')[3]
+ print('found db hostname = ' + kms_jpa_jdbc_hostname )
+ print('found db name = ' + kms_jpa_jdbc_db_name )
+
+ ranger_kms_properties_from_file['db_host'] = kms_jpa_jdbc_hostname
+ ranger_kms_properties_from_file['db_name'] = kms_jpa_jdbc_db_name
+
+ kms_database_password = ''
+ kms_keystore_masterkey_password = ''
+
+ libpath = os.path.join(hdp_version_dir, 'ranger-kms', 'cred', 'lib', '*')
+ aliasKey = ranger_kms_properties_from_file['ranger.ks.jpa.jdbc.credential.alias']
+ if(aliasKey is None or len(aliasKey) == 0):
+ aliasKey = 'ranger.ks.jdbc.password'
+ aliasValue = ''
+ filepath = ranger_kms_properties_from_file['ranger.ks.jpa.jdbc.credential.provider.path']
+ if (filepath is None or len(filepath) == 0) :
+ filepath = os.path.join(hdp_version_dir, 'ranger-kms', 'ews', 'webapp', 'WEB-INF', 'classes', 'conf', '.jceks', 'rangerkms.jceks')
+
+ getorcreateorlist = 'get'
+
+ statuscode, value = call_keystore(libpath, aliasKey, aliasValue, filepath, getorcreateorlist)
+ if statuscode == 0:
+ kms_database_password = value.strip()
+ print('kms_database_password = ' + kms_database_password)
+ aliasKey = ranger_kms_properties_from_file['ranger.ks.masterkey.credential.alias']
+ if(aliasKey is None or len(aliasKey) == 0):
+ aliasKey = 'ranger.ks.masterkey.password'
+ statuscode, value = call_keystore(libpath, aliasKey, aliasValue, filepath, getorcreateorlist)
+
+ if statuscode == 0:
+ kms_keystore_masterkey_password = value.strip()
+
+ print('kms_keystore_masterkey_password = ' + kms_keystore_masterkey_password)
+
+ if str(ranger_kms_properties_from_file['ranger.ks.jpa.jdbc.password']) == '_' or str(ranger_kms_properties_from_file['ranger.ks.jpa.jdbc.password']).lower() == 'crypted':
+ ranger_kms_properties_from_file['ranger.ks.jpa.jdbc.password'] = kms_database_password
+ ranger_kms_properties_from_file['KMS_MASTER_KEY_PASSWD'] = kms_keystore_masterkey_password
+ ranger_kms_properties_from_file['ranger.db.encrypt.key.password'] = kms_keystore_masterkey_password
+
+ return ranger_kms_properties_from_file
+
+
+def get_additional_properties_for_usersync(ranger_usersync_properties_from_file):
+ ranger_conf_path = '/etc/ranger/usersync/conf'
+ ranger_ugsync_default_site_xml_properties = os.path.join(ranger_conf_path, 'ranger-ugsync-default.xml')
+ ranger_ugsync_site_xml_properties = os.path.join(ranger_conf_path, 'ranger-ugsync-site.xml')
+ ranger_usersync_properties_from_file = import_properties_from_xml(ranger_ugsync_default_site_xml_properties, ranger_usersync_properties_from_file)
+ ranger_usersync_properties_from_file = import_properties_from_xml(ranger_ugsync_site_xml_properties, ranger_usersync_properties_from_file)
+ if (('unix'.lower()) in str(ranger_usersync_properties_from_file['ranger.usersync.source.impl.class']).lower()):
+ print('sync_source is unix')
+ ranger_usersync_properties_from_file['SYNC_SOURCE'] = 'unix'
+ if (('ldap'.lower()) in str(ranger_usersync_properties_from_file['ranger.usersync.source.impl.class']).lower()):
+ print('sync source is ldap')
+ ranger_usersync_properties_from_file['SYNC_SOURCE'] = 'ldap'
+ return ranger_usersync_properties_from_file
+
+
+def port_ranger_hdfs_plugin_to_ambari():
+ print('Trying to add ranger hdfs plugin.')
+ flag_hdfs_plugin_installed, hdfs_plugin_install_properties, hdfs_site_xml_properties = get_hdfs_plugin_configuration()
+ if flag_hdfs_plugin_installed and hdfs_plugin_install_properties is not None and hdfs_site_xml_properties is not None:
+ hdfs_site_xml_properties['dfs.permissions.enabled'] = 'true'
+ print('hdfs plugin is installed and enabled, adding to configurations')
+ advanced_ranger_hdfs_plugin_properties = dict()
+ advanced_ranger_hdfs_audit_properties = dict()
+ advanced_ranger_hdfs_policymgr_ssl_properties = dict()
+ advanced_ranger_hdfs_security_properties = dict()
+
+ advanced_ranger_hdfs_plugin_properties['policy_user'] = 'ambari-qa'
+ advanced_ranger_hdfs_plugin_properties['hadoop.rpc.protection'] = ''
+ advanced_ranger_hdfs_plugin_properties['common.name.for.certificate'] = ''
+ advanced_ranger_hdfs_plugin_properties['ranger-hdfs-plugin-enabled'] = 'Yes'
+ advanced_ranger_hdfs_plugin_properties['REPOSITORY_CONFIG_USERNAME'] = 'hadoop'
+ advanced_ranger_hdfs_plugin_properties['REPOSITORY_CONFIG_PASSWORD'] = 'hadoop'
+
+ advanced_ranger_hdfs_audit_properties['xasecure.audit.is.enabled'] = hdfs_plugin_install_properties.get('xasecure.audit.is.enabled','true')
+ advanced_ranger_hdfs_audit_properties['xasecure.audit.destination.db'] = hdfs_plugin_install_properties.get('xasecure.audit.db.is.enabled','false')
+ advanced_ranger_hdfs_audit_properties['xasecure.audit.destination.db.jdbc.url'] = hdfs_plugin_install_properties.get('xasecure.audit.jpa.javax.persistence.jdbc.url','{{audit_jdbc_url}}')
+ advanced_ranger_hdfs_audit_properties['xasecure.audit.destination.db.user'] = hdfs_plugin_install_properties.get('xasecure.audit.jpa.javax.persistence.jdbc.user','{{xa_audit_db_user}}')
+ advanced_ranger_hdfs_audit_properties['xasecure.audit.destination.db.password'] = hdfs_plugin_install_properties.get('xasecure.audit.jpa.javax.persistence.jdbc.password','crypted')
+ advanced_ranger_hdfs_audit_properties['xasecure.audit.destination.db.jdbc.driver'] = hdfs_plugin_install_properties.get('xasecure.audit.jpa.javax.persistence.jdbc.driver','{{jdbc_driver}}')
+ advanced_ranger_hdfs_audit_properties['xasecure.audit.credential.provider.file'] = hdfs_plugin_install_properties.get('xasecure.audit.credential.provider.file','jceks://file{{credential_file}}')
+ advanced_ranger_hdfs_audit_properties['xasecure.audit.destination.db.batch.filespool.dir'] = hdfs_plugin_install_properties.get('xasecure.audit.destination.db.batch.filespool.dir','/var/log/hadoop/hdfs/audit/db/spool')
+ advanced_ranger_hdfs_audit_properties['xasecure.audit.destination.hdfs'] = hdfs_plugin_install_properties.get('xasecure.audit.destination.hdfs','true')
+ advanced_ranger_hdfs_audit_properties['xasecure.audit.destination.hdfs.dir'] = hdfs_plugin_install_properties.get('xasecure.audit.destination.hdfs.dir','hdfs://NAMENODE_HOSTNAME:8020/ranger/audit')
+ advanced_ranger_hdfs_audit_properties['xasecure.audit.destination.hdfs.batch.filespool.dir'] = hdfs_plugin_install_properties.get('xasecure.audit.destination.hdfs.batch.filespool.dir','/var/log/hadoop/hdfs/audit/hdfs/spool')
+ advanced_ranger_hdfs_audit_properties['xasecure.audit.destination.solr'] = hdfs_plugin_install_properties.get('xasecure.audit.destination.solr','false')
+ advanced_ranger_hdfs_audit_properties['xasecure.audit.destination.solr.urls'] = hdfs_plugin_install_properties.get('xasecure.audit.destination.solr.urls','{{ranger_audit_solr_urls}}')
+ advanced_ranger_hdfs_audit_properties['xasecure.audit.destination.solr.zookeepers'] = hdfs_plugin_install_properties.get('xasecure.audit.is.enabled','none')
+ advanced_ranger_hdfs_audit_properties['xasecure.audit.destination.solr.batch.filespool.dir'] = hdfs_plugin_install_properties.get('xasecure.audit.destination.solr.batch.filespool.dir','/var/log/hadoop/hdfs/audit/solr/spool')
+ advanced_ranger_hdfs_audit_properties['xasecure.audit.provider.summary.enabled'] = hdfs_plugin_install_properties.get('xasecure.audit.provider.summary.enabled','false')
+
+
+ advanced_ranger_hdfs_policymgr_ssl_properties['xasecure.policymgr.clientssl.keystore'] = hdfs_plugin_install_properties.get('xasecure.policymgr.clientssl.keystore','/usr/hdp/current/hadoop-client/conf/ranger-plugin-keystore.jks')
+ advanced_ranger_hdfs_policymgr_ssl_properties['xasecure.policymgr.clientssl.keystore.password'] = hdfs_plugin_install_properties.get('xasecure.policymgr.clientssl.keystore.password','myKeyFilePassword')
+ advanced_ranger_hdfs_policymgr_ssl_properties['xasecure.policymgr.clientssl.truststore'] = hdfs_plugin_install_properties.get('xasecure.policymgr.clientssl.truststore','/usr/hdp/current/hadoop-client/conf/ranger-plugin-truststore.jks')
+ advanced_ranger_hdfs_policymgr_ssl_properties['xasecure.policymgr.clientssl.truststore.password'] = hdfs_plugin_install_properties.get('xasecure.policymgr.clientssl.truststore.password','changeit')
+ advanced_ranger_hdfs_policymgr_ssl_properties['xasecure.policymgr.clientssl.keystore.credential.file'] = hdfs_plugin_install_properties.get('xasecure.policymgr.clientssl.keystore.credential.file','jceks://file{{credential_file}}')
+ advanced_ranger_hdfs_policymgr_ssl_properties['xasecure.policymgr.clientssl.truststore.credential.file'] = hdfs_plugin_install_properties.get('xasecure.policymgr.clientssl.truststore.credential.file','jceks://file{{credential_file}}')
+
+
+
+ advanced_ranger_hdfs_security_properties['ranger.plugin.hdfs.service.name'] = hdfs_plugin_install_properties.get('ranger.plugin.hdfs.service.name','{{repo_name}}')
+ advanced_ranger_hdfs_security_properties['ranger.plugin.hdfs.policy.source.impl'] = hdfs_plugin_install_properties.get('ranger.plugin.hdfs.policy.source.impl','org.apache.ranger.admin.client.RangerAdminRESTClient')
+ advanced_ranger_hdfs_security_properties['ranger.plugin.hdfs.policy.rest.url'] = hdfs_plugin_install_properties.get('ranger.plugin.hdfs.policy.rest.url','{{policymgr_mgr_url}}')
+ advanced_ranger_hdfs_security_properties['ranger.plugin.hdfs.policy.rest.ssl.config.file'] = hdfs_plugin_install_properties.get('ranger.plugin.hdfs.policy.rest.ssl.config.file','/etc/hadoop/conf/ranger-policymgr-ssl.xml')
+ advanced_ranger_hdfs_security_properties['ranger.plugin.hdfs.policy.pollIntervalMs'] = hdfs_plugin_install_properties.get('ranger.plugin.hdfs.policy.pollIntervalMs','30000')
+ advanced_ranger_hdfs_security_properties['ranger.plugin.hdfs.policy.cache.dir'] = hdfs_plugin_install_properties.get('ranger.plugin.hdfs.policy.cache.dir','/etc/ranger/{{repo_name}}/policycache')
+ advanced_ranger_hdfs_security_properties['xasecure.add-hadoop-authorization'] = hdfs_plugin_install_properties.get('xasecure.add-hadoop-authorization','true')
+
+
+ date_time_stamp = getDateTimeNow()
+
+ plugin_configuration_data = '[{"Clusters":{"desired_config":[{"type":"hdfs-site", "service_config_version_note": "Initial configuration for Ranger HDFS plugin" ,"tag":"' + str(date_time_stamp) + '","properties":' + str(
+ json.dumps(hdfs_site_xml_properties)) + ', "properties_attributes": {"final": "false"}},{"type": "ranger-hdfs-plugin-properties", "service_config_version_note": "Initial configuration for Ranger HDFS plugin" , "tag": "' + str(
+ date_time_stamp) + '", "properties":' + json.dumps(advanced_ranger_hdfs_plugin_properties) + ',"properties_attributes": {"final": "false"}},{"type": "ranger-hdfs-audit", "service_config_version_note": "Initial configuration for Ranger HDFS plugin" , "tag": "' + str(
+ date_time_stamp) + '", "properties":' + json.dumps(advanced_ranger_hdfs_audit_properties) + ',"properties_attributes": {"final": "false"}},{"type": "ranger-hdfs-policymgr-ssl", "service_config_version_note": "Initial configuration for Ranger HDFS plugin" , "tag": "' + str(
+ date_time_stamp) + '", "properties":' + json.dumps(advanced_ranger_hdfs_policymgr_ssl_properties) + ',"properties_attributes": {"final": "false"}},{"type": "ranger-hdfs-security", "service_config_version_note": "Initial configuration for Ranger HDFS plugin" , "tag": "' + str(
+ date_time_stamp) + '", "properties":' + json.dumps(advanced_ranger_hdfs_security_properties) + ',"properties_attributes": {"final": "false"}}]}}]'
+
+ print ('####################### hdfs_site_xml configuration :')
+ for each_key in hdfs_site_xml_properties:
+ print str(each_key) + ' = ' + str(hdfs_site_xml_properties[each_key])
+
+ print ('####################### ranger_hdfs_plugin_properties configuration :')
+ for each_key in advanced_ranger_hdfs_plugin_properties:
+ print str(each_key) + ' = ' + str(advanced_ranger_hdfs_plugin_properties[each_key])
+
+ print ('####################### ranger_hdfs_audit_properties configuration :')
+ for each_key in advanced_ranger_hdfs_audit_properties:
+ print str(each_key) + ' = ' + str(advanced_ranger_hdfs_audit_properties[each_key])
+
+ print ('####################### ranger_hdfs_policymgr_ssl_properties configuration :')
+ for each_key in advanced_ranger_hdfs_policymgr_ssl_properties:
+ print str(each_key) + ' = ' + str(advanced_ranger_hdfs_policymgr_ssl_properties[each_key])
+
+ print ('####################### ranger_hdfs_security_properties configuration :')
+ for each_key in advanced_ranger_hdfs_security_properties:
+ print str(each_key) + ' = ' + str(advanced_ranger_hdfs_security_properties[each_key])
+
+ confirm_configurations = raw_input('please confirm the above configuration values y/n (n) : ')
+ if(confirm_configurations == ''):
+ confirm_configurations = 'n'
+ print ('Input registered as ' + str(confirm_configurations))
+
+
+ if(confirm_configurations.lower() == 'y'):
+ ranger_config_request_url = ambari_cluster_url
+ request_result = call_ambari_api(ranger_config_request_url, 'PUT', ambari_username_password, str(plugin_configuration_data))
+ if request_result is not None:
+ response_code = request_result.getcode()
+ response = json.loads(json.JSONEncoder().encode(request_result.read()))
+ if response_code == 200 and response is not None:
+ print('ranger hdfs plugin configuration added successfully in ambari.')
+ return True
+ else:
+ print('ranger hdfs plugin configuration add failed in ambari.')
+ return False
+ else:
+ print('ranger hdfs plugin configuration add failed in ambari.')
+ return False
+ else:
+ print ('exiting installation without configuration !')
+ sys.exit(0)
+ else:
+ print('ranger hdfs plugin configuration add failed in ambari.')
+ return False
+
+def port_ranger_yarn_plugin_to_ambari():
+ print('Trying to add ranger yarn plugin.')
+ flag_yarn_plugin_installed,yarn_plugin_installed_properties,yarn_site_xml_properties = get_yarn_plugin_configuration()
+ if( flag_yarn_plugin_installed and yarn_plugin_installed_properties is not None and yarn_site_xml_properties is not None):
+ print('yarn plugin is installed and enabled, adding to configurations')
+ advanced_ranger_yarn_plugin_properties = dict()
+ advanced_ranger_yarn_audit_properties = dict()
+ advanced_ranger_yarn_policymgr_ssl_properties = dict()
+ advanced_ranger_yarn_security_properties = dict()
+
+ advanced_ranger_yarn_plugin_properties['policy_user'] = 'ambari-qa'
+ advanced_ranger_yarn_plugin_properties['hadoop.rpc.protection'] = ''
+ advanced_ranger_yarn_plugin_properties['common.name.for.certificate'] = ''
+ advanced_ranger_yarn_plugin_properties['ranger-yarn-plugin-enabled'] = 'Yes'
+ advanced_ranger_yarn_plugin_properties['REPOSITORY_CONFIG_USERNAME'] = 'yarn'
+ advanced_ranger_yarn_plugin_properties['REPOSITORY_CONFIG_PASSWORD'] = 'yarn'
+
+
+ advanced_ranger_yarn_audit_properties['xasecure.audit.is.enabled'] = yarn_plugin_installed_properties.get('xasecure.audit.is.enabled','true')
+ advanced_ranger_yarn_audit_properties['xasecure.audit.destination.db'] = yarn_plugin_installed_properties.get('xasecure.audit.db.is.enabled','false')
+ advanced_ranger_yarn_audit_properties['xasecure.audit.destination.db.jdbc.url'] = yarn_plugin_installed_properties.get('xasecure.audit.jpa.javax.persistence.jdbc.url','{{audit_jdbc_url}}')
+ advanced_ranger_yarn_audit_properties['xasecure.audit.destination.db.user'] = yarn_plugin_installed_properties.get('xasecure.audit.jpa.javax.persistence.jdbc.user','{{xa_audit_db_user}}')
+ advanced_ranger_yarn_audit_properties['xasecure.audit.destination.db.password'] = yarn_plugin_installed_properties.get('xasecure.audit.jpa.javax.persistence.jdbc.password','crypted')
+ advanced_ranger_yarn_audit_properties['xasecure.audit.destination.db.jdbc.driver'] = yarn_plugin_installed_properties.get('xasecure.audit.jpa.javax.persistence.jdbc.driver','{{jdbc_driver}}')
+ advanced_ranger_yarn_audit_properties['xasecure.audit.credential.provider.file'] = yarn_plugin_installed_properties.get('xasecure.audit.credential.provider.file','jceks://file{{credential_file}}')
+ advanced_ranger_yarn_audit_properties['xasecure.audit.destination.db.batch.filespool.dir'] = yarn_plugin_installed_properties.get('xasecure.audit.destination.db.batch.filespool.dir','/var/log/hadoop/yarn/audit/db/spool')
+ advanced_ranger_yarn_audit_properties['xasecure.audit.destination.hdfs'] = yarn_plugin_installed_properties.get('xasecure.audit.destination.hdfs','true')
+ advanced_ranger_yarn_audit_properties['xasecure.audit.destination.hdfs.dir'] = yarn_plugin_installed_properties.get('xasecure.audit.destination.hdfs.dir','hdfs://NAMENODE_HOSTNAME:8020/ranger/audit')
+ advanced_ranger_yarn_audit_properties['xasecure.audit.destination.hdfs.batch.filespool.dir'] = yarn_plugin_installed_properties.get('xasecure.audit.destination.hdfs.batch.filespool.dir','/var/log/hadoop/yarn/audit/hdfs/spool')
+ advanced_ranger_yarn_audit_properties['xasecure.audit.destination.solr'] = yarn_plugin_installed_properties.get('xasecure.audit.destination.solr','false')
+ advanced_ranger_yarn_audit_properties['xasecure.audit.destination.solr.urls'] = yarn_plugin_installed_properties.get('xasecure.audit.destination.solr.urls','{{ranger_audit_solr_urls}}')
+ advanced_ranger_yarn_audit_properties['xasecure.audit.destination.solr.zookeepers'] = yarn_plugin_installed_properties.get('xasecure.audit.destination.solr.zookeepers','none')
+ advanced_ranger_yarn_audit_properties['xasecure.audit.destination.solr.batch.filespool.dir'] = yarn_plugin_installed_properties.get('xasecure.audit.destination.solr.batch.filespool.dir','/var/log/hadoop/yarn/audit/solr/spool')
+ advanced_ranger_yarn_audit_properties['xasecure.audit.provider.summary.enabled'] = yarn_plugin_installed_properties.get('xasecure.audit.provider.summary.enabled','false')
+
+ advanced_ranger_yarn_policymgr_ssl_properties['xasecure.policymgr.clientssl.keystore'] = yarn_plugin_installed_properties.get('xasecure.policymgr.clientssl.keystore','/usr/hdp/current/hadoop-client/conf/ranger-yarn-plugin-keystore.jks')
+ advanced_ranger_yarn_policymgr_ssl_properties['xasecure.policymgr.clientssl.keystore.password'] = yarn_plugin_installed_properties.get('xasecure.policymgr.clientssl.keystore.password','myKeyFilePassword')
+ advanced_ranger_yarn_policymgr_ssl_properties['xasecure.policymgr.clientssl.truststore'] = yarn_plugin_installed_properties.get('xasecure.policymgr.clientssl.truststore','/usr/hdp/current/hadoop-client/conf/ranger-yarn-plugin-truststore.jks')
+ advanced_ranger_yarn_policymgr_ssl_properties['xasecure.policymgr.clientssl.truststore.password'] = yarn_plugin_installed_properties.get('xasecure.policymgr.clientssl.truststore.password','changeit')
+ advanced_ranger_yarn_policymgr_ssl_properties['xasecure.policymgr.clientssl.keystore.credential.file'] = yarn_plugin_installed_properties.get('xasecure.policymgr.clientssl.keystore.credential.file','jceks://file{{credential_file}}')
+ advanced_ranger_yarn_policymgr_ssl_properties['xasecure.policymgr.clientssl.truststore.credential.file'] = yarn_plugin_installed_properties.get('xasecure.policymgr.clientssl.truststore.credential.file','jceks://file{{credential_file}}')
+
+
+ advanced_ranger_yarn_security_properties['ranger.plugin.yarn.service.name'] = yarn_plugin_installed_properties.get('ranger.plugin.yarn.service.name','{{repo_name}}')
+ advanced_ranger_yarn_security_properties['ranger.plugin.yarn.policy.source.impl'] = yarn_plugin_installed_properties.get('ranger.plugin.yarn.policy.source.impl','org.apache.ranger.admin.client.RangerAdminRESTClient')
+ advanced_ranger_yarn_security_properties['ranger.plugin.yarn.policy.rest.url'] = yarn_plugin_installed_properties.get('ranger.plugin.yarn.policy.rest.url','{{policymgr_mgr_url}}')
+ advanced_ranger_yarn_security_properties['ranger.plugin.yarn.policy.rest.ssl.config.file'] = yarn_plugin_installed_properties.get('ranger.plugin.yarn.policy.rest.ssl.config.file','/etc/hadoop/conf/ranger-policymgr-ssl-yarn.xml')
+ advanced_ranger_yarn_security_properties['ranger.plugin.yarn.policy.pollIntervalMs'] = yarn_plugin_installed_properties.get('ranger.plugin.yarn.policy.pollIntervalMs','30000')
+ advanced_ranger_yarn_security_properties['ranger.plugin.yarn.policy.cache.dir'] = yarn_plugin_installed_properties.get('ranger.plugin.yarn.policy.cache.dir','/etc/ranger/{{repo_name}}/policycache')
+
+ date_time_stamp = getDateTimeNow()
+
+ plugin_configuration_data = '[{"Clusters":{"desired_config":[{"type":"yarn-site", "service_config_version_note": "Initial configuration for Ranger YARN plugin" ,"tag":"' + str(date_time_stamp) + '","properties":' + str(
+ json.dumps(yarn_site_xml_properties)) + ', "properties_attributes": {"final": "false"}},{"type": "ranger-yarn-plugin-properties", "service_config_version_note": "Initial configuration for Ranger YARN plugin" , "tag": "' + str(
+ date_time_stamp) + '", "properties":' + json.dumps(advanced_ranger_yarn_plugin_properties) + ',"properties_attributes": {"final": "false"}},{"type": "ranger-yarn-audit", "service_config_version_note": "Initial configuration for Ranger YARN plugin" , "tag": "' + str(
+ date_time_stamp) + '", "properties":' + json.dumps(advanced_ranger_yarn_audit_properties) + ',"properties_attributes": {"final": "false"}},{"type": "ranger-yarn-policymgr-ssl", "service_config_version_note": "Initial configuration for Ranger YARN plugin" , "tag": "' + str(
+ date_time_stamp) + '", "properties":' + json.dumps(advanced_ranger_yarn_policymgr_ssl_properties) + ',"properties_attributes": {"final": "false"}},{"type": "ranger-yarn-security", "service_config_version_note": "Initial configuration for Ranger YARN plugin" , "tag": "' + str(
+ date_time_stamp) + '", "properties":' + json.dumps(advanced_ranger_yarn_security_properties) + ',"properties_attributes": {"final": "false"}}]}}]'
+
+ print ('####################### yarn_site_xml configuration :')
+ for each_key in yarn_site_xml_properties:
+ print str(each_key) + ' = ' + str(yarn_site_xml_properties[each_key])
+
+ print ('####################### ranger_yarn_plugin_properties configuration :')
+ for each_key in advanced_ranger_yarn_plugin_properties:
+ print str(each_key) + ' = ' + str(advanced_ranger_yarn_plugin_properties[each_key])
+
+ print ('####################### ranger_yarn_audit_properties configuration :')
+ for each_key in advanced_ranger_yarn_audit_properties:
+ print str(each_key) + ' = ' + str(advanced_ranger_yarn_audit_properties[each_key])
+
+ print ('####################### ranger_yarn_policymgr_ssl_properties configuration :')
+ for each_key in advanced_ranger_yarn_policymgr_ssl_properties:
+ print str(each_key) + ' = ' + str(advanced_ranger_yarn_policymgr_ssl_properties[each_key])
+
+ print ('####################### ranger_hdfs_security_properties configuration :')
+ for each_key in advanced_ranger_yarn_security_properties:
+ print str(each_key) + ' = ' + str(advanced_ranger_yarn_security_properties[each_key])
+
+
+ confirm_configurations = raw_input('please confirm the above configuration values y/n (n) : ')
+ if(confirm_configurations == ''):
+ confirm_configurations = 'n'
+ print ('Input registered as ' + str(confirm_configurations))
+
+ if(confirm_configurations.lower() == 'y'):
+ ranger_config_request_url = ambari_cluster_url
+ request_result = call_ambari_api(ranger_config_request_url, 'PUT', ambari_username_password, str(plugin_configuration_data))
+ if request_result is not None:
+ response_code = request_result.getcode()
+ response = json.loads(json.JSONEncoder().encode(request_result.read()))
+ if response_code == 200 and response is not None:
+ print('ranger yarn plugin configuration added successfully in ambari.')
+ return True
+ else:
+ print('ranger yarn plugin configuration add failed in ambari.')
+ return False
+ else:
+ print('ranger yarn plugin configuration add failed in ambari.')
+ return False
+ else:
+ print ('exiting installation without configuration !')
+ sys.exit(0)
+ else:
+ print('ranger yarn plugin configuration add failed in ambari.')
+ return False
+
+
+def port_ranger_hive_plugin_to_ambari():
+ print('Trying to add ranger hive plugin.')
+ flag_hive_plugin_installed, hive_plugin_install_properties, hive_server2_xml_properties = get_hive_plugin_configuration()
+ hive_env_properties, hive_site_properties = get_hive_configs_from_ambari()
+ if flag_hive_plugin_installed and hive_plugin_install_properties is not None and hive_server2_xml_properties is not None and hive_env_properties is not None and hive_site_properties is not None:
+ hive_server2_xml_properties['hive.security.authorization.enabled'] = 'true'
+ hive_server2_xml_properties['hive.security.authorization.manager'] = 'org.apache.ranger.authorization.hive.authorizer.RangerHiveAuthorizerFactory'
+ hive_server2_xml_properties['hive.security.authenticator.manager'] = 'org.apache.hadoop.hive.ql.security.SessionStateUserAuthenticator'
+ hive_server2_xml_properties['hive.conf.restricted.list'] = 'hive.security.authorization.enabled,hive.security.authorization.manager,hive.security.authenticator.manager'
+
+ print('hive plugin is installed and enabled, adding to configurations')
+ advanced_ranger_hive_plugin_properties = dict()
+ advanced_ranger_hive_audit_properties = dict()
+ advanced_ranger_hive_policymgr_ssl_properties = dict()
+ advanced_ranger_hive_security_properties = dict()
+
+ advanced_ranger_hive_plugin_properties['policy_user'] = 'ambari-qa'
+ advanced_ranger_hive_plugin_properties['jdbc.driverClassName'] = 'org.apache.hive.jdbc.HiveDriver'
+ advanced_ranger_hive_plugin_properties['common.name.for.certificate'] = ''
+# advanced_ranger_hive_plugin_properties['ranger-hive-plugin-enabled'] = 'Yes'
+ advanced_ranger_hive_plugin_properties['REPOSITORY_CONFIG_USERNAME'] = 'hive'
+ advanced_ranger_hive_plugin_properties['REPOSITORY_CONFIG_PASSWORD'] = 'hive'
+
+ advanced_ranger_hive_audit_properties['xasecure.audit.is.enabled'] = hive_plugin_install_properties.get('xasecure.audit.is.enabled','true')
+ advanced_ranger_hive_audit_properties['xasecure.audit.destination.db'] = hive_plugin_install_properties.get('xasecure.audit.db.is.enabled','false')
+ advanced_ranger_hive_audit_properties['xasecure.audit.destination.db.jdbc.url'] = hive_plugin_install_properties.get('xasecure.audit.jpa.javax.persistence.jdbc.url','{{audit_jdbc_url}}')
+ advanced_ranger_hive_audit_properties['xasecure.audit.destination.db.user'] = hive_plugin_install_properties.get('xasecure.audit.jpa.javax.persistence.jdbc.user','{{xa_audit_db_user}}')
+ advanced_ranger_hive_audit_properties['xasecure.audit.destination.db.password'] = hive_plugin_install_properties.get('xasecure.audit.jpa.javax.persistence.jdbc.password','crypted')
+ advanced_ranger_hive_audit_properties['xasecure.audit.destination.db.jdbc.driver'] = hive_plugin_install_properties.get('xasecure.audit.jpa.javax.persistence.jdbc.driver','{{jdbc_driver}}')
+ advanced_ranger_hive_audit_properties['xasecure.audit.credential.provider.file'] = hive_plugin_install_properties.get('xasecure.audit.credential.provider.file','jceks://file{{credential_file}}')
+ advanced_ranger_hive_audit_properties['xasecure.audit.destination.db.batch.filespool.dir'] = hive_plugin_install_properties.get('xasecure.audit.destination.db.batch.filespool.dir','/var/log/hive/audit/db/spool')
+ advanced_ranger_hive_audit_properties['xasecure.audit.destination.hdfs'] = hive_plugin_install_properties.get('xasecure.audit.destination.hdfs','true')
+ advanced_ranger_hive_audit_properties['xasecure.audit.destination.hdfs.dir'] = hive_plugin_install_properties.get('xasecure.audit.destination.hdfs.dir','hdfs://NAMENODE_HOSTNAME:8020/ranger/audit')
+ advanced_ranger_hive_audit_properties['xasecure.audit.destination.hdfs.batch.filespool.dir'] = hive_plugin_install_properties.get('xasecure.audit.destination.hdfs.batch.filespool.dir','/var/log/hive/audit/hdfs/spool')
+ advanced_ranger_hive_audit_properties['xasecure.audit.destination.solr'] = hive_plugin_install_properties.get('xasecure.audit.destination.solr','false')
+ advanced_ranger_hive_audit_properties['xasecure.audit.destination.solr.urls'] = hive_plugin_install_properties.get('xasecure.audit.destination.solr.urls','{{ranger_audit_solr_urls}}')
+ advanced_ranger_hive_audit_properties['xasecure.audit.destination.solr.zookeepers'] = hive_plugin_install_properties.get('xasecure.audit.destination.solr.zookeepers','none')
+ advanced_ranger_hive_audit_properties['xasecure.audit.destination.solr.batch.filespool.dir'] = hive_plugin_install_properties.get('xasecure.audit.destination.solr.batch.filespool.dir','/var/log/hive/audit/solr/spool')
+ advanced_ranger_hive_audit_properties['xasecure.audit.provider.summary.enabled'] = hive_plugin_install_properties.get('xasecure.audit.provider.summary.enabled','false')
+
+
+ advanced_ranger_hive_policymgr_ssl_properties['xasecure.policymgr.clientssl.keystore'] = hive_plugin_install_properties.get('xasecure.policymgr.clientssl.keystore','/usr/hdp/current/hive-server2/conf/ranger-plugin-keystore.jks')
+ advanced_ranger_hive_policymgr_ssl_properties['xasecure.policymgr.clientssl.keystore.password'] = hive_plugin_install_properties.get('xasecure.policymgr.clientssl.keystore.password','myKeyFilePassword')
+ advanced_ranger_hive_policymgr_ssl_properties['xasecure.policymgr.clientssl.truststore'] = hive_plugin_install_properties.get('xasecure.policymgr.clientssl.truststore','/usr/hdp/current/hive-server2/conf/ranger-plugin-truststore.jks')
+ advanced_ranger_hive_policymgr_ssl_properties['xasecure.policymgr.clientssl.truststore.password'] = hive_plugin_install_properties.get('xasecure.policymgr.clientssl.truststore.password','changeit')
+ advanced_ranger_hive_policymgr_ssl_properties['xasecure.policymgr.clientssl.keystore.credential.file'] = hive_plugin_install_properties.get('xasecure.policymgr.clientssl.keystore.credential.file','jceks://file{{credential_file}}')
+ advanced_ranger_hive_policymgr_ssl_properties['xasecure.policymgr.clientssl.truststore.credential.file'] = hive_plugin_install_properties.get('xasecure.policymgr.clientssl.truststore.credential.file','jceks://file{{credential_file}}')
+
+
+ advanced_ranger_hive_security_properties['ranger.plugin.hive.service.name'] = hive_plugin_install_properties.get('ranger.plugin.hive.service.name','{{repo_name}}')
+ advanced_ranger_hive_security_properties['ranger.plugin.hive.policy.source.impl'] = hive_plugin_install_properties.get('ranger.plugin.hive.policy.source.impl','org.apache.ranger.admin.client.RangerAdminRESTClient')
+ advanced_ranger_hive_security_properties['ranger.plugin.hive.policy.rest.url'] = hive_plugin_install_properties.get('ranger.plugin.hive.policy.rest.url','{{policymgr_mgr_url}}')
+ advanced_ranger_hive_security_properties['ranger.plugin.hive.policy.rest.ssl.config.file'] = hive_plugin_install_properties.get('ranger.plugin.hive.policy.rest.ssl.config.file','/usr/hdp/current/hive-server2/conf/ranger-policymgr-ssl.xml')
+ advanced_ranger_hive_security_properties['ranger.plugin.hive.policy.pollIntervalMs'] = hive_plugin_install_properties.get('ranger.plugin.hive.policy.pollIntervalMs','30000')
+ advanced_ranger_hive_security_properties['ranger.plugin.hive.policy.cache.dir'] = hive_plugin_install_properties.get('ranger.plugin.hive.policy.cache.dir','/etc/ranger/{{repo_name}}/policycache')
+ advanced_ranger_hive_security_properties['xasecure.hive.update.xapolicies.on.grant.revoke'] = hive_plugin_install_properties.get('xasecure.hive.update.xapolicies.on.grant.revoke','true')
+
+ hive_env_properties['hive_security_authorization'] = 'Ranger'
+ hive_site_properties['hive.server2.enable.doAs'] = 'false'
+
+
+ date_time_stamp = getDateTimeNow()
+
+ plugin_configuration_data = '[{"Clusters":{"desired_config":[{"type":"hiveserver2-site", "service_config_version_note": "Initial configuration for Ranger HIVE plugin" ,"tag":"' + str(date_time_stamp) + '","properties":' + str(
+ json.dumps(hive_server2_xml_properties)) + ', "properties_attributes": {"final": "false"}},{"type":"hive-site", "service_config_version_note": "Initial configuration for Ranger HIVE plugin" ,"tag":"' + str(date_time_stamp) + '","properties":' + str(
+ json.dumps(hive_site_properties)) + ', "properties_attributes": {"final": "false"}},{"type":"hive-env", "service_config_version_note": "Initial configuration for Ranger HIVE plugin" ,"tag":"' + str(date_time_stamp) + '","properties":' + str(
+ json.dumps(hive_env_properties)) + ', "properties_attributes": {"final": "false"}},{"type": "ranger-hive-plugin-properties", "service_config_version_note": "Initial configuration for Ranger HIVE plugin" ,"tag":"' + str(
+ date_time_stamp) + '", "properties":' + json.dumps(advanced_ranger_hive_plugin_properties) + ',"properties_attributes": {"final": "false"}},{"type": "ranger-hive-audit", "service_config_version_note": "Initial configuration for Ranger HIVE plugin" ,"tag":"' + str(
+ date_time_stamp) + '", "properties":' + json.dumps(advanced_ranger_hive_audit_properties) + ',"properties_attributes": {"final": "false"}},{"type": "ranger-hive-policymgr-ssl", "service_config_version_note": "Initial configuration for Ranger HIVE plugin" ,"tag":"' + str(
+ date_time_stamp) + '", "properties":' + json.dumps(advanced_ranger_hive_policymgr_ssl_properties) + ',"properties_attributes": {"final": "false"}},{"type": "ranger-hive-security", "service_config_version_note": "Initial configuration for Ranger HIVE plugin" ,"tag":"' + str(
+ date_time_stamp) + '", "properties":' + json.dumps(advanced_ranger_hive_security_properties) + ',"properties_attributes": {"final": "false"}}]}}]'
+
+
+ print ('####################### hive_server2_xml configuration :')
+ for each_key in hive_server2_xml_properties:
+ print str(each_key) + ' = ' + str(hive_server2_xml_properties[each_key])
+
+ print ('####################### ranger_hive_plugin_properties configuration :')
+ for each_key in advanced_ranger_hive_plugin_properties:
+ print str(each_key) + ' = ' + str(advanced_ranger_hive_plugin_properties[each_key])
+
+ print ('####################### ranger_hive_audit_properties configuration :')
+ for each_key in advanced_ranger_hive_audit_properties:
+ print str(each_key) + ' = ' + str(advanced_ranger_hive_audit_properties[each_key])
+
+ print ('####################### ranger_hive_policymgr_ssl configuration :')
+ for each_key in advanced_ranger_hive_policymgr_ssl_properties:
+ print str(each_key) + ' = ' + str(advanced_ranger_hive_policymgr_ssl_properties[each_key])
+
+ print ('####################### ranger_hive_security_properties configuration :')
+ for each_key in advanced_ranger_hive_security_properties:
+ print str(each_key) + ' = ' + str(advanced_ranger_hive_security_properties[each_key])
+
+ print ('####################### ranger_hive_env_properties configuration :')
+ for each_key in hive_env_properties:
+ print str(each_key) + ' = ' + str(hive_env_properties[each_key])
+
+ print ('####################### ranger_hive_site_properties configuration :')
+ for each_key in hive_site_properties:
+ print str(each_key) + ' = ' + str(hive_site_properties[each_key])
+
+
+ confirm_configurations = raw_input('please confirm the above configuration values y/n (n) : ')
+ if(confirm_configurations == ''):
+ confirm_configurations = 'n'
+ print ('Input registered as ' + str(confirm_configurations))
+
+
+ if(confirm_configurations.lower() == 'y'):
+ ranger_config_request_url = ambari_cluster_url
+ request_result = call_ambari_api(ranger_config_request_url, 'PUT', ambari_username_password, str(plugin_configuration_data))
+ if request_result is not None:
+ response_code = request_result.getcode()
+ response = json.loads(json.JSONEncoder().encode(request_result.read()))
+ if response_code == 200 and response is not None:
+ print('ranger hive plugin configuration added successfully in ambari.')
+ return True
+ else:
+ print('ranger hive plugin configuration add failed in ambari.')
+ return False
+ else:
+ print('ranger hive plugin configuration add failed in ambari.')
+ return False
+ else:
+ print ('exiting installation without configuration !')
+ sys.exit(0)
+ else:
+ print('ranger hive plugin configuration add failed in ambari.')
+ return False
+
+
+
+def port_ranger_hbase_plugin_to_ambari():
+ print('Trying to add ranger Hbase plugin.')
+ flag_hbase_plugin_installed, hbase_plugin_install_properties, hbase_site_xml_properties = get_hbase_plugin_configuration()
+ if flag_hbase_plugin_installed and hbase_plugin_install_properties is not None and hbase_site_xml_properties is not None:
+ print('Hbase plugin is installed and enabled, adding to configurations')
+ advanced_ranger_hbase_plugin_properties = dict()
+ advanced_ranger_hbase_audit_properties = dict()
+ advanced_ranger_hbase_policymgr_ssl_properties = dict()
+ advanced_ranger_hbase_security_properties = dict()
+
+ advanced_ranger_hbase_plugin_properties['policy_user'] = 'ambari-qa'
+ advanced_ranger_hbase_plugin_properties['common.name.for.certificate'] = ''
+ advanced_ranger_hbase_plugin_properties['ranger-hbase-plugin-enabled'] = 'Yes'
+ advanced_ranger_hbase_plugin_properties['REPOSITORY_CONFIG_USERNAME'] = 'hbase'
+ advanced_ranger_hbase_plugin_properties['REPOSITORY_CONFIG_PASSWORD'] = 'hbase'
+
+
+ advanced_ranger_hbase_audit_properties['xasecure.audit.is.enabled'] = hbase_plugin_install_properties.get('xasecure.audit.is.enabled','true')
+ advanced_ranger_hbase_audit_properties['xasecure.audit.destination.db'] = hbase_plugin_install_properties.get('xasecure.audit.db.is.enabled','false')
+ advanced_ranger_hbase_audit_properties['xasecure.audit.destination.db.jdbc.url'] = hbase_plugin_install_properties.get('xasecure.audit.jpa.javax.persistence.jdbc.url','{{audit_jdbc_url}}')
+ advanced_ranger_hbase_audit_properties['xasecure.audit.destination.db.user'] = hbase_plugin_install_properties.get('xasecure.audit.jpa.javax.persistence.jdbc.user','{{xa_audit_db_user}}')
+ advanced_ranger_hbase_audit_properties['xasecure.audit.destination.db.password'] = hbase_plugin_install_properties.get('xasecure.audit.jpa.javax.persistence.jdbc.password','crypted')
+ advanced_ranger_hbase_audit_properties['xasecure.audit.destination.db.jdbc.driver'] = hbase_plugin_install_properties.get('xasecure.audit.jpa.javax.persistence.jdbc.driver','{{jdbc_driver}}')
+ advanced_ranger_hbase_audit_properties['xasecure.audit.credential.provider.file'] = hbase_plugin_install_properties.get('xasecure.audit.credential.provider.file','jceks://file{{credential_file}}')
+ advanced_ranger_hbase_audit_properties['xasecure.audit.destination.db.batch.filespool.dir'] = hbase_plugin_install_properties.get('xasecure.audit.destination.db.batch.filespool.dir','/var/log/hbase/audit/db/spool')
+ advanced_ranger_hbase_audit_properties['xasecure.audit.destination.hdfs'] = hbase_plugin_install_properties.get('xasecure.audit.destination.hdfs','true')
+ advanced_ranger_hbase_audit_properties['xasecure.audit.destination.hdfs.dir'] = hbase_plugin_install_properties.get('xasecure.audit.destination.hdfs.dir','hdfs://NAMENODE_HOSTNAME:8020/ranger/audit')
+ advanced_ranger_hbase_audit_properties['xasecure.audit.destination.hdfs.batch.filespool.dir'] = hbase_plugin_install_properties.get('xasecure.audit.destination.hdfs.batch.filespool.dir','/var/log/hbase/audit/hdfs/spool')
+ advanced_ranger_hbase_audit_properties['xasecure.audit.destination.solr'] = hbase_plugin_install_properties.get('xasecure.audit.destination.solr','false')
+ advanced_ranger_hbase_audit_properties['xasecure.audit.destination.solr.urls'] = hbase_plugin_install_properties.get('xasecure.audit.destination.solr.urls','{{ranger_audit_solr_urls}}')
+ advanced_ranger_hbase_audit_properties['xasecure.audit.destination.solr.zookeepers'] = hbase_plugin_install_properties.get('xasecure.audit.destination.solr.zookeepers','none')
+ advanced_ranger_hbase_audit_properties['xasecure.audit.destination.solr.batch.filespool.dir'] = hbase_plugin_install_properties.get('xasecure.audit.destination.solr.batch.filespool.dir','/var/log/hbase/audit/solr/spool')
+ advanced_ranger_hbase_audit_properties['xasecure.audit.provider.summary.enabled'] = hbase_plugin_install_properties.get('xasecure.audit.provider.summary.enabled','true')
+
+ advanced_ranger_hbase_policymgr_ssl_properties['xasecure.policymgr.clientssl.keystore'] = hbase_plugin_install_properties.get('xasecure.policymgr.clientssl.keystore','/usr/hdp/current/hbase-client/conf/ranger-plugin-keystore.jks')
+ advanced_ranger_hbase_policymgr_ssl_properties['xasecure.policymgr.clientssl.keystore.password'] = hbase_plugin_install_properties.get('xasecure.policymgr.clientssl.keystore.password','myKeyFilePassword')
+ advanced_ranger_hbase_policymgr_ssl_properties['xasecure.policymgr.clientssl.truststore'] = hbase_plugin_install_properties.get('xasecure.policymgr.clientssl.truststore','/usr/hdp/current/hbase-client/conf/ranger-plugin-truststore.jks')
+ advanced_ranger_hbase_policymgr_ssl_properties['xasecure.policymgr.clientssl.truststore.password'] = hbase_plugin_install_properties.get('xasecure.policymgr.clientssl.truststore.password','changeit')
+ advanced_ranger_hbase_policymgr_ssl_properties['xasecure.policymgr.clientssl.keystore.credential.file'] = hbase_plugin_install_properties.get('xasecure.policymgr.clientssl.keystore.credential.file','jceks://file{{credential_file}}')
+ advanced_ranger_hbase_policymgr_ssl_properties['xasecure.policymgr.clientssl.truststore.credential.file'] = hbase_plugin_install_properties.get('xasecure.policymgr.clientssl.truststore.credential.file','jceks://file{{credential_file}}')
+
+ advanced_ranger_hbase_security_properties['ranger.plugin.hbase.service.name'] = hbase_plugin_install_properties.get('ranger.plugin.hbase.service.name','{{repo_name}}')
+ advanced_ranger_hbase_security_properties['ranger.plugin.hbase.policy.source.impl'] = hbase_plugin_install_properties.get('ranger.plugin.hbase.policy.source.impl','org.apache.ranger.admin.client.RangerAdminRESTClient')
+ advanced_ranger_hbase_security_properties['ranger.plugin.hbase.policy.rest.url'] = hbase_plugin_install_properties.get('ranger.plugin.hbase.policy.rest.url','{{policymgr_mgr_url}}')
+ advanced_ranger_hbase_security_properties['ranger.plugin.hbase.policy.rest.ssl.config.file'] = hbase_plugin_install_properties.get('ranger.plugin.hbase.policy.rest.ssl.config.file','/etc/hbase/conf/ranger-policymgr-ssl.xml')
+ advanced_ranger_hbase_security_properties['ranger.plugin.hbase.policy.pollIntervalMs'] = hbase_plugin_install_properties.get('ranger.plugin.hbase.policy.pollIntervalMs','30000')
+ advanced_ranger_hbase_security_properties['ranger.plugin.hbase.policy.cache.dir'] = hbase_plugin_install_properties.get('ranger.plugin.hbase.policy.cache.dir','/etc/ranger/{{repo_name}}/policycache')
+ advanced_ranger_hbase_security_properties['xasecure.hbase.update.xapolicies.on.grant.revoke'] = hbase_plugin_install_properties.get('xasecure.hbase.update.xapolicies.on.grant.revoke','true')
+
+
+ date_time_stamp = getDateTimeNow()
+ plugin_configuration_data = '[{"Clusters":{"desired_config":[{"type":"hbase-site", "service_config_version_note": "Initial configuration for Ranger HBASE plugin" ,"tag":"' + str(date_time_stamp) + '","properties":' + str(
+ json.dumps(hbase_site_xml_properties)) + ', "properties_attributes": {"final": "false"}},{"type": "ranger-hbase-plugin-properties","service_config_version_note": "Initial configuration for Ranger HBASE plugin" ,"tag":"' + str(
+ date_time_stamp) + '", "properties":' + json.dumps(advanced_ranger_hbase_plugin_properties) + ',"properties_attributes": {"final": "false"}},{"type": "ranger-hbase-audit","service_config_version_note": "Initial configuration for Ranger HBASE plugin" ,"tag":"' + str(
+ date_time_stamp) + '", "properties":' + json.dumps(advanced_ranger_hbase_audit_properties) + ',"properties_attributes": {"final": "false"}},{"type": "ranger-hbase-policymgr-ssl","service_config_version_note": "Initial configuration for Ranger HBASE plugin" ,"tag":"' + str(
+ date_time_stamp) + '", "properties":' + json.dumps(advanced_ranger_hbase_policymgr_ssl_properties) + ',"properties_attributes": {"final": "false"}},{"type": "ranger-hbase-security","service_config_version_note": "Initial configuration for Ranger HBASE plugin" ,"tag":"' + str(
+ date_time_stamp) + '", "properties":' + json.dumps(advanced_ranger_hbase_security_properties) + ',"properties_attributes": {"final": "false"}}]}}]'
+
+ print ('####################### hbase_site_xml configuration :')
+ for each_key in hbase_site_xml_properties:
+ print str(each_key) + ' = ' + str(hbase_site_xml_properties[each_key])
+
+ print ('####################### ranger_hbase_plugin_properties configuration :')
+ for each_key in advanced_ranger_hbase_plugin_properties:
+ print str(each_key) + ' = ' + str(advanced_ranger_hbase_plugin_properties[each_key])
+
+ print ('####################### ranger_hbase_audit_properties configuration :')
+ for each_key in advanced_ranger_hbase_audit_properties:
+ print str(each_key) + ' = ' + str(advanced_ranger_hbase_audit_properties[each_key])
+
+ print ('####################### ranger_hbase_policymgr_ssl_properties configuration :')
+ for each_key in advanced_ranger_hbase_policymgr_ssl_properties:
+ print str(each_key) + ' = ' + str(advanced_ranger_hbase_policymgr_ssl_properties[each_key])
+
+ print ('####################### ranger_hbase_security_properties configuration :')
+ for each_key in advanced_ranger_hbase_security_properties:
+ print str(each_key) + ' = ' + str(advanced_ranger_hbase_security_properties[each_key])
+
+ confirm_configurations = raw_input('please confirm the above configuration values y/n (n) : ')
+ if(confirm_configurations == ''):
+ confirm_configurations = 'n'
+ print ('Input registered as ' + str(confirm_configurations))
+
+
+ if(confirm_configurations.lower() == 'y'):
+ ranger_config_request_url = ambari_cluster_url
+ request_result = call_ambari_api(ranger_config_request_url, 'PUT', ambari_username_password, str(plugin_configuration_data))
+ if request_result is not None:
+ response_code = request_result.getcode()
+ response = json.loads(json.JSONEncoder().encode(request_result.read()))
+ if response_code == 200 and response is not None:
+ print('ranger hbase plugin configuration added successfully in ambari.')
+ return True
+ else:
+ print('ranger hbase plugin configuration add failed in ambari.')
+ return False
+ else:
+ print ('ranger hbase plugin configuration add failed in ambari.')
+ return False
+ else:
+ print ('exiting installation without configuration !')
+ sys.exit(0)
+ else:
+ print ('ranger hbase plugin configuration add failed in ambari.')
+ return False
+
+
+
+def port_ranger_knox_plugin_to_ambari():
+ print('trying to add ranger knox plugin.')
+ flag_knox_plugin_installed, knox_plugin_install_properties = get_knox_plugin_configuration()
+ if flag_knox_plugin_installed and knox_plugin_install_properties is not None:
+ print('Knox plugin is installed and enabled, adding to configurations')
+ advanced_ranger_knox_plugin_properties = dict()
+ advanced_ranger_knox_audit_properties = dict()
+ advanced_ranger_knox_policymgr_ssl_properties = dict()
+ advanced_ranger_knox_security_properties = dict()
+
+ advanced_ranger_knox_plugin_properties['policy_user'] = 'ambari-qa'
+ advanced_ranger_knox_plugin_properties['common.name.for.certificate'] = ''
+ advanced_ranger_knox_plugin_properties['ranger-knox-plugin-enabled'] = 'Yes'
+ advanced_ranger_knox_plugin_properties['REPOSITORY_CONFIG_USERNAME'] = 'admin'
+ advanced_ranger_knox_plugin_properties['REPOSITORY_CONFIG_PASSWORD'] = 'admin-password'
+ advanced_ranger_knox_plugin_properties['KNOX_HOME'] = '/usr/hdp/current/knox-server'
+
+ advanced_ranger_knox_audit_properties['xasecure.audit.is.enabled'] = knox_plugin_install_properties.get('xasecure.audit.is.enabled','true')
+ advanced_ranger_knox_audit_properties['xasecure.audit.destination.db'] = knox_plugin_install_properties.get('xasecure.audit.db.is.enabled','false')
+ advanced_ranger_knox_audit_properties['xasecure.audit.destination.db.jdbc.url'] = knox_plugin_install_properties.get('xasecure.audit.jpa.javax.persistence.jdbc.url','{{audit_jdbc_url}}')
+ advanced_ranger_knox_audit_properties['xasecure.audit.destination.db.user'] = knox_plugin_install_properties.get('xasecure.audit.jpa.javax.persistence.jdbc.user','{{xa_audit_db_user}}')
+ advanced_ranger_knox_audit_properties['xasecure.audit.destination.db.password'] = knox_plugin_install_properties.get('xasecure.audit.jpa.javax.persistence.jdbc.password','crypted')
+ advanced_ranger_knox_audit_properties['xasecure.audit.destination.db.jdbc.driver'] = knox_plugin_install_properties.get('xasecure.audit.jpa.javax.persistence.jdbc.driver','{{jdbc_driver}}')
+ advanced_ranger_knox_audit_properties['xasecure.audit.credential.provider.file'] = knox_plugin_install_properties.get('xasecure.audit.credential.provider.file','jceks://file{{credential_file}}')
+ advanced_ranger_knox_audit_properties['xasecure.audit.destination.db.batch.filespool.dir'] = knox_plugin_install_properties.get('xasecure.audit.destination.db.batch.filespool.dir','/var/log/knox/audit/db/spool')
+ advanced_ranger_knox_audit_properties['xasecure.audit.destination.hdfs'] = knox_plugin_install_properties.get('xasecure.audit.destination.hdfs','true')
+ advanced_ranger_knox_audit_properties['xasecure.audit.destination.hdfs.dir'] = knox_plugin_install_properties.get('xasecure.audit.destination.hdfs.dir','hdfs://NAMENODE_HOSTNAME:8020/ranger/audit')
+ advanced_ranger_knox_audit_properties['xasecure.audit.destination.hdfs.batch.filespool.dir'] = knox_plugin_install_properties.get('xasecure.audit.destination.hdfs.batch.filespool.dir','/var/log/knox/audit/hdfs/spool')
+ advanced_ranger_knox_audit_properties['xasecure.audit.destination.solr'] = knox_plugin_install_properties.get('xasecure.audit.destination.solr','false')
+ advanced_ranger_knox_audit_properties['xasecure.audit.destination.solr.urls'] = knox_plugin_install_properties.get('xasecure.audit.destination.solr.urls','{{ranger_audit_solr_urls}}')
+ advanced_ranger_knox_audit_properties['xasecure.audit.destination.solr.zookeepers'] = knox_plugin_install_properties.get('xasecure.audit.destination.solr.zookeepers','none')
+ advanced_ranger_knox_audit_properties['xasecure.audit.destination.solr.batch.filespool.dir'] = knox_plugin_install_properties.get('xasecure.audit.destination.solr.batch.filespool.dir','/var/log/knox/audit/solr/spool')
+ advanced_ranger_knox_audit_properties['xasecure.audit.provider.summary.enabled'] = knox_plugin_install_properties.get('xasecure.audit.provider.summary.enabled','false')
+
+ advanced_ranger_knox_policymgr_ssl_properties['xasecure.policymgr.clientssl.keystore'] = knox_plugin_install_properties.get('xasecure.policymgr.clientssl.keystore','/usr/hdp/current/knox-server/conf/ranger-plugin-keystore.jks')
+ advanced_ranger_knox_policymgr_ssl_properties['xasecure.policymgr.clientssl.keystore.password'] = knox_plugin_install_properties.get('xasecure.policymgr.clientssl.keystore.password','myKeyFilePassword')
+ advanced_ranger_knox_policymgr_ssl_properties['xasecure.policymgr.clientssl.truststore'] = knox_plugin_install_properties.get('xasecure.policymgr.clientssl.truststore','/usr/hdp/current/knox-server/conf/ranger-plugin-truststore.jks')
+ advanced_ranger_knox_policymgr_ssl_properties['xasecure.policymgr.clientssl.truststore.password'] = knox_plugin_install_properties.get('xasecure.policymgr.clientssl.truststore.password','changeit')
+ advanced_ranger_knox_policymgr_ssl_properties['xasecure.policymgr.clientssl.keystore.credential.file'] = knox_plugin_install_properties.get('xasecure.policymgr.clientssl.keystore.credential.file','jceks://file{{credential_file}}')
+ advanced_ranger_knox_policymgr_ssl_properties['xasecure.policymgr.clientssl.truststore.credential.file'] = knox_plugin_install_properties.get('xasecure.policymgr.clientssl.truststore.credential.file','jceks://file{{credential_file}}')
+
+ advanced_ranger_knox_security_properties['ranger.plugin.knox.service.name'] = knox_plugin_install_properties.get('ranger.plugin.knox.service.name','{{repo_name}}')
+ advanced_ranger_knox_security_properties['ranger.plugin.knox.policy.source.impl'] = knox_plugin_install_properties.get('ranger.plugin.knox.policy.source.impl','org.apache.ranger.admin.client.RangerAdminJersey2RESTClient')
+ advanced_ranger_knox_security_properties['ranger.plugin.knox.policy.rest.url'] = knox_plugin_install_properties.get('ranger.plugin.knox.policy.rest.url','{{policymgr_mgr_url}}')
+ advanced_ranger_knox_security_properties['ranger.plugin.knox.policy.rest.ssl.config.file'] = knox_plugin_install_properties.get('ranger.plugin.knox.policy.rest.ssl.config.file','/usr/hdp/current/knox-server/conf/ranger-policymgr-ssl.xml')
+ advanced_ranger_knox_security_properties['ranger.plugin.knox.policy.pollIntervalMs'] = knox_plugin_install_properties.get('ranger.plugin.knox.policy.pollIntervalMs','30000')
+ advanced_ranger_knox_security_properties['ranger.plugin.knox.policy.cache.dir'] = knox_plugin_install_properties.get('ranger.plugin.knox.policy.cache.dir','/etc/ranger/{{repo_name}}/policycache')
+
+
+ date_time_stamp = getDateTimeNow()
+ plugin_configuration_data = '[{"Clusters":{"desired_config":[{"type": "ranger-knox-plugin-properties", "service_config_version_note": "Initial configuration for Ranger KNOX plugin" ,"tag":"' + str(date_time_stamp) + '", "properties":' + json.dumps(
+ advanced_ranger_knox_plugin_properties) + ',"properties_attributes": {"final": "false"}},{"type": "ranger-knox-audit", "service_config_version_note": "Initial configuration for Ranger KNOX plugin" ,"tag":"' + str(date_time_stamp) + '", "properties":' + json.dumps(
+ advanced_ranger_knox_audit_properties) + ',"properties_attributes": {"final": "false"}},{"type": "ranger-knox-policymgr-ssl", "service_config_version_note": "Initial configuration for Ranger KNOX plugin" ,"tag":"' + str(date_time_stamp) + '", "properties":' + json.dumps(
+ advanced_ranger_knox_policymgr_ssl_properties) + ',"properties_attributes": {"final": "false"}},{"type": "ranger-knox-security", "service_config_version_note": "Initial configuration for Ranger KNOX plugin" ,"tag":"' + str(date_time_stamp) + '", "properties":' + json.dumps(
+ advanced_ranger_knox_security_properties) + ',"properties_attributes": {"final": "false"}}]}}]'
+
+ print ('####################### ranger_knox_plugin_properties configuration :')
+ for each_key in advanced_ranger_knox_plugin_properties:
+ print str(each_key) + ' = ' + str(advanced_ranger_knox_plugin_properties[each_key])
+
+ print ('####################### ranger_knox_audit_properties configuration :')
+ for each_key in advanced_ranger_knox_audit_properties:
+ print str(each_key) + ' = ' + str(advanced_ranger_knox_audit_properties[each_key])
+
+ print ('####################### ranger_knox_policymgr_ssl_properties configuration :')
+ for each_key in advanced_ranger_knox_policymgr_ssl_properties:
+ print str(each_key) + ' = ' + str(advanced_ranger_knox_policymgr_ssl_properties[each_key])
+
+ print ('####################### ranger_knox_security_properties configuration :')
+ for each_key in advanced_ranger_knox_security_properties:
+ print str(each_key) + ' = ' + str(advanced_ranger_knox_security_properties[each_key])
+
+ confirm_configurations = raw_input('please confirm the above configuration values y/n (n) : ')
+ if(confirm_configurations == ''):
+ confirm_configurations = 'n'
+ print ('input registered as ' + str(confirm_configurations))
+
+
+ if(confirm_configurations.lower() == 'y'):
+ ranger_config_request_url = ambari_cluster_url
+ request_result = call_ambari_api(ranger_config_request_url, 'PUT', ambari_username_password, str(plugin_configuration_data))
+ if request_result is not None:
+ response_code = request_result.getcode()
+ response = json.loads(json.JSONEncoder().encode(request_result.read()))
+ if response_code == 200 and response is not None:
+ print('ranger knox plugin configuration added successfully in ambari.')
+ return True
+ else:
+ print('ranger knox plugin configuration add failed in ambari.')
+ return False
+ else:
+ print('ranger knox plugin configuration add failed in ambari.')
+ return False
+ else:
+ print ('exiting installation without configuration !')
+ sys.exit(0)
+ else:
+ print('ranger knox plugin configuration add failed in ambari.')
+ return False
+
+
+def port_ranger_storm_plugin_to_ambari():
+ print('Trying to add ranger storm plugin.')
+ flag_storm_plugin_installed, storm_plugin_install_properties = get_storm_plugin_configuration()
+ if flag_storm_plugin_installed and storm_plugin_install_properties is not None:
+ print('Storm plugin is installed and enabled, adding to configurations')
+ storm_site_properties = get_storm_configs_from_ambari()
+ storm_site_properties['nimbus.authorizer'] = 'org.apache.ranger.authorization.storm.authorizer.RangerStormAuthorizer'
+
+ advanced_ranger_storm_plugin_properties = dict()
+ advanced_ranger_storm_audit_properties = dict()
+ advanced_ranger_storm_policymgr_ssl_properties = dict()
+ advanced_ranger_storm_security_properties = dict()
+
+ advanced_ranger_storm_plugin_properties['policy_user'] = 'storm'
+ advanced_ranger_storm_plugin_properties['common.name.for.certificate'] = ''
+ advanced_ranger_storm_plugin_properties['ranger-storm-plugin-enabled'] = 'Yes'
+ advanced_ranger_storm_plugin_properties['REPOSITORY_CONFIG_USERNAME'] = 'stormtestuser@EXAMPLE.COM'
+ advanced_ranger_storm_plugin_properties['REPOSITORY_CONFIG_PASSWORD'] = 'stormtestuser'
+
+
+ advanced_ranger_storm_audit_properties['xasecure.audit.is.enabled'] = storm_plugin_install_properties.get('xasecure.audit.db.is.enabled','true')
+ advanced_ranger_storm_audit_properties['xasecure.audit.destination.db'] = storm_plugin_install_properties.get('xasecure.audit.db.is.enabled','false')
+ advanced_ranger_storm_audit_properties['xasecure.audit.destination.db.jdbc.url'] = storm_plugin_install_properties.get('xasecure.audit.jpa.javax.persistence.jdbc.url','{{audit_jdbc_url}}')
+ advanced_ranger_storm_audit_properties['xasecure.audit.destination.db.user'] = storm_plugin_install_properties.get('xasecure.audit.jpa.javax.persistence.jdbc.user','{{xa_audit_db_user}}')
+ advanced_ranger_storm_audit_properties['xasecure.audit.destination.db.password'] = storm_plugin_install_properties.get('xasecure.audit.jpa.javax.persistence.jdbc.password','crypted')
+ advanced_ranger_storm_audit_properties['xasecure.audit.destination.db.jdbc.driver'] = storm_plugin_install_properties.get('xasecure.audit.jpa.javax.persistence.jdbc.driver','{{jdbc_driver}}')
+ advanced_ranger_storm_audit_properties['xasecure.audit.credential.provider.file'] = storm_plugin_install_properties.get('xasecure.audit.credential.provider.file','jceks://file{{credential_file}}')
+ advanced_ranger_storm_audit_properties['xasecure.audit.destination.db.batch.filespool.dir'] = storm_plugin_install_properties.get('xasecure.audit.destination.db.batch.filespool.dir','/var/log/storm/audit/db/spool')
+ advanced_ranger_storm_audit_properties['xasecure.audit.destination.hdfs'] = storm_plugin_install_properties.get('xasecure.audit.destination.hdfs','true')
+ advanced_ranger_storm_audit_properties['xasecure.audit.destination.hdfs.dir'] = storm_plugin_install_properties.get('xasecure.audit.destination.hdfs.dir','hdfs://NAMENODE_HOSTNAME:8020/ranger/audit')
+ advanced_ranger_storm_audit_properties['xasecure.audit.destination.hdfs.batch.filespool.dir'] = storm_plugin_install_properties.get('xasecure.audit.destination.hdfs.batch.filespool.dir','/var/log/storm/audit/hdfs/spool')
+ advanced_ranger_storm_audit_properties['xasecure.audit.destination.solr'] = storm_plugin_install_properties.get('xasecure.audit.destination.solr','false')
+ advanced_ranger_storm_audit_properties['xasecure.audit.destination.solr.urls'] = storm_plugin_install_properties.get('xasecure.audit.destination.solr.urls','{{ranger_audit_solr_urls}}')
+ advanced_ranger_storm_audit_properties['xasecure.audit.destination.solr.zookeepers'] = storm_plugin_install_properties.get('xasecure.audit.destination.solr.zookeepers','none')
+ advanced_ranger_storm_audit_properties['xasecure.audit.destination.solr.batch.filespool.dir'] = storm_plugin_install_properties.get('xasecure.audit.destination.solr.batch.filespool.dir','/var/log/storm/audit/solr/spool')
+ advanced_ranger_storm_audit_properties['xasecure.audit.provider.summary.enabled'] = storm_plugin_install_properties.get('xasecure.audit.provider.summary.enabled','false')
+
+
+ advanced_ranger_storm_policymgr_ssl_properties['xasecure.policymgr.clientssl.keystore'] = storm_plugin_install_properties.get('xasecure.policymgr.clientssl.keystore','/usr/hdp/current/storm-client/conf/ranger-plugin-keystore.jks')
+ advanced_ranger_storm_policymgr_ssl_properties['xasecure.policymgr.clientssl.keystore.password'] = storm_plugin_install_properties.get('xasecure.policymgr.clientssl.keystore.password','myKeyFilePassword')
+ advanced_ranger_storm_policymgr_ssl_properties['xasecure.policymgr.clientssl.truststore'] = storm_plugin_install_properties.get('xasecure.policymgr.clientssl.truststore','/usr/hdp/current/storm-client/conf/ranger-plugin-truststore.jks')
+ advanced_ranger_storm_policymgr_ssl_properties['xasecure.policymgr.clientssl.truststore.password'] = storm_plugin_install_properties.get('xasecure.policymgr.clientssl.truststore.password','changeit')
+ advanced_ranger_storm_policymgr_ssl_properties['xasecure.policymgr.clientssl.keystore.credential.file'] = storm_plugin_install_properties.get('xasecure.policymgr.clientssl.keystore.credential.file','jceks://file{{credential_file}}')
+ advanced_ranger_storm_policymgr_ssl_properties['xasecure.policymgr.clientssl.truststore.credential.file'] = storm_plugin_install_properties.get('xasecure.policymgr.clientssl.truststore.credential.file','jceks://file{{credential_file}}')
+
+
+ advanced_ranger_storm_security_properties['ranger.plugin.storm.service.name'] = storm_plugin_install_properties.get('ranger.plugin.storm.service.name','{{repo_name}}')
+ advanced_ranger_storm_security_properties['ranger.plugin.storm.policy.source.impl'] = storm_plugin_install_properties.get('ranger.plugin.storm.policy.source.impl','org.apache.ranger.admin.client.RangerAdminRESTClient')
+ advanced_ranger_storm_security_properties['ranger.plugin.storm.policy.rest.url'] = storm_plugin_install_properties.get('ranger.plugin.storm.policy.rest.url','{{policymgr_mgr_url}}')
+ advanced_ranger_storm_security_properties['ranger.plugin.storm.policy.rest.ssl.config.file'] = storm_plugin_install_properties.get('ranger.plugin.storm.policy.rest.ssl.config.file','/usr/hdp/current/storm-client/conf/ranger-policymgr-ssl.xml')
+ advanced_ranger_storm_security_properties['ranger.plugin.storm.policy.pollIntervalMs'] = storm_plugin_install_properties.get('ranger.plugin.storm.policy.pollIntervalMs','30000')
+ advanced_ranger_storm_security_properties['ranger.plugin.storm.policy.cache.dir'] = storm_plugin_install_properties.get('ranger.plugin.storm.policy.cache.dir','/etc/ranger/{{repo_name}}/policycache')
+
+
+ date_time_stamp = getDateTimeNow()
+ plugin_configuration_data = '[{"Clusters":{"desired_config":[{"type": "ranger-storm-plugin-properties", "service_config_version_note": "Initial configuration for Ranger STORM plugin" ,"tag":"' + str(date_time_stamp) + '", "properties":' + json.dumps(
+ advanced_ranger_storm_plugin_properties) + ',"properties_attributes": {"final": "false"}},{"type": "ranger-storm-audit", "service_config_version_note": "Initial configuration for Ranger STORM plugin" ,"tag":"' + str(date_time_stamp) + '", "properties":' + json.dumps(
+ advanced_ranger_storm_audit_properties) + ',"properties_attributes": {"final": "false"}},{"type": "ranger-storm-policymgr-ssl", "service_config_version_note": "Initial configuration for Ranger STORM plugin" ,"tag":"' + str(date_time_stamp) + '", "properties":' + json.dumps(
+ advanced_ranger_storm_policymgr_ssl_properties) + ',"properties_attributes": {"final": "false"}},{"type": "ranger-storm-security", "service_config_version_note": "Initial configuration for Ranger STORM plugin" ,"tag":"' + str(date_time_stamp) + '", "properties":' + json.dumps(
+ advanced_ranger_storm_security_properties) + ',"properties_attributes": {"final": "false"}}]}}]'
+
+ print ('####################### ranger_storm_plugin_properties configuration :')
+ for each_key in advanced_ranger_storm_plugin_properties:
+ print str(each_key) + ' = ' + str(advanced_ranger_storm_plugin_properties[each_key])
+
+ print ('####################### ranger_storm_audit_properties configuration :')
+ for each_key in advanced_ranger_storm_audit_properties:
+ print str(each_key) + ' = ' + str(advanced_ranger_storm_audit_properties[each_key])
+
+ print ('####################### ranger_storm_policymgr_ssl_properties configuration :')
+ for each_key in advanced_ranger_storm_policymgr_ssl_properties:
+ print str(each_key) + ' = ' + str(advanced_ranger_storm_policymgr_ssl_properties[each_key])
+
+ print ('####################### ranger_storm_security_properties configuration :')
+ for each_key in advanced_ranger_storm_security_properties:
+ print str(each_key) + ' = ' + str(advanced_ranger_storm_security_properties[each_key])
+
+
+
+ confirm_configurations = raw_input('please confirm the above configuration values y/n (n) : ')
+ if(confirm_configurations == ''):
+ confirm_configurations = 'n'
+ print ('Input registered as ' + str(confirm_configurations))
+
+
+ if(confirm_configurations.lower() == 'y'):
+ ranger_config_request_url = ambari_cluster_url
+ request_result = call_ambari_api(ranger_config_request_url, 'PUT', ambari_username_password, str(plugin_configuration_data))
+ if request_result is not None:
+ response_code = request_result.getcode()
+ response = json.loads(json.JSONEncoder().encode(request_result.read()))
+ if response_code == 200 and response is not None:
+ print('ranger storm plugin configuration added successfully in ambari.')
+ return True
+ else:
+ print('ranger storm plugin configuration add failed in ambari.')
+ return False
+ else:
+ print('ranger storm plugin configuration add failed in ambari.')
+ return False
+ else:
+ print ('exiting installation without configuration !')
+ sys.exit(0)
+ else:
+ print('ranger storm plugin configuration add failed in ambari.')
+ return False
+
+def port_ranger_kafka_plugin_to_ambari():
+ print('Trying to add ranger kafka plugin.')
+ flag_kafka_plugin_installed,kafka_plugin_installed_properties = get_kafka_plugin_configuration()
+ if flag_kafka_plugin_installed and kafka_plugin_installed_properties is not None:
+ advanced_ranger_kafka_plugin_properties = dict()
+ advanced_ranger_kafka_audit_properties = dict()
+ advanced_ranger_kafka_policymgr_ssl_properties = dict()
+ advanced_ranger_kafka_security_properties = dict()
+ advanced_kafka_log4j_properties = dict()
+
+ print('Kafka plugin is installed and enabled, adding to configurations')
+ advanced_kafka_broker_properties = get_kafka_configs_from_ambari()
+ advanced_kafka_broker_properties['authorizer.class.name'] = 'org.apache.ranger.authorization.kafka.authorizer.RangerKafkaAuthorizer'
+
+
+ advanced_ranger_kafka_plugin_properties['policy_user'] = 'ambari-qa'
+ advanced_ranger_kafka_plugin_properties['hadoop.rpc.protection'] = ''
+ advanced_ranger_kafka_plugin_properties['common.name.for.certificate'] = ''
+ advanced_ranger_kafka_plugin_properties['zookeeper.connect'] = 'localhost:2181'
+ advanced_ranger_kafka_plugin_properties['ranger-kafka-plugin-enabled'] = 'Yes'
+ advanced_ranger_kafka_plugin_properties['REPOSITORY_CONFIG_USERNAME'] = 'kafka'
+ advanced_ranger_kafka_plugin_properties['REPOSITORY_CONFIG_PASSWORD'] = 'kafka'
+
+
+ advanced_ranger_kafka_audit_properties['xasecure.audit.is.enabled'] = kafka_plugin_installed_properties.get('xasecure.audit.is.enabled','true')
+ advanced_ranger_kafka_audit_properties['xasecure.audit.destination.db'] = kafka_plugin_installed_properties.get('xasecure.audit.db.is.enabled','false')
+ advanced_ranger_kafka_audit_properties['xasecure.audit.destination.db.jdbc.url'] = kafka_plugin_installed_properties.get('xasecure.audit.jpa.javax.persistence.jdbc.url','{{audit_jdbc_url}}')
+ advanced_ranger_kafka_audit_properties['xasecure.audit.destination.db.user'] = kafka_plugin_installed_properties.get('xasecure.audit.jpa.javax.persistence.jdbc.user','{{xa_audit_db_user}}')
+ advanced_ranger_kafka_audit_properties['xasecure.audit.destination.db.password'] = kafka_plugin_installed_properties.get('xasecure.audit.jpa.javax.persistence.jdbc.password','crypted')
+ advanced_ranger_kafka_audit_properties['xasecure.audit.destination.db.jdbc.driver'] = kafka_plugin_installed_properties.get('xasecure.audit.jpa.javax.persistence.jdbc.driver','{{jdbc_driver}}')
+ advanced_ranger_kafka_audit_properties['xasecure.audit.credential.provider.file'] = kafka_plugin_installed_properties.get('xasecure.audit.credential.provider.file','jceks://file{{credential_file}}')
+ advanced_ranger_kafka_audit_properties['xasecure.audit.destination.db.batch.filespool.dir'] = kafka_plugin_installed_properties.get('xasecure.audit.destination.db.batch.filespool.dir','/var/log/kafka/audit/db/spool')
+ advanced_ranger_kafka_audit_properties['xasecure.audit.destination.hdfs'] = kafka_plugin_installed_properties.get('xasecure.audit.destination.hdfs','true')
+ advanced_ranger_kafka_audit_properties['xasecure.audit.destination.hdfs.dir'] = kafka_plugin_installed_properties.get('xasecure.audit.destination.hdfs.dir','hdfs://NAMENODE_HOSTNAME:8020/ranger/audit')
+ advanced_ranger_kafka_audit_properties['xasecure.audit.destination.hdfs.batch.filespool.dir'] = kafka_plugin_installed_properties.get('xasecure.audit.destination.hdfs.batch.filespool.dir','/var/log/kafka/audit/hdfs/spool')
+ advanced_ranger_kafka_audit_properties['xasecure.audit.destination.solr'] = kafka_plugin_installed_properties.get('xasecure.audit.destination.solr','true')
+ advanced_ranger_kafka_audit_properties['xasecure.audit.destination.solr.urls'] = kafka_plugin_installed_properties.get('xasecure.audit.destination.solr.urls','{{ranger_audit_solr_urls}}')
+ advanced_ranger_kafka_audit_properties['xasecure.audit.destination.solr.zookeepers'] = kafka_plugin_installed_properties.get('xasecure.audit.db.is.enabledxasecure.audit.destination.solr.zookeepers','none')
+ advanced_ranger_kafka_audit_properties['xasecure.audit.destination.solr.batch.filespool.dir'] = kafka_plugin_installed_properties.get('xasecure.audit.destination.solr.batch.filespool.dir','/var/log/kafka/audit/solr/spool')
+ advanced_ranger_kafka_audit_properties['xasecure.audit.provider.summary.enabled'] = kafka_plugin_installed_properties.get('xasecure.audit.db.is.enabled','true')
+
+ advanced_ranger_kafka_policymgr_ssl_properties['xasecure.policymgr.clientssl.keystore'] = kafka_plugin_installed_properties.get('xasecure.policymgr.clientssl.keystore','/usr/hdp/current/kafka-broker/config/ranger-plugin-keystore.jks')
+ advanced_ranger_kafka_policymgr_ssl_properties['xasecure.policymgr.clientssl.keystore.password'] = kafka_plugin_installed_properties.get('xasecure.policymgr.clientssl.keystore.password','myKeyFilePassword')
+ advanced_ranger_kafka_policymgr_ssl_properties['xasecure.policymgr.clientssl.truststore'] = kafka_plugin_installed_properties.get('xasecure.policymgr.clientssl.truststore','/usr/hdp/current/kafka-broker/config/ranger-plugin-truststore.jks')
+ advanced_ranger_kafka_policymgr_ssl_properties['xasecure.policymgr.clientssl.truststore.password'] = kafka_plugin_installed_properties.get('xasecure.policymgr.clientssl.truststore.password','changeit')
+ advanced_ranger_kafka_policymgr_ssl_properties['xasecure.policymgr.clientssl.keystore.credential.file'] = kafka_plugin_installed_properties.get('xasecure.policymgr.clientssl.keystore.credential.file','jceks://file/{{credential_file}}')
+ advanced_ranger_kafka_policymgr_ssl_properties['xasecure.policymgr.clientssl.truststore.credential.file'] = kafka_plugin_installed_properties.get('xasecure.policymgr.clientssl.truststore.credential.file','jceks://file/{{credential_file}}')
+
+ advanced_ranger_kafka_security_properties['ranger.plugin.kafka.service.name'] = kafka_plugin_installed_properties.get('ranger.plugin.kafka.service.name','{{repo_name}}')
+ advanced_ranger_kafka_security_properties['ranger.plugin.kafka.policy.source.impl'] = kafka_plugin_installed_properties.get('ranger.plugin.kafka.policy.source.impl','org.apache.ranger.admin.client.RangerAdminRESTClient')
+ advanced_ranger_kafka_security_properties['ranger.plugin.kafka.policy.rest.url'] = kafka_plugin_installed_properties.get('ranger.plugin.kafka.policy.rest.url','{{policymgr_mgr_url}}')
+ advanced_ranger_kafka_security_properties['ranger.plugin.kafka.policy.rest.ssl.config.file'] = kafka_plugin_installed_properties.get('ranger.plugin.kafka.policy.rest.ssl.config.file','/etc/kafka/conf/ranger-policymgr-ssl.xml')
+ advanced_ranger_kafka_security_properties['ranger.plugin.kafka.policy.pollIntervalMs'] = kafka_plugin_installed_properties.get('ranger.plugin.kafka.policy.pollIntervalMs','30000')
+ advanced_ranger_kafka_security_properties['ranger.plugin.kafka.policy.cache.dir'] = kafka_plugin_installed_properties.get('ranger.plugin.kafka.policy.cache.dir','/etc/ranger/{{repo_name}}/policycache')
+
+ advanced_kafka_log4j_properties['content'] = kafka_plugin_installed_properties.get('kafka.log4j.properties','')
+
+ date_time_stamp = getDateTimeNow()
+ plugin_configuration_data = '[{"Clusters":{"desired_config":[{"type": "kafka-broker", "service_config_version_note": "Initial configuration for Ranger KAFKA plugin" ,"tag":"' + str(date_time_stamp) + '", "properties":' + json.dumps(
+ advanced_kafka_broker_properties) + ',"properties_attributes": {"final": "false"}},{"type": "kafka-log4j", "service_config_version_note": "Initial configuration for Ranger KAFKA plugin" ,"tag":"' + str(date_time_stamp) + '", "properties":' + json.dumps(
+ advanced_kafka_log4j_properties) + ',"properties_attributes": {"final": "false"}},{"type": "ranger-kafka-plugin-properties", "service_config_version_note": "Initial configuration for Ranger KAFKA plugin" ,"tag":"' + str(date_time_stamp) + '", "properties":' + json.dumps(
+ advanced_ranger_kafka_plugin_properties) + ',"properties_attributes": {"final": "false"}},{"type": "ranger-kafka-audit", "service_config_version_note": "Initial configuration for Ranger KAFKA plugin" ,"tag":"' + str(date_time_stamp) + '", "properties":' + json.dumps(
+ advanced_ranger_kafka_audit_properties) + ',"properties_attributes": {"final": "false"}},{"type": "ranger-kafka-policymgr-ssl", "service_config_version_note": "Initial configuration for Ranger KAFKA plugin" ,"tag":"' + str(date_time_stamp) + '", "properties":' + json.dumps(
+ advanced_ranger_kafka_policymgr_ssl_properties) + ',"properties_attributes": {"final": "false"}},{"type": "ranger-kafka-security", "service_config_version_note": "Initial configuration for Ranger KAFKA plugin" ,"tag":"' + str(date_time_stamp) + '", "properties":' + json.dumps(
+ advanced_ranger_kafka_security_properties) + ',"properties_attributes": {"final": "false"}}]}}]'
+
+
+ print ('####################### kafka_broker_properties configuration :')
+ for each_key in advanced_kafka_broker_properties:
+ print str(each_key) + ' = ' + str(advanced_kafka_broker_properties[each_key])
+
+ print ('####################### kafka_log4j_properties configuration :')
+ for each_key in advanced_kafka_log4j_properties:
+ print str(each_key) + ' = ' + str(advanced_kafka_log4j_properties[each_key])
+
+
+ print ('####################### ranger_kafka_plugin_properties configuration :')
+ for each_key in advanced_ranger_kafka_plugin_properties:
+ print str(each_key) + ' = ' + str(advanced_ranger_kafka_plugin_properties[each_key])
+
+ print ('####################### ranger_kafka_audit_properties configuration :')
+ for each_key in advanced_ranger_kafka_audit_properties:
+ print str(each_key) + ' = ' + str(advanced_ranger_kafka_audit_properties[each_key])
+
+ print ('####################### ranger_kafka_policymgr_ssl_properties configuration :')
+ for each_key in advanced_ranger_kafka_policymgr_ssl_properties:
+ print str(each_key) + ' = ' + str(advanced_ranger_kafka_policymgr_ssl_properties[each_key])
+
+ print ('####################### ranger_kafka_security_properties configuration :')
+ for each_key in advanced_ranger_kafka_security_properties:
+ print str(each_key) + ' = ' + str(advanced_ranger_kafka_security_properties[each_key])
+
+ confirm_configurations = raw_input('please confirm the above configuration values y/n (n) : ')
+ if(confirm_configurations == ''):
+ confirm_configurations = 'n'
+ print ('input registered as ' + str(confirm_configurations))
+
+
+ if(confirm_configurations.lower() == 'y'):
+ ranger_config_request_url = ambari_cluster_url
+ request_result = call_ambari_api(ranger_config_request_url, 'PUT', ambari_username_password, str(plugin_configuration_data))
+ if request_result is not None:
+ response_code = request_result.getcode()
+ response = json.loads(json.JSONEncoder().encode(request_result.read()))
+ if response_code == 200 and response is not None:
+ print('ranger kafka plugin configuration added successfully in ambari.')
+ return True
+ else:
+ print('ranger kafka plugin configuration add failed in ambari.')
+ return False
+ else:
+ print('ranger kafka plugin configuration add failed in ambari.')
+ return False
+ else:
+ print ('exiting installation without configuration !')
+ sys.exit(0)
+ else:
+ print('ranger kafka plugin configuration add failed in ambari.')
+ return False
+
+
+
+def get_hdfs_plugin_configuration():
+ flag_hdfs_plugin_installed = False
+ hdfs_plugin_install_properties = dict()
+ print('hdfs plugin is present and installed to ranger,getting additional properties from installed files.')
+ base_hadoop_conf_path = '/etc/hadoop/conf/'
+ hdfs_site_xml_path = os.path.join(base_hadoop_conf_path, 'hdfs-site.xml')
+ hdfs_site_xml_properties = import_properties_from_xml(hdfs_site_xml_path)
+ ranger_audit_xml_path = os.path.join(base_hadoop_conf_path, 'ranger-hdfs-audit.xml')
+ hdfs_plugin_install_properties = import_properties_from_xml(ranger_audit_xml_path, hdfs_plugin_install_properties)
+ ranger_hdfs_security_xml_path = os.path.join(base_hadoop_conf_path, 'ranger-hdfs-security.xml')
+ hdfs_plugin_install_properties = import_properties_from_xml(ranger_hdfs_security_xml_path, hdfs_plugin_install_properties)
+ ranger_policy_ssl_xml_path = os.path.join(base_hadoop_conf_path, 'ranger-policymgr-ssl.xml')
+ hdfs_plugin_install_properties = import_properties_from_xml(ranger_policy_ssl_xml_path, hdfs_plugin_install_properties)
+ flag_plugin_installed = check_plugin_enabled('hdfs', hdfs_plugin_install_properties)
+ if(flag_plugin_installed):
+ flag_hdfs_plugin_installed = True
+ return flag_hdfs_plugin_installed, hdfs_plugin_install_properties, hdfs_site_xml_properties
+
+
+def get_yarn_plugin_configuration():
+ flag_yarn_plugin_installed = False
+ yarn_plugin_installed_properties = dict()
+ print('yarn plugin is present and installed to ranger,getting additional properties from installed files.')
+ base_yarn_conf_path = '/etc/hadoop/conf/'
+ yarn_site_xml_path = os.path.join(base_yarn_conf_path,'yarn-site.xml')
+ yarn_site_xml_properties = import_properties_from_xml(yarn_site_xml_path)
+ ranger_yarn_audit_properties_path = os.path.join(base_yarn_conf_path,'ranger-yarn-audit.xml')
+ yarn_plugin_installed_properties = import_properties_from_xml(ranger_yarn_audit_properties_path, yarn_plugin_installed_properties)
+ ranger_yarn_security_properties_path = os.path.join(base_yarn_conf_path,'ranger-yarn-security.xml')
+ yarn_plugin_installed_properties = import_properties_from_xml(ranger_yarn_security_properties_path, yarn_plugin_installed_properties)
+ ranger_policymgr_ssl_properties_path = os.path.join(base_yarn_conf_path,'ranger-policymgr-ssl.xml')
+ yarn_plugin_installed_properties = import_properties_from_xml(ranger_policymgr_ssl_properties_path, yarn_plugin_installed_properties)
+ flag_plugin_installed = check_plugin_enabled('yarn', yarn_plugin_installed_properties)
+ if(flag_plugin_installed):
+ flag_yarn_plugin_installed = True
+ return flag_yarn_plugin_installed,yarn_plugin_installed_properties,yarn_site_xml_properties
+
+
+def get_hive_plugin_configuration():
+ flag_hive_plugin_installed = False
+ hive_plugin_install_properties = dict()
+ print('hive plugin is present and installed to ranger, configuring to setup in ambari.')
+ base_hive_conf_path = '/etc/hive/conf/conf.server/'
+ hive_server2_xml_path = os.path.join(base_hive_conf_path, 'hiveserver2-site.xml')
+ hive_server2_xml_properties = import_properties_from_xml(hive_server2_xml_path)
+ ranger_audit_xml_path = os.path.join(base_hive_conf_path, 'ranger-hive-audit.xml')
+ hive_plugin_install_properties = import_properties_from_xml(ranger_audit_xml_path, hive_plugin_install_properties)
+ ranger_hive_security_xml_path = os.path.join(base_hive_conf_path, 'ranger-hive-security.xml')
+ hive_plugin_install_properties = import_properties_from_xml(ranger_hive_security_xml_path, hive_plugin_install_properties)
+ ranger_policy_ssl_xml_path = os.path.join(base_hive_conf_path, 'ranger-policymgr-ssl.xml')
+ hive_plugin_install_properties = import_properties_from_xml(ranger_policy_ssl_xml_path, hive_plugin_install_properties)
+ flag_plugin_installed = check_plugin_enabled('hive', hive_plugin_install_properties)
+
+ if(flag_plugin_installed):
+ flag_hive_plugin_installed = True
+ return flag_hive_plugin_installed, hive_plugin_install_properties, hive_server2_xml_properties
+
+def get_hive_configs_from_ambari():
+ desired_config_url = ambari_cluster_url + '?fields=Clusters/desired_configs'
+ request_result = call_ambari_api(desired_config_url,'GET',ambari_username_password,None)
+ response_code = None
+ desired_configs_response = None
+ if request_result is not None:
+ response_code = request_result.getcode()
+ desired_configs_response = json.loads(json.JSONEncoder().encode(request_result.read()))
+
+ hive_site_tag = str(json.loads(desired_configs_response)['Clusters']['desired_configs']['hive-site']['tag'])
+ hive_env_tag = str(json.loads(desired_configs_response)['Clusters']['desired_configs']['hive-env']['tag'])
+
+ hive_env_properties_url = ambari_cluster_url + '/configurations?type=hive-env&tag='+hive_env_tag
+ hive_env_properties_response = None
+ print ('hive_env_properties_url = ' + str(hive_env_properties_url))
+ request_result = call_ambari_api(hive_env_properties_url,'GET',ambari_username_password,None)
+ if request_result is not None:
+ response_code = request_result.getcode()
+ hive_env_properties_response = json.loads(json.JSONEncoder().encode(request_result.read()))
+ print 'hive-env len response = ' , len(json.loads(hive_env_properties_response)['items'])
+ hive_env_properties = json.loads(hive_env_properties_response)['items'][0]['properties']
+ print ('hive_env_properties = ' + str(hive_env_properties))
+
+ hive_site_properties_url = ambari_cluster_url + '/configurations?type=hive-site&tag='+hive_site_tag
+ hive_site_properties_response = None
+ request_result = call_ambari_api(hive_site_properties_url,'GET',ambari_username_password,None)
+ if request_result is not None:
+ response_code = request_result.getcode()
+ hive_site_properties_response = json.loads(json.JSONEncoder().encode(request_result.read()))
+ print 'hive-site len response = ' , len(json.loads(hive_site_properties_response)['items'])
+ hive_site_properties = json.loads(hive_site_properties_response)['items'][0]['properties']
+ print ('hive_site_properties = ' + str(hive_site_properties))
+
+ return hive_env_properties,hive_site_properties
+
+
+
+def get_hbase_plugin_configuration():
+ flag_hbase_plugin_installed = False
+ hbase_plugin_install_properties = dict()
+ print('hbase plugin is present and installed to ranger, configuring to setup in ambari.')
+ base_hbase_conf_path = '/etc/hbase/conf/'
+ hbase_site_xml_path = os.path.join(base_hbase_conf_path, 'hbase-site.xml')
+ hbase_site_xml_properties = import_properties_from_xml(hbase_site_xml_path)
+ ranger_audit_xml_path = os.path.join(base_hbase_conf_path, 'ranger-hbase-audit.xml')
+ hbase_plugin_install_properties = import_properties_from_xml(ranger_audit_xml_path, hbase_plugin_install_properties)
+ ranger_hbase_security_xml_path = os.path.join(base_hbase_conf_path, 'ranger-hbase-security.xml')
+ hbase_plugin_install_properties = import_properties_from_xml(ranger_hbase_security_xml_path, hbase_plugin_install_properties)
+ ranger_policy_ssl_xml_path = os.path.join(base_hbase_conf_path, 'ranger-policymgr-ssl.xml')
+ hbase_plugin_install_properties = import_properties_from_xml(ranger_policy_ssl_xml_path, hbase_plugin_install_properties)
+ flag_plugin_installed = check_plugin_enabled('hbase', hbase_plugin_install_properties)
+ if(flag_plugin_installed):
+ flag_hbase_plugin_installed = True
+ return flag_hbase_plugin_installed, hbase_plugin_install_properties, hbase_site_xml_properties
+
+
+def get_knox_plugin_configuration():
+ flag_knox_plugin_installed = False
+ knox_plugin_install_properties = dict()
+ print('knox plugin is present and installed to ranger, configuring to setup in ambari.')
+ base_knox_conf_path = '/etc/knox/conf/'
+ ranger_audit_xml_path = os.path.join(base_knox_conf_path, 'ranger-knox-audit.xml')
+ knox_plugin_install_properties = import_properties_from_xml(ranger_audit_xml_path, knox_plugin_install_properties)
+ ranger_knox_security_xml_path = os.path.join(base_knox_conf_path, 'ranger-knox-security.xml')
+ knox_plugin_install_properties = import_properties_from_xml(ranger_knox_security_xml_path, knox_plugin_install_properties)
+ ranger_policy_ssl_xml_path = os.path.join(base_knox_conf_path, 'ranger-policymgr-ssl.xml')
+ knox_plugin_install_properties = import_properties_from_xml(ranger_policy_ssl_xml_path, knox_plugin_install_properties)
+ flag_plugin_installed = check_plugin_enabled('knox', knox_plugin_install_properties)
+ if(flag_plugin_installed):
+ flag_knox_plugin_installed = True
+ return flag_knox_plugin_installed, knox_plugin_install_properties
+
+
+
+def get_storm_plugin_configuration():
+ flag_storm_plugin_installed = False
+ storm_plugin_install_properties = dict()
+ print('storm plugin is present and installed to ranger, configuring to setup in ambari.')
+ base_storm_conf_path = '/etc/storm/conf/'
+ ranger_audit_xml_path = os.path.join(base_storm_conf_path, 'ranger-storm-audit.xml')
+ storm_plugin_install_properties = import_properties_from_xml(ranger_audit_xml_path, storm_plugin_install_properties)
+ ranger_storm_security_xml_path = os.path.join(base_storm_conf_path, 'ranger-storm-security.xml')
+ storm_plugin_install_properties = import_properties_from_xml(ranger_storm_security_xml_path, storm_plugin_install_properties)
+ ranger_policy_ssl_xml_path = os.path.join(base_storm_conf_path, 'ranger-policymgr-ssl.xml')
+ storm_plugin_install_properties = import_properties_from_xml(ranger_policy_ssl_xml_path, storm_plugin_install_properties)
+ flag_plugin_installed = check_plugin_enabled('storm', storm_plugin_install_properties)
+ if(flag_plugin_installed):
+ flag_storm_plugin_installed = True
+ return flag_storm_plugin_installed, storm_plugin_install_properties
+
+
+def get_storm_configs_from_ambari():
+ desired_config_url = ambari_cluster_url + '?fields=Clusters/desired_configs'
+ request_result = call_ambari_api(desired_config_url,'GET',ambari_username_password,None)
+ response_code = None
+ desired_configs_response = None
+ if request_result is not None:
+ response_code = request_result.getcode()
+ desired_configs_response = json.loads(json.JSONEncoder().encode(request_result.read()))
+
+ storm_site_tag = str(json.loads(desired_configs_response)['Clusters']['desired_configs']['storm-site']['tag'])
+ print ('storm_site_tag = ' + storm_site_tag)
+
+ kafka_broker_properties_url = ambari_cluster_url + '/configurations?type=storm-site&tag='+storm_site_tag
+
+ request_result = call_ambari_api(kafka_broker_properties_url,'GET',ambari_username_password,None)
+ if request_result is not None:
+ response_code = request_result.getcode()
+ response = json.loads(json.JSONEncoder().encode(request_result.read()))
+ print 'storm-site len response = ' , len(json.loads(response)['items'])
+ storm_site_properties = json.loads(response)['items'][0]['properties']
+ print ('storm_site_properties = ' + str(storm_site_properties))
+
+ return storm_site_properties
+
+
+
+
+def get_kafka_plugin_configuration():
+ flag_kafka_plugin_installed = False
+ kafka_plugin_install_properties = dict()
+ print('kafka plugin is present and installed to ranger configuring to setup ambari')
+ base_kafka_conf_path = '/etc/kafka/conf/'
+ ranger_audit_xml_path = os.path.join(base_kafka_conf_path,'ranger-kafka-audit.xml')
+ kafka_plugin_install_properties = import_properties_from_xml(ranger_audit_xml_path, kafka_plugin_install_properties)
+ ranger_kafka_security_xml_path = os.path.join(base_kafka_conf_path,'ranger-kafka-security.xml')
+ kafka_plugin_install_properties = import_properties_from_xml(ranger_kafka_security_xml_path, kafka_plugin_install_properties)
+ ranger_policymgr_ssl_xml_path = os.path.join(base_kafka_conf_path,'ranger-policymgr-ssl.xml')
+ kafka_plugin_install_properties = import_properties_from_xml(ranger_policymgr_ssl_xml_path, kafka_plugin_install_properties)
+ kafka_log4j_xml_path = os.path.join(base_kafka_conf_path,'log4j.properties')
+ kafka_plugin_install_properties['kafka.log4j.properties'] = read_properties_file(kafka_log4j_xml_path)
+
+ flag_plugin_installed = check_plugin_enabled('kafka', kafka_plugin_install_properties)
+ if flag_plugin_installed:
+ flag_kafka_plugin_installed = True
+ return flag_kafka_plugin_installed, kafka_plugin_install_properties
+
+def get_kafka_configs_from_ambari():
+ desired_config_url = ambari_cluster_url + '?fields=Clusters/desired_configs'
+ request_result = call_ambari_api(desired_config_url,'GET',ambari_username_password,None)
+ response_code = None
+ desired_configs_response = None
+ if request_result is not None:
+ response_code = request_result.getcode()
+ desired_configs_response = json.loads(json.JSONEncoder().encode(request_result.read()))
+
+ kafka_broker_tag = str(json.loads(desired_configs_response)['Clusters']['desired_configs']['kafka-broker']['tag'])
+ print ('kafka_broker_tag = ' + kafka_broker_tag)
+
+ kafka_broker_properties_url = ambari_cluster_url + '/configurations?type=kafka-broker&tag='+kafka_broker_tag
+
+ request_result = call_ambari_api(kafka_broker_properties_url,'GET',ambari_username_password,None)
+ if request_result is not None:
+ response_code = request_result.getcode()
+ response = json.loads(json.JSONEncoder().encode(request_result.read()))
+ print 'kafka-broker len response = ' , len(json.loads(response)['items'])
+ kafka_broker_properties = json.loads(response)['items'][0]['properties']
+ print ('kafka_broker_properties = ' + str(kafka_broker_properties))
+
+ return kafka_broker_properties
+
+
+
+def check_plugin_enabled(component_name, component_plugin_install_properties):
+ flag_plugin_installed = False
+ repository_key = 'ranger.plugin.' + component_name + '.service.name'
+ if not (str(component_plugin_install_properties[repository_key]).strip() == ''):
+ repo_base_path = os.path.join('/etc/ranger', component_plugin_install_properties[repository_key])
+ print('repo_base_path = ' + str(repo_base_path))
+ if os.path.exists(repo_base_path):
+ print('Plugin is installed for component ' + component_name)
+ flag_plugin_installed = True
+ return flag_plugin_installed
+
+
+def call_ambari_api(ambari_url, method, username_password, data):
+ try:
+ url = ambari_url
+ base64string = base64.encodestring('{0}'.format(username_password)).replace('\n', '')
+ headers = {"X-Requested-By": "ambari"}
+ request = urllib2.Request(url, data, headers, 'compressed')
+ request.get_method = lambda: method
+ request.add_header("Authorization", "Basic {0}".format(base64string))
+ result = urllib2.urlopen(request)
+ return result
+ except urllib2.URLError, e:
+ if isinstance(e, urllib2.HTTPError):
+ print("HTTP Code: {0}".format(e.code))
+ print("HTTP Data: {0}".format(e.read()))
+ return e
+ else:
+ print("Error: {0}".format(e.reason))
+ print ('ambari server is not reachable, please make sure valid ambari server url has been provided and ambari server is started.')
+ return e
+ except httplib.BadStatusLine:
+ print("ambari service is not reachable, please restart the service and then try again")
+ return None
+
+
+def import_properties_from_file(install_properties_path, properties_from_file=None):
+ if properties_from_file is None:
+ print('properties_from_file is none initializing to dict')
+ properties_from_file = dict()
+ if os.path.isfile(install_properties_path):
+ install_properties_file = open(install_properties_path)
+ for each_line in install_properties_file.read().split('\n'):
+ each_line = each_line.strip()
+ if len(each_line) == 0: continue
+ if '#https.service.port' in each_line:
+ each_line = each_line.strip('#')
+ if '#' in each_line: continue
+ key, value = each_line.strip().split("=", 1)
+ key = key.strip()
+ value = value.strip()
+ properties_from_file[key] = value
+ else:
+ print('Property file not found at path : ' + str(install_properties_path))
+ return properties_from_file
+
+def read_properties_file(properties_file_path):
+ file_text = ''
+ if(os.path.isfile(properties_file_path)):
+ print('property file exists reading file content')
+ file_text = open(properties_file_path,'r').read()
+ else:
+ print('file not found at path : ' + str(properties_file_path))
+ return file_text
+
+
+
+def import_properties_from_xml(xml_path, properties_from_xml=None):
+ print('getting values from file : ' + str(xml_path))
+ if os.path.isfile(xml_path):
+ xml = ET.parse(xml_path)
+ root = xml.getroot()
+ if properties_from_xml is None:
+ properties_from_xml = dict()
+ for child in root.findall('property'):
+ name = child.find("name").text.strip()
+ value = child.find("value").text.strip() if child.find("value").text is not None else ""
+ properties_from_xml[name] = value
+ else:
+ print('XML file not found at path : ' + str(xml_path))
+ return properties_from_xml
+
+
+def get_authentication_method():
+ print('Getting authentication method for ranger services')
+ ranger_conf_path = '/etc/ranger/admin/conf'
+ security_appln_context_path = os.path.join(ranger_conf_path,'security-applicationContext.xml')
+ print ('security_appln_context_path = ' + security_appln_context_path)
+ app_context_xml_tree = ET.parse(security_appln_context_path)
+ app_context_xml_root = app_context_xml_tree.getroot()
+ reference_auth_method = None
+ authentication_method = None
+ for child_nodes in app_context_xml_root.getiterator():
+ if( ('authentication-provider' in str(child_nodes.tag)) and not('-ref' in str(child_nodes.attrib)) ):
+ reference_auth_method = child_nodes.attrib['ref']
+
+ if( reference_auth_method is not None and 'jaasAuthProvider' in reference_auth_method):
+ authentication_method = 'UNIX'
+ elif( reference_auth_method is not None and 'activeDirectoryAuthenticationProvider' in reference_auth_method):
+ authentication_method = 'ACTIVE_DIRECTORY'
+ elif( reference_auth_method is not None and 'ldapAuthProvider' in reference_auth_method):
+ authentication_method = 'LDAP'
+ else:
+ authentication_method = 'NONE'
+
+ return authentication_method
+
+
+
+def call_keystore(libpath, aliasKey, aliasValue, filepath, getorcreateorlist):
+ finalLibPath = libpath.replace('\\', '/').replace('//', '/')
+ finalFilePath = 'jceks://file/' + filepath.replace('\\', '/').replace('//', '/')
+ if getorcreateorlist == 'create':
+ commandtorun = ['java', '-cp', finalLibPath, 'org.apache.ranger.credentialapi.buildks', 'create', aliasKey, '-value', aliasValue, '-provider', finalFilePath]
+ p = Popen(commandtorun, stdin=PIPE, stdout=PIPE, stderr=PIPE)
+ output, error = p.communicate()
+ statuscode = p.returncode
+ return statuscode
+ elif getorcreateorlist == 'get':
+ commandtorun = ['java', '-cp', finalLibPath, 'org.apache.ranger.credentialapi.buildks', 'get', aliasKey, '-provider', finalFilePath]
+ p = Popen(commandtorun, stdin=PIPE, stdout=PIPE, stderr=PIPE)
+ output, error = p.communicate()
+ statuscode = p.returncode
+ return statuscode, output
+ elif getorcreateorlist == 'list':
+ commandtorun = ['java', '-cp', finalLibPath, 'org.apache.ranger.credentialapi.buildks', 'list', '-provider', finalFilePath]
+ p = Popen(commandtorun, stdin=PIPE, stdout=PIPE, stderr=PIPE)
+ output, error = p.communicate()
+ statuscode = p.returncode
+ return statuscode, output
+ else:
+ print('proper command not received for input need get or create')
+
+
+def get_hdp_version():
+ return_code = -1
+ hdp_output = ''
+ hdp_version = None
+ match = None
+ statuscode = -1
+ try:
+ command_to_run = 'hdp-select status hadoop-client'
+ output = Popen(command_to_run, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)
+ return_code, error = output.communicate()
+ statuscode = output.returncode
+ except Exception, e:
+ print('Error : ' + str(e))
+ if statuscode == 0:
+ hdp_version = re.sub('hadoop-client - ', '', return_code)
+ hdp_version = hdp_version.rstrip()
+ match = re.match('[0-9]+.[0-9]+.[0-9]+.[0-9]+-[0-9]+', hdp_version)
+ print ('hdp_version = ' + hdp_version)
+ else:
+ print('Unable to determine the current version because of a non-zero return code of {0}'.format(str(return_code)))
+
+ if match is None:
+ print('Failed to get extracted version')
+ return None
+ else:
+ return hdp_version
+
+def getDateTimeNow():
+ return datetime.datetime.now().strftime("%Y%m%d%H%M%S")
+
+
+if __name__ == '__main__':
+
+
+ if len(sys.argv) > 1:
+ function_to_call = sys.argv[1] if len(sys.argv) > 1 else None
+ base_url = sys.argv[2] if len(sys.argv) > 2 else None
+ print ('base url = ' + base_url)
+ ambari_username_password = sys.argv[3] if len(sys.argv) > 3 else None
+ print ('ambari_username_password = ' + ambari_username_password)
+ cluster_name = sys.argv[4] if len(sys.argv) > 4 else None
+ print ('cluster_name = ' + cluster_name)
+ ranger_admin_fqdn = sys.argv[5] if len(sys.argv) > 5 else None
+ print ('ranger_admin_fqdn = ' + ranger_admin_fqdn)
+ ranger_service_name = 'RANGER'
+ admin_component_name = 'RANGER_ADMIN'
+ usersync_component_name = 'RANGER_USERSYNC'
+ ambari_cluster_url = str(base_url) + '/api/v1/clusters/' + str(cluster_name)
+ ambari_service_url = str(ambari_cluster_url) + '/services'
+ hdp_dir = os.path.join('/usr', 'hdp')
+ hdp_current_dir = os.path.join(hdp_dir, 'current')
+ hdp_version = get_hdp_version()
+ print('Found hdp_version = ' + str(hdp_version))
+ hdp_version_dir = os.path.join(hdp_dir, hdp_version)
+ if function_to_call is not None and len(function_to_call) > 0:
+ print('Found first argument as : ' + function_to_call)
+ function_to_call = int(function_to_call)
+ if function_to_call == 1:
+ print('Porting ranger admin installation details to ambari.')
+ port_ranger_admin_installation_to_ambari()
+ elif function_to_call == 2:
+ print('Porting ranger User-sync installation details to ambari.')
+ port_ranger_usersync_installation_to_ambari()
+ elif function_to_call == 3:
+ print('Porting ranger kms installation details to ambari.')
+ port_ranger_kms_installation_to_ambari()
+ elif function_to_call == 4:
+ print('Porting ranger hdfs plugin details to ambari.')
+ port_ranger_hdfs_plugin_to_ambari()
+ elif function_to_call == 5:
+ print('Porting ranger yarn plugin details to ambari.')
+ port_ranger_yarn_plugin_to_ambari()
+ elif function_to_call == 6:
+ print('Porting ranger Hive plugin details to ambari.')
+ port_ranger_hive_plugin_to_ambari()
+ elif function_to_call == 7:
+ print('Porting ranger Hbase plugin details to ambari.')
+ port_ranger_hbase_plugin_to_ambari()
+ elif function_to_call == 8:
+ print('Porting ranger Knox plugin details to ambari.')
+ port_ranger_knox_plugin_to_ambari()
+ elif function_to_call == 9:
+ print('Porting ranger Storm plugin details to ambari.')
+ port_ranger_storm_plugin_to_ambari()
+ elif function_to_call == 10:
+ print('Porting ranger Kafka plugin details to ambari.')
+ port_ranger_kafka_plugin_to_ambari()
+ else:
+ print ('Unsupported option passed for installation, please pass proper supported option')
+
+ else:
+ print('Usage :'
+ '\n python import_ranger_to_ambari.py {install option eg. 1} { ambari server url (eg. http://100.100.100.100:8080) } {ambari server username password (eg. demo_user:demo_pass) } {cluster name (eg. ambari_cluster)} {FQDN of host having Ranger Admin or Ranger Usersync or plugins installe (eg. ambari.server.com)} '
+ '\n Actual call will be like : python ranger_port_script.py 1 http://100.100.100.100:8080 demo_user:demo_pass ambari_cluster ambari.server.com'
+ '\n Pass first parameter as 1 for Ranger integration with Ambari.'
+ '\n Pass first parameter as 2 for Ranger User-sync integration with Ambari.'
+ '\n Pass first parameter as 3 for Ranger KMS integration with Ambari.'
+ '\n Pass first parameter as 4 for Ranger Hdfs Plugin integration with Ambari.'
+ '\n Pass first parameter as 5 for Ranger Yarn Plugin integration with Ambari.'
+ '\n Pass first parameter as 6 for Ranger Hive Plugin integration with Ambari.'
+ '\n Pass first parameter as 7 for Ranger Hbase Plugin integration with Ambari.'
+ '\n Pass first parameter as 8 for Ranger Knox Plugin integration with Ambari.'
+ '\n Pass first parameter as 9 for Ranger Storm Plugin integration with Ambari.'
+ '\n Pass first parameter as 10 for Ranger Kafka Plugin integration with Ambari.')
+
+ sys.exit(0)
+
diff --git a/migration-util/ambari2.1-hdp2.3-ranger0.50/bin/ranger_admin_install.properties b/migration-util/ambari2.1-hdp2.3-ranger0.50/bin/ranger_admin_install.properties
new file mode 100755
index 00000000000..f892a602dac
--- /dev/null
+++ b/migration-util/ambari2.1-hdp2.3-ranger0.50/bin/ranger_admin_install.properties
@@ -0,0 +1,33 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+#
+# This file provides list of deployment variables for the Policy Manager Web Application to be migrated to Ambari server
+#
+
+# Below are the mandatory parameters, required to be filled in by the user.
+
+#
+# DB password for the DB admin user-id
+#
+# For example:
+# db_root_user=root
+# db_root_user=SYS
+#
+# Mandatory properties for migration to be filled by user prior to migration.
+# db_root_user = needs to be updated by user before running the migration script.
+# db_root_password = needs to be updated by user before running the migration script.
+db_root_user=
+db_root_password=
diff --git a/migration-util/ambari2.1-hdp2.3-ranger0.50/doc/README.TXT b/migration-util/ambari2.1-hdp2.3-ranger0.50/doc/README.TXT
new file mode 100755
index 00000000000..bd56e8deb06
--- /dev/null
+++ b/migration-util/ambari2.1-hdp2.3-ranger0.50/doc/README.TXT
@@ -0,0 +1,78 @@
+Utility to Migrate Ranger Config into Ambari-2.1.0 (from a previous manual install of Ranger service and plugins)
+-----------------------------------------------------------------------------
+
+Pre-requisites:
+----------------
+ * Ambari Server (2.1.0) installed on one of the host of the cluster.
+ * Ranger service is manually installed outside Ambari.
+ * If user had Ambari 1.7.0 installed or Ambari 2.0.0, Ambari needs to be upgraded to 2.1.0, before this script is run.
+ * HDP 2.3 Components should be installed.
+ * Ranger service is expected to be up and running.
+ * Whichever component plugin needs to imported, that component should be up and running in Ambari server.
+ * Whichever component plugin needs to be imported, that plugin needs to be installed as well as enabled independently by the user outside Ambari.
+ * The installation folder paths for each component is as follows :
+ * For Ranger Admin service: /usr/hdp//ranger-admin
+ * For Ranger Usersync service: /usr/hdp//ranger-usersync
+ * For Ranger Hbase plugin: /usr/hdp//ranger-hbase-plugin
+ * For Ranger Hdfs plugin: /usr/hdp//ranger-hdfs-plugin
+ * For Ranger Hive plugin: /usr/hdp//ranger-hive-plugin
+ * For Ranger Knox plugin: /usr/hdp//ranger-knox-plugin
+ * For Ranger Storm plugin: /usr/hdp//ranger-storm-plugin
+
+Pre Install:
+------------
+ * Please take a backup of existing ranger DB and configurations, in case required.
+ * Please take a backup of existing ambari DB and configurations, in case required.
+ * You must have an existing MySQL Server, Oracle Server, or Postgres database instance running to be used by Ranger.
+ * Ensure that the access for the DB Admin user (root in case of MySQL or SYS in case of Oracle) is enabled in DB server from any host.
+ * Execute the following command on the Ambari Server host.
+ * Replace database-type with mysql or oracle and /jdbc/driver/path based on the location of the MySQL or Oracle JDBC driver:
+
+ ambari-server setup --jdbc-db={database-type} --jdbc-driver={/jdbc/driver/path}
+
+Steps to Add Ranger in a Ambari HDP cluster:
+--------------------------------------------
+ * In order to know about usage of the script, Execute the command:
+ python import_ranger_to_ambari.py
+ * Migration script locates the existing config in post-install properties files used by the service.
+ * This script will collect required configs from the independently installed Ranger service configurations
+ and after verification from the user, post it to the specified Ambari Server.
+ * Set appropriate values in the _install.properties template file, only if required.
+ For Ranger Admin service, ranger_admin_install.properties
+ * For script to use proper values, mandatory properties to be filled by user are as follows :
+ 1) During Ranger_Admin installation migration db_root_username and db_root_password are mandatory,
+ which can be set in the ranger_admin_install.properties
+
+To import Ranger (Admin and User-Sync) service and plugins we need to run the python script using command line as shown below,
+with valid input parameters, from the host where specific Ranger component has been installed / enabled :
+
+python import_ranger_to_ambari.py {install option} {ambari server url} {ambari server admin username:password} {cluster name} {FQDN of host having Ranger Admin or Ranger Usersync or plugins installed}
+
+for example the actual command will be as :
+
+python import_ranger_to_ambari.py 1 http://100.100.100.100:8080 admin:admin ambari_cluster rangerambari-feb09-rhel6-mp-sec-6.cs1cloud.internal
+
+First parameter (install option) is to mention the service type to be ported to Ambari that is,
+ 1 for adding Ranger service and Ranger Admin component to Ambari.
+ 2 for adding Ranger User sync component to Ambari.
+ 3 for adding Ranger KMS component to Ambari.
+ 4 to import Ranger Hdfs Plugin configs to Ambari.
+ 5 to import Ranger Yarn Plugin configs to Ambari.
+ 6 to import Ranger Hive Plugin configs to Ambari.
+ 7 to import Ranger Hbase Plugin configs to Ambari.
+ 8 to import Ranger Knox Plugin configs to Ambari.
+ 9 to import Ranger Storm Plugin configs to Ambari.
+ 10 to import Ranger Storm Plugin configs to Ambari.
+
+ * After running the script with first parameter as 1, Ranger service should be visible as Ambari service and Ranger-Admin should be visible.
+ * After running with 2 Ranger-Usersync should also be visible as its component, like-wise for the respective plugins.
+ * After executing the script with options 3 to 8 - please visit Ambari UI and restart the individual component, after the UI reflects the changes.
+
+Debugging:
+----------
+ * Make sure to back up the ranger config and DB prior to running the scripts.
+ * It is possible that the service-components may be added to Ambari but the installation may fail. In that case, look for the logs from Ambari-UI.
+ * If any of the pre-requisite is not met this might happen, in that case, try installation from Ambari-UI itself.
+ * If the services are configured and not started it may show up as Install Pending, reinstall both Admin and User-sync from Ambari UI, and then start the services.
+ * In case if the services are installed and in stopped state, restart them from Ambari-UI.
+
From 67e845a3bf4c704c647457f7a0404a3e3a7551a2 Mon Sep 17 00:00:00 2001
From: Gautam Borad
Date: Fri, 7 Aug 2015 12:19:11 +0530
Subject: [PATCH 032/202] RANGER-588 : Take care of Ranger KMS installation
even if java is not in PATH
Signed-off-by: Velmurugan Periasamy
---
kms/scripts/db_setup.py | 23 +----------------------
kms/scripts/dba_script.py | 26 ++------------------------
2 files changed, 3 insertions(+), 46 deletions(-)
mode change 100644 => 100755 kms/scripts/db_setup.py
mode change 100644 => 100755 kms/scripts/dba_script.py
diff --git a/kms/scripts/db_setup.py b/kms/scripts/db_setup.py
old mode 100644
new mode 100755
index 61940cca3ce..5e2f9506a99
--- a/kms/scripts/db_setup.py
+++ b/kms/scripts/db_setup.py
@@ -72,31 +72,10 @@ def populate_global_dict():
key , value = each_line.strip().split("=",1)
key = key.strip()
if 'PASSWORD' in key:
- jceks_file_path = os.path.join(RANGER_KMS_HOME, 'jceks','ranger_db.jceks')
- statuscode,value = call_keystore(library_path,key,'',jceks_file_path,'get')
- if statuscode == 1:
- value = ''
+ value = ''
value = value.strip()
globalDict[key] = value
-def call_keystore(libpath,aliasKey,aliasValue , filepath,getorcreate):
- finalLibPath = libpath.replace('\\','/').replace('//','/')
- finalFilePath = 'jceks://file/'+filepath.replace('\\','/').replace('//','/')
- if getorcreate == 'create':
- commandtorun = ['java', '-cp', finalLibPath, 'org.apache.ranger.credentialapi.buildks' ,'create', aliasKey, '-value', aliasValue, '-provider',finalFilePath]
- p = Popen(commandtorun,stdin=PIPE, stdout=PIPE, stderr=PIPE)
- output, error = p.communicate()
- statuscode = p.returncode
- return statuscode
- elif getorcreate == 'get':
- commandtorun = ['java', '-cp', finalLibPath, 'org.apache.ranger.credentialapi.buildks' ,'get', aliasKey, '-provider',finalFilePath]
- p = Popen(commandtorun,stdin=PIPE, stdout=PIPE, stderr=PIPE)
- output, error = p.communicate()
- statuscode = p.returncode
- return statuscode, output
- else:
- print 'proper command not received for input need get or create'
-
class BaseDB(object):
def check_connection(self, db_name, db_user, db_password):
diff --git a/kms/scripts/dba_script.py b/kms/scripts/dba_script.py
old mode 100644
new mode 100755
index 03e0a19e193..b2aa80a550d
--- a/kms/scripts/dba_script.py
+++ b/kms/scripts/dba_script.py
@@ -37,25 +37,6 @@
elif os_name == "WINDOWS":
RANGER_KMS_HOME = os.getenv("RANGER_KMS_HOME")
-def call_keystore(libpath,aliasKey,aliasValue , filepath,getorcreate):
- finalLibPath = libpath.replace('\\','/').replace('//','/')
- finalFilePath = 'jceks://file/'+filepath.replace('\\','/').replace('//','/')
- if getorcreate == 'create':
- commandtorun = ['java', '-cp', finalLibPath, 'org.apache.ranger.credentialapi.buildks' ,'create', aliasKey, '-value', aliasValue, '-provider',finalFilePath]
- p = Popen(commandtorun,stdin=PIPE, stdout=PIPE, stderr=PIPE)
- output, error = p.communicate()
- statuscode = p.returncode
- return statuscode
- elif getorcreate == 'get':
- commandtorun = ['java', '-cp', finalLibPath, 'org.apache.ranger.credentialapi.buildks' ,'get', aliasKey, '-provider',finalFilePath]
- p = Popen(commandtorun,stdin=PIPE, stdout=PIPE, stderr=PIPE)
- output, error = p.communicate()
- statuscode = p.returncode
- return statuscode, output
- else:
- print 'proper command not received for input need get or create'
-
-
def check_output(query):
if os_name == "LINUX":
p = subprocess.Popen(shlex.split(query), stdout=subprocess.PIPE)
@@ -83,17 +64,14 @@ def populate_global_dict():
elif os_name == "WINDOWS":
read_config_file = open(os.path.join(RANGER_KMS_HOME,'bin','install_config.properties'))
library_path = os.path.join(RANGER_KMS_HOME,"cred","lib","*")
- read_config_file = open(os.path.join(RANGER_KMS_HOME,'install.properties'))
+ read_config_file = open(os.path.join(RANGER_KMS_HOME,'install.properties'))
for each_line in read_config_file.read().split('\n') :
if len(each_line) == 0 : continue
if re.search('=', each_line):
key , value = each_line.strip().split("=",1)
key = key.strip()
if 'PASSWORD' in key:
- jceks_file_path = os.path.join(RANGER_KMS_HOME, 'jceks','ranger_db.jceks')
- statuscode,value = call_keystore(library_path,key,'',jceks_file_path,'get')
- if statuscode == 1:
- value = ''
+ value = ''
value = value.strip()
globalDict[key] = value
From 7e2677b7d65bdb20fb5113c13b5f2fc0bf2d363e Mon Sep 17 00:00:00 2001
From: rmani
Date: Tue, 28 Jul 2015 10:54:49 -0700
Subject: [PATCH 033/202] BUG-41359 : UserSync process performance issue due to
user group cache inconsistency
---
.../ranger/unixusersync/model/XUserInfo.java | 21 +++++++++++++++++--
1 file changed, 19 insertions(+), 2 deletions(-)
diff --git a/ugsync/src/main/java/org/apache/ranger/unixusersync/model/XUserInfo.java b/ugsync/src/main/java/org/apache/ranger/unixusersync/model/XUserInfo.java
index 5a59fc7b6a6..ca228188e12 100644
--- a/ugsync/src/main/java/org/apache/ranger/unixusersync/model/XUserInfo.java
+++ b/ugsync/src/main/java/org/apache/ranger/unixusersync/model/XUserInfo.java
@@ -27,7 +27,8 @@ public class XUserInfo {
private String name ;
private String description ;
- private List groups = new ArrayList() ;
+ private List groupNameList = new ArrayList() ;
+ private List groupIdList = new ArrayList() ;
public String getId() {
return id;
@@ -48,8 +49,24 @@ public void setDescription(String description) {
this.description = description;
}
+ public void setGroupNameList(List groupNameList) {
+ this.groupNameList = groupNameList;
+ }
+
+ public List getGroupNameList() {
+ return groupNameList;
+ }
+
+ public List getGroupIdList() {
+ return groupIdList;
+ }
+
+ public void setGroupIdList(List groupIdList) {
+ this.groupIdList = groupIdList;
+ }
+
public List getGroups() {
- return groups;
+ return groupNameList;
}
}
From 9e0f2da6476f9bb34d5a6310e8614ed0b096f250 Mon Sep 17 00:00:00 2001
From: Alok Lal
Date: Fri, 12 Jun 2015 16:29:04 -0700
Subject: [PATCH 034/202] RANGER-551 Policy Validation: If resource levels are
not valid for any hierarchy then checks about missing mandatory levels should
be skipped
Signed-off-by: Madhan Neethiraj
---
.../validation/RangerPolicyValidator.java | 38 +++++++++----------
1 file changed, 19 insertions(+), 19 deletions(-)
diff --git a/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerPolicyValidator.java b/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerPolicyValidator.java
index d27b6671c39..84f750db4ac 100644
--- a/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerPolicyValidator.java
+++ b/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerPolicyValidator.java
@@ -322,26 +322,26 @@ boolean isValidResourceNames(final RangerPolicy policy, final ListUDF or DB->TBL->COL hierarchy.
- * However, if both UDF and TBL were required then we can detect that policy does not specify mandatory levels for any of the candidate hierarchies.
- */
- Set> validHierarchies = filterHierarchies_mandatoryResourcesSpecifiedInPolicy(policyResources, candidateHierarchies, defHelper);
- if (validHierarchies.isEmpty()) {
- failures.add(new ValidationFailureDetailsBuilder()
- .field("resources")
- .subField("missing mandatory")
- .isSemanticallyIncorrect()
- .becauseOf("policy is missing required resources. Mandatory fields of potential hierarchies are: " + toStringHierarchies_mandatory(candidateHierarchies, defHelper))
- .build());
- valid = false;
- } else {
- if (LOG.isDebugEnabled()) {
- LOG.debug("isValidResourceNames: Found hierarchies with all mandatory fields specified: " + toStringHierarchies_mandatory(validHierarchies, defHelper));
+ /*
+ * Among the candidate hierarchies there should be at least one for which policy specifies all of the mandatory resources. Note that there could be multiple
+ * hierarchies that meet that criteria, e.g. a hive policy that specified only DB. It is not clear if it belongs to DB->UDF or DB->TBL->COL hierarchy.
+ * However, if both UDF and TBL were required then we can detect that policy does not specify mandatory levels for any of the candidate hierarchies.
+ */
+ Set> validHierarchies = filterHierarchies_mandatoryResourcesSpecifiedInPolicy(policyResources, candidateHierarchies, defHelper);
+ if (validHierarchies.isEmpty()) {
+ failures.add(new ValidationFailureDetailsBuilder()
+ .field("resources")
+ .subField("missing mandatory")
+ .isSemanticallyIncorrect()
+ .becauseOf("policy is missing required resources. Mandatory fields of potential hierarchies are: " + toStringHierarchies_mandatory(candidateHierarchies, defHelper))
+ .build());
+ valid = false;
+ } else {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("isValidResourceNames: Found hierarchies with all mandatory fields specified: " + toStringHierarchies_mandatory(validHierarchies, defHelper));
+ }
}
}
}
From 6087c375a45b17226002019aa2c0c40779558c25 Mon Sep 17 00:00:00 2001
From: Alok Lal
Date: Thu, 18 Jun 2015 15:30:51 -0700
Subject: [PATCH 035/202] RANGER-560 Policy validation: user friendly error
messages about validation failures
Signed-off-by: Madhan Neethiraj
---
.../validation/RangerPolicyValidator.java | 265 ++++++++++++++----
.../model/validation/RangerValidator.java | 42 ++-
.../validation/ValidationFailureDetails.java | 38 ++-
.../ValidationFailureDetailsBuilder.java | 19 +-
.../validation/TestRangerPolicyValidator.java | 22 +-
.../TestValidationFailureDetails.java | 39 +++
6 files changed, 345 insertions(+), 80 deletions(-)
create mode 100644 agents-common/src/test/java/org/apache/ranger/plugin/model/validation/TestValidationFailureDetails.java
diff --git a/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerPolicyValidator.java b/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerPolicyValidator.java
index 84f750db4ac..88170490ee9 100644
--- a/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerPolicyValidator.java
+++ b/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerPolicyValidator.java
@@ -19,11 +19,7 @@
package org.apache.ranger.plugin.model.validation;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
+import java.util.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
@@ -75,15 +71,18 @@ boolean isValid(Long id, Action action, List failures)
boolean valid = true;
if (action != Action.DELETE) {
- failures.add(new ValidationFailureDetailsBuilder()
+ failures.add(new RangerPolicyValidationErrorBuilder()
.isAnInternalError()
- .becauseOf("isValid(Long) is only supported for DELETE")
+ .becauseOf("method signature isValid(Long) is only supported for DELETE")
+ .errorCode(ErrorCode.InternalError_InvalidMethodInvocation)
.build());
valid = false;
} else if (id == null) {
- failures.add(new ValidationFailureDetailsBuilder()
+ failures.add(new RangerPolicyValidationErrorBuilder()
+ .becauseOf("policy id was null/missing")
.field("id")
.isMissing()
+ .errorCode(ErrorCode.Missing_PolicyId_Delete)
.build());
valid = false;
} else if (getPolicy(id) == null) {
@@ -110,10 +109,11 @@ boolean isValid(RangerPolicy policy, Action action, boolean isAdmin, List policies = getPolicies(serviceName, policyName);
if (CollectionUtils.isNotEmpty(policies)) {
if (policies.size() > 1) {
- failures.add(new ValidationFailureDetailsBuilder()
+ failures.add(new RangerPolicyValidationErrorBuilder()
+ .field("name")
.isAnInternalError()
.becauseOf("multiple policies found with the name[" + policyName + "]")
+ .errorCode(ErrorCode.InternalError_Data_MultiplePoliciesSameName)
.build());
valid = false;
} else if (action == Action.CREATE) { // size == 1
- failures.add(new ValidationFailureDetailsBuilder()
- .field("name")
+ failures.add(new RangerPolicyValidationErrorBuilder()
+ .field("policy name")
.isSemanticallyIncorrect()
- .becauseOf("policy already exists with name[" + policyName + "]; its id is[" + policies.iterator().next().getId() + "]")
+ .becauseOf("A policy already exists with name[" + policyName + "] for service[" + serviceName + "]; its id is[" + policies.iterator().next().getId() + "]")
+ .errorCode(ErrorCode.Duplicate_PolicyName_Create)
.build());
valid = false;
} else if (!policies.iterator().next().getId().equals(id)) { // size == 1 && action == UPDATE
- failures.add(new ValidationFailureDetailsBuilder()
+ failures.add(new RangerPolicyValidationErrorBuilder()
.field("id/name")
.isSemanticallyIncorrect()
+ .errorCode(ErrorCode.Duplicate_PolicyName_Update)
.becauseOf("id/name conflict: another policy already exists with name[" + policyName + "], its id is[" + policies.iterator().next().getId() + "]")
.build());
valid = false;
@@ -177,19 +184,21 @@ boolean isValid(RangerPolicy policy, Action action, boolean isAdmin, List 1 || !matchedPolicy.getId().equals(policy.getId())))) {
- failures.add(new ValidationFailureDetailsBuilder()
+ String message = String.format("another policy[%s] with matching resources[%s] exists for service[%s]!",
+ matchedPolicy.getName(), matchedPolicy.getResources(), policy.getService());
+ failures.add(new RangerPolicyValidationErrorBuilder()
.field("resources")
.isSemanticallyIncorrect()
- .becauseOf("found another policy[" + matchedPolicy.getName() + "] with matching resources[" + matchedPolicy.getResources() + "]!")
+ .becauseOf(message)
+ .errorCode(ErrorCode.Duplicate_PolicyResource)
.build());
valid = false;
}
@@ -312,12 +328,14 @@ boolean isValidResourceNames(final RangerPolicy policy, final List> candidateHierarchies = filterHierarchies_hierarchyHasAllPolicyResources(policyResources, hierarchies, defHelper);
if (candidateHierarchies.isEmpty()) {
// let's build a helpful message for user
- failures.add(new ValidationFailureDetailsBuilder()
- .field("resources")
+ String message = String.format("policy resources %s are not compatible with any resource hierarchy for service def[%s]! Valid hierarchies are: %s",
+ policyResources.toString(), serviceDef.getName(), toStringHierarchies_all(hierarchies, defHelper));
+ failures.add(new RangerPolicyValidationErrorBuilder()
+ .field("policy resources")
.subField("incompatible")
.isSemanticallyIncorrect()
- .becauseOf(String.format("policy resources [%s] were incompatible with all the hierarchies for this service defs! Valid hierarchies are: %s",
- policyResources.toString(), toStringHierarchies_all(hierarchies, defHelper)))
+ .becauseOf(message)
+ .errorCode(ErrorCode.Invalid_PolicyResource_NoCompatibleHierarchy)
.build());
valid = false;
} else {
@@ -331,11 +349,12 @@ boolean isValidResourceNames(final RangerPolicy policy, final List> validHierarchies = filterHierarchies_mandatoryResourcesSpecifiedInPolicy(policyResources, candidateHierarchies, defHelper);
if (validHierarchies.isEmpty()) {
- failures.add(new ValidationFailureDetailsBuilder()
- .field("resources")
+ failures.add(new RangerPolicyValidationErrorBuilder()
+ .field("policy resources")
.subField("missing mandatory")
.isSemanticallyIncorrect()
- .becauseOf("policy is missing required resources. Mandatory fields of potential hierarchies are: " + toStringHierarchies_mandatory(candidateHierarchies, defHelper))
+ .errorCode(ErrorCode.Invalid_PolicyResource_MissingMandatory)
+ .becauseOf("policy is missing required resources. Mandatory resources of potential hierarchies are: " + toStringHierarchies_mandatory(candidateHierarchies, defHelper))
.build());
valid = false;
} else {
@@ -438,16 +457,18 @@ boolean isValidResourceFlags(final Map inputPolicy
Map policyResources = getPolicyResourceWithLowerCaseKeys(inputPolicyResources);
for (RangerResourceDef resourceDef : resourceDefs) {
if (resourceDef == null) {
- failures.add(new ValidationFailureDetailsBuilder()
+ failures.add(new RangerPolicyValidationErrorBuilder()
.field("resource-def")
.isAnInternalError()
+ .errorCode(ErrorCode.InternalError_Data_NullResourceDef)
.becauseOf("a resource-def on resource def collection of service-def[" + serviceDefName + "] was null")
.build());
valid = false;
} else if (StringUtils.isBlank(resourceDef.getName())) {
- failures.add(new ValidationFailureDetailsBuilder()
+ failures.add(new RangerPolicyValidationErrorBuilder()
.field("resource-def-name")
.isAnInternalError()
+ .errorCode(ErrorCode.InternalError_Data_NullResourceDefName)
.becauseOf("name of a resource-def on resource def collection of service-def[" + serviceDefName + "] was null")
.build());
valid = false;
@@ -462,31 +483,34 @@ boolean isValidResourceFlags(final Map inputPolicy
boolean excludesSupported = Boolean.TRUE.equals(resourceDef.getExcludesSupported()); // could be null
boolean policyResourceIsExcludes = Boolean.TRUE.equals(policyResource.getIsExcludes()); // could be null
if (policyResourceIsExcludes && !excludesSupported) {
- failures.add(new ValidationFailureDetailsBuilder()
+ failures.add(new RangerPolicyValidationErrorBuilder()
.field("isExcludes")
.subField(resourceName)
.isSemanticallyIncorrect()
+ .errorCode(ErrorCode.Invalid_Excludes_NotSupported)
.becauseOf("isExcludes specified as [" + policyResourceIsExcludes + "] for resource [" + resourceName + "] which doesn't support isExcludes")
.build());
valid = false;
}
if (policyResourceIsExcludes && !isAdmin) {
- failures.add(new ValidationFailureDetailsBuilder()
+ failures.add(new RangerPolicyValidationErrorBuilder()
.field("isExcludes")
.subField("isAdmin")
.isSemanticallyIncorrect()
.becauseOf("isExcludes specified as [" + policyResourceIsExcludes + "] for resource [" + resourceName + "]. Insufficient permissions to create excludes policy.")
+ .errorCode(ErrorCode.Invalid_Excludes_RequiresAdmin)
.build());
valid = false;
}
boolean recursiveSupported = Boolean.TRUE.equals(resourceDef.getRecursiveSupported());
boolean policyIsRecursive = Boolean.TRUE.equals(policyResource.getIsRecursive());
if (policyIsRecursive && !recursiveSupported) {
- failures.add(new ValidationFailureDetailsBuilder()
+ failures.add(new RangerPolicyValidationErrorBuilder()
.field("isRecursive")
.subField(resourceName)
.isSemanticallyIncorrect()
.becauseOf("isRecursive specified as [" + policyIsRecursive + "] for resource [" + resourceName + "] which doesn't support isRecursive")
+ .errorCode(ErrorCode.Invalid_Recursive_NotSupported)
.build());
valid = false;
}
@@ -517,11 +541,14 @@ boolean isValidResourceValues(Map resourceMap, Lis
if (StringUtils.isBlank(aValue)) {
LOG.debug("resource value was blank");
} else if (!aValue.matches(regEx)) {
- failures.add(new ValidationFailureDetailsBuilder()
+ String message = String.format("Value[%s] of resource[%s] does not conform to the validation regex[%s] defined on the service-def[%s]", aValue, name, regEx, serviceDef.getName());
+ LOG.debug(message);
+ failures.add(new RangerPolicyValidationErrorBuilder()
.field("resource-values")
.subField(name)
.isSemanticallyIncorrect()
- .becauseOf("resources value[" + aValue + "] does not match validation regex[" + regEx + "] defined on service-def[" + serviceDef.getName() + "]")
+ .becauseOf(message)
+ .errorCode(ErrorCode.Invalid_ResourceValue_RegEx)
.build());
valid = false;
}
@@ -546,10 +573,11 @@ boolean isValidPolicyItems(List policyItems, List accesses, List accessTypes = getAccessTypes(serviceDef);
for (RangerPolicyItemAccess access : accesses) {
if (access == null) {
- failures.add(new ValidationFailureDetailsBuilder()
+ failures.add(new RangerPolicyValidationErrorBuilder()
.field("policy item access")
.isMissing()
.becauseOf("policy items access object was null")
+ .errorCode(ErrorCode.InternalError_Data_NullPolicyItemAccess)
.build());
valid = false;
} else {
@@ -650,19 +681,21 @@ boolean isValidPolicyItemAccess(RangerPolicyItemAccess access, List _TemplateId2Template = createMap(MessageTemplateData);
+
+ static int[][] ErrorCode2MessageTemplateData = new int[][] {
+ { ErrorCode.InternalError_InvalidMethodInvocation, MessageId.InternalError},
+ { ErrorCode.Missing_PolicyId_Delete, MessageId.MissingField},
+ { ErrorCode.Missing_PolicyObject, MessageId.InternalError},
+ { ErrorCode.Missing_PolicyId_Update, MessageId.MissingField},
+ { ErrorCode.Invalid_PolicyId, MessageId.InvalidField},
+ { ErrorCode.Missing_PolicyName, MessageId.MissingField},
+ { ErrorCode.InternalError_Data_MultiplePoliciesSameName, MessageId.InternalError_BadData},
+ { ErrorCode.Duplicate_PolicyName_Create, MessageId.DuplicateValue},
+ { ErrorCode.Duplicate_PolicyName_Update, MessageId.DuplicateValue},
+ { ErrorCode.Missing_ServiceName, MessageId.MissingField},
+ { ErrorCode.Invalid_ServiceName, MessageId.InvalidField},
+ { ErrorCode.Missing_PolicyItems, MessageId.MissingField},
+ { ErrorCode.InternalError_Data_MissingServiceDef, MessageId.InternalError_BadData},
+ { ErrorCode.Duplicate_PolicyResource, MessageId.DuplicateValue},
+ { ErrorCode.Invalid_PolicyResource_NoCompatibleHierarchy, MessageId.InvalidField},
+ { ErrorCode.Invalid_PolicyResource_MissingMandatory, MessageId.MissingField},
+ { ErrorCode.InternalError_Data_NullResourceDef, MessageId.InternalError_BadData},
+ { ErrorCode.InternalError_Data_NullResourceDefName, MessageId.InternalError_BadData},
+ { ErrorCode.Invalid_Excludes_NotSupported, MessageId.InvalidField},
+ { ErrorCode.Invalid_Excludes_RequiresAdmin, MessageId.InvalidField},
+ { ErrorCode.Invalid_Recursive_NotSupported, MessageId.InvalidField},
+ { ErrorCode.Invalid_ResourceValue_RegEx, MessageId.InvalidField},
+ { ErrorCode.InternalError_Data_NullPolicyItem, MessageId.InternalError_BadData},
+ { ErrorCode.Missing_PolicyItemAccesses, MessageId.MissingField},
+ { ErrorCode.Missing_PolicyItemUserGroup, MessageId.MissingField},
+ { ErrorCode.InternalError_Data_NullPolicyItemAccess, MessageId.InternalError_BadData},
+ { ErrorCode.Missing_PolicyItemAccessType, MessageId.MissingField},
+ { ErrorCode.Invalid_PolicyItemAccessType, MessageId.InvalidField},
+ { ErrorCode.Invalid_PolicyItemAccessType_Deny, MessageId.InvalidField},
+
+ };
+ static final Map _ErrorCode2MessageTemplate = createMap(ErrorCode2MessageTemplateData);
+
}
diff --git a/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerValidator.java b/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerValidator.java
index 3246138db6f..381864d14cd 100644
--- a/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerValidator.java
+++ b/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerValidator.java
@@ -106,9 +106,10 @@ String serializeFailures(List failures) {
LOG.warn("serializeFailures: called while list of failures is null/empty!");
} else {
StringBuilder builder = new StringBuilder();
- for (ValidationFailureDetails aFailure : failures) {
- builder.append(aFailure.toString());
- builder.append(";");
+ for (int i = 0; i < failures.size(); i++) {
+ builder.append(String.format("(%d)", i));
+ builder.append(failures.get(i).toString());
+ builder.append(" ");
}
message = builder.toString();
}
@@ -651,4 +652,39 @@ Set getEnumValues(RangerEnumDef enumDef) {
return result;
}
+ static Map createMap(int[][] data) {
+ Map result = new HashMap<>();
+ if (data != null) {
+ for (int[] row : data) {
+ Integer key = row[0];
+ Integer value = row[1];
+ if (result.containsKey(key)) {
+ LOG.warn("createMap: Internal error: duplicate key: multiple rows found for [" + key + "]. Skipped");
+ } else {
+ result.put(key, value);
+ }
+ }
+ }
+ return result;
+ }
+
+ static Map createMap(Object[][] data) {
+ Map result = new HashMap<>();
+ if (data != null) {
+ for (Object[] row : data) {
+ Integer key = (Integer)row[0];
+ String value = (String)row[1];
+ if (key == null) {
+ LOG.warn("createMap: error converting key[" + row[0] + "] to Integer! Sipped!");
+ } else if (StringUtils.isEmpty(value)) {
+ LOG.warn("createMap: empty/null value. Skipped!");
+ } else if (result.containsKey(key)) {
+ LOG.warn("createMap: Internal error: duplicate key. Multiple rows found for [" + key + "]. Skipped");
+ } else {
+ result.put(key, value);
+ }
+ }
+ }
+ return result;
+ }
}
diff --git a/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/ValidationFailureDetails.java b/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/ValidationFailureDetails.java
index 015203a0d8f..64e7e507480 100644
--- a/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/ValidationFailureDetails.java
+++ b/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/ValidationFailureDetails.java
@@ -19,18 +19,27 @@
package org.apache.ranger.plugin.model.validation;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
import java.util.Objects;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
public class ValidationFailureDetails {
+ private static final Log LOG = LogFactory.getLog(ValidationFailureDetails.class);
+
final String _fieldName;
final String _subFieldName;
final boolean _missing;
final boolean _semanticError;
final boolean _internalError;
final String _reason;
-
- public ValidationFailureDetails(String fieldName, String subFieldName, boolean missing, boolean semanticError, boolean internalError, String reason) {
+ final int _errorCode;
+
+ public ValidationFailureDetails(int errorCode, String fieldName, String subFieldName, boolean missing, boolean semanticError, boolean internalError, String reason) {
+ _errorCode = errorCode;
_missing = missing;
_semanticError = semanticError;
_internalError = internalError;
@@ -39,6 +48,11 @@ public ValidationFailureDetails(String fieldName, String subFieldName, boolean m
_reason = reason;
}
+ // TODO - legacy signature remove after all 3 are ported over to new message framework
+ public ValidationFailureDetails(String fieldName, String subFieldName, boolean missing, boolean semanticError, boolean internalError, String reason) {
+ this(-1, fieldName, subFieldName, missing, semanticError, internalError, reason);
+ }
+
public String getFieldName() {
return _fieldName;
}
@@ -61,18 +75,29 @@ String getType() {
public String getSubFieldName() {
return _subFieldName;
}
-
+
+ // matches "{blah}", "{{blah}", "{ }" and yields variables names like "blah", "{blah", " ", etc. for substitution
+ static final Pattern _Pattern = Pattern.compile("\\{([^\\}]+)\\}");
+
+ public String substituteVariables(String template) {
+ return template.replace("{field}", _fieldName == null ? "" : _fieldName)
+ .replace("{sub-field}", _subFieldName == null ? "" : _subFieldName)
+ .replace("{reason}", _reason == null ? "" : _reason);
+ }
+
+ // TODO legacy implementation. Remove when all
@Override
public String toString() {
+ LOG.debug("ValidationFailureDetails.toString()");
return String.format("Field[%s]%s is %s: reason[%s]",
_fieldName,
_subFieldName == null ? "" : ", subField[" + _subFieldName + "]",
getType(), _reason);
}
-
+
@Override
public int hashCode() {
- return Objects.hash(_fieldName, _subFieldName, _missing, _semanticError, _internalError, _reason);
+ return Objects.hash(_fieldName, _subFieldName, _missing, _semanticError, _internalError, _reason, _errorCode);
}
@Override
@@ -86,6 +111,7 @@ public boolean equals(Object obj) {
Objects.equals(_reason, that._reason) &&
_internalError == that._internalError &&
_missing == that._missing &&
- _semanticError == that._semanticError;
+ _semanticError == that._semanticError &&
+ _errorCode == that._errorCode;
}
}
diff --git a/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/ValidationFailureDetailsBuilder.java b/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/ValidationFailureDetailsBuilder.java
index 3a57341581a..ab67f1f1659 100644
--- a/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/ValidationFailureDetailsBuilder.java
+++ b/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/ValidationFailureDetailsBuilder.java
@@ -20,13 +20,14 @@
package org.apache.ranger.plugin.model.validation;
public class ValidationFailureDetailsBuilder {
- private String _fieldName;
- private boolean _missing;
- private boolean _semanticError;
- private String _reason;
- private String _subFieldName;
- private boolean _internalError;
-
+ protected String _fieldName;
+ protected boolean _missing;
+ protected boolean _semanticError;
+ protected String _reason;
+ protected String _subFieldName;
+ protected boolean _internalError;
+ protected int _errorCode;
+
ValidationFailureDetailsBuilder becauseOf(String aReason) {
_reason = aReason;
return this;
@@ -61,4 +62,8 @@ ValidationFailureDetailsBuilder isAnInternalError() {
return this;
}
+ ValidationFailureDetailsBuilder errorCode(int errorCode) {
+ _errorCode = errorCode;
+ return this;
+ }
}
diff --git a/agents-common/src/test/java/org/apache/ranger/plugin/model/validation/TestRangerPolicyValidator.java b/agents-common/src/test/java/org/apache/ranger/plugin/model/validation/TestRangerPolicyValidator.java
index 6236d71c663..e0f3b0e2c22 100644
--- a/agents-common/src/test/java/org/apache/ranger/plugin/model/validation/TestRangerPolicyValidator.java
+++ b/agents-common/src/test/java/org/apache/ranger/plugin/model/validation/TestRangerPolicyValidator.java
@@ -341,7 +341,7 @@ public final void testIsValid_failures() throws Exception {
filter.setParam(SearchFilter.SERVICE_NAME, "service-name");
filter.setParam(SearchFilter.POLICY_NAME, "policy-name");
when(_store.getPolicies(filter)).thenReturn(existingPolicies);
- checkFailure_isValid(Action.CREATE, "semantic", "name");
+ checkFailure_isValid(Action.CREATE, "semantic", "policy name");
// update : does not exist for id
when(_policy.getId()).thenReturn(7L);
@@ -374,11 +374,11 @@ public final void testIsValid_failures() throws Exception {
for (boolean isAdmin : new boolean[] { true, false }) {
when(_policy.getService()).thenReturn(null);
_failures.clear(); assertFalse(_validator.isValid(_policy, action, isAdmin, _failures));
- _utils.checkFailureForMissingValue(_failures, "service");
+ _utils.checkFailureForMissingValue(_failures, "service name");
when(_policy.getService()).thenReturn("");
_failures.clear(); assertFalse(_validator.isValid(_policy, action, isAdmin, _failures));
- _utils.checkFailureForMissingValue(_failures, "service");
+ _utils.checkFailureForMissingValue(_failures, "service name");
}
}
@@ -389,19 +389,19 @@ public final void testIsValid_failures() throws Exception {
for (boolean isAdmin : new boolean[] { true, false }) {
when(_policy.getService()).thenReturn(null);
_failures.clear(); assertFalse(_validator.isValid(_policy, action, isAdmin, _failures));
- _utils.checkFailureForMissingValue(_failures, "service");
+ _utils.checkFailureForMissingValue(_failures, "service name");
when(_policy.getService()).thenReturn(null);
_failures.clear(); assertFalse(_validator.isValid(_policy, action, isAdmin, _failures));
- _utils.checkFailureForMissingValue(_failures, "service");
+ _utils.checkFailureForMissingValue(_failures, "service name");
when(_policy.getService()).thenReturn("service-name");
_failures.clear(); assertFalse(_validator.isValid(_policy, action, isAdmin, _failures));
- _utils.checkFailureForSemanticError(_failures, "service");
+ _utils.checkFailureForSemanticError(_failures, "service name");
when(_policy.getService()).thenReturn("another-service-name");
_failures.clear(); assertFalse(_validator.isValid(_policy, action, isAdmin, _failures));
- _utils.checkFailureForSemanticError(_failures, "service");
+ _utils.checkFailureForSemanticError(_failures, "service name");
}
}
@@ -475,7 +475,7 @@ public final void testIsValid_failures() throws Exception {
for (Action action : cu) {
for (boolean isAdmin : new boolean[] { true, false }) {
_failures.clear(); assertFalse(_validator.isValid(_policy, action, isAdmin, _failures));
- _utils.checkFailureForSemanticError(_failures, "resources");
+ _utils.checkFailureForSemanticError(_failures, "policy resources");
}
}
}
@@ -766,19 +766,19 @@ public final void test_isValidResourceNames_failures() {
Map policyResources = _utils.createPolicyResourceMap(policyResourceMap_bad);
when(_policy.getResources()).thenReturn(policyResources);
assertFalse("Missing required resource and unknown resource", _validator.isValidResourceNames(_policy, _failures, _serviceDef));
- _utils.checkFailureForSemanticError(_failures, "resources");
+ _utils.checkFailureForSemanticError(_failures, "policy resources");
// another bad resource map that straddles multiple hierarchies
policyResources = _utils.createPolicyResourceMap(policyResourceMap_bad_multiple_hierarchies);
when(_policy.getResources()).thenReturn(policyResources);
_failures.clear(); assertFalse("Policy with resources for multiple hierarchies", _validator.isValidResourceNames(_policy, _failures, _serviceDef));
- _utils.checkFailureForSemanticError(_failures, "resources", "incompatible");
+ _utils.checkFailureForSemanticError(_failures, "policy resources", "incompatible");
// another bad policy resource map that could match multiple hierarchies but is short on mandatory resources for all of those matches
policyResources = _utils.createPolicyResourceMap(policyResourceMap_bad_multiple_hierarchies_missing_mandatory);
when(_policy.getResources()).thenReturn(policyResources);
_failures.clear(); assertFalse("Policy with resources for multiple hierarchies missing mandatory resources for all pontential matches", _validator.isValidResourceNames(_policy, _failures, _serviceDef));
- _utils.checkFailureForSemanticError(_failures, "resources", "missing mandatory");
+ _utils.checkFailureForSemanticError(_failures, "policy resources", "missing mandatory");
}
diff --git a/agents-common/src/test/java/org/apache/ranger/plugin/model/validation/TestValidationFailureDetails.java b/agents-common/src/test/java/org/apache/ranger/plugin/model/validation/TestValidationFailureDetails.java
new file mode 100644
index 00000000000..0a758d11949
--- /dev/null
+++ b/agents-common/src/test/java/org/apache/ranger/plugin/model/validation/TestValidationFailureDetails.java
@@ -0,0 +1,39 @@
+package org.apache.ranger.plugin.model.validation;
+
+import junit.framework.TestCase;
+import org.junit.Test;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import static org.junit.Assert.assertEquals;
+
+/**
+ * Created by alal on 6/17/15.
+ */
+public class TestValidationFailureDetails {
+
+ @Test
+ public void test1() {
+ String[] templates = new String[] {
+ "The {field}, was missing and sub-field {sub-field} was mssing, too. Validation failed due to {reason}", // pattern at end.
+ "{field}, was missing and sub-field {sub-field} was mssing, too. Validation failed due to {reason}.", // pattern at start but not end.
+ "The {field}, was missing and sub-field {sub-field} was mssing, too. Validation failed due to {missing}.", // unknown substitute
+ "Template does not have field, but had {sub-field} along with a {reason} and a sprious field named {missing}.", // unknown substitute
+ };
+
+ ValidationFailureDetails failureDetails = new ValidationFailureDetails("id", "subType", false, false, false, "foo-bar");
+
+ String[] results = new String[] {
+ "The id, was missing and sub-field subType was mssing, too. Validation failed due to foo-bar", // pattern at end.
+ "id, was missing and sub-field subType was mssing, too. Validation failed due to foo-bar.", // pattern at start but not end.
+ "The id, was missing and sub-field subType was mssing, too. Validation failed due to {missing}.", // unknown substitute
+ "Template does not have field, but had subType along with a foo-bar and a sprious field named {missing}.", // unknown substitute
+ };
+
+ for (int i = 0; i < templates.length; i++) {
+ String result = failureDetails.substituteVariables(templates[i]);
+ assertEquals(results[i], result);
+ }
+ }
+}
\ No newline at end of file
From 7a6f88a7be29e6ea32bb468c8a67e9fb11e10d7b Mon Sep 17 00:00:00 2001
From: Alok Lal
Date: Tue, 28 Jul 2015 23:22:31 -0700
Subject: [PATCH 036/202] RANGER-560 Apache license added to test file
Signed-off-by: Madhan Neethiraj
---
.../TestValidationFailureDetails.java | 19 +++++++++++++++++++
1 file changed, 19 insertions(+)
diff --git a/agents-common/src/test/java/org/apache/ranger/plugin/model/validation/TestValidationFailureDetails.java b/agents-common/src/test/java/org/apache/ranger/plugin/model/validation/TestValidationFailureDetails.java
index 0a758d11949..cf929c69c6b 100644
--- a/agents-common/src/test/java/org/apache/ranger/plugin/model/validation/TestValidationFailureDetails.java
+++ b/agents-common/src/test/java/org/apache/ranger/plugin/model/validation/TestValidationFailureDetails.java
@@ -1,3 +1,22 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
package org.apache.ranger.plugin.model.validation;
import junit.framework.TestCase;
From 5fa82cba71a49b27a43e06a8dbcbcc9bd831627a Mon Sep 17 00:00:00 2001
From: Alok Lal
Date: Thu, 30 Jul 2015 15:33:42 -0700
Subject: [PATCH 037/202] RANGER-584 User friendly error messages for service
validation error failures
---
.../plugin/errors/ValidationErrorCode.java | 76 +++++++++
.../validation/RangerServiceValidator.java | 159 +++++++++++-------
.../errors/TestValidationErrorCode.java | 72 ++++++++
.../TestValidationFailureDetails.java | 3 -
4 files changed, 248 insertions(+), 62 deletions(-)
create mode 100644 agents-common/src/main/java/org/apache/ranger/plugin/errors/ValidationErrorCode.java
create mode 100644 agents-common/src/test/java/org/apache/ranger/plugin/errors/TestValidationErrorCode.java
diff --git a/agents-common/src/main/java/org/apache/ranger/plugin/errors/ValidationErrorCode.java b/agents-common/src/main/java/org/apache/ranger/plugin/errors/ValidationErrorCode.java
new file mode 100644
index 00000000000..77d16f5c0a9
--- /dev/null
+++ b/agents-common/src/main/java/org/apache/ranger/plugin/errors/ValidationErrorCode.java
@@ -0,0 +1,76 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.ranger.plugin.errors;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import java.text.MessageFormat;
+import java.util.Arrays;
+
+public enum ValidationErrorCode {
+
+ SERVICE_VALIDATION_ERR_UNSUPPORTED_ACTION(1001, "Internal error: unsupported action[{0}]; isValid(Long) is only supported for DELETE"),
+ SERVICE_VALIDATION_ERR_MISSING_FIELD(1002, "Internal error: missing field[{0}]"),
+ SERVICE_VALIDATION_ERR_NULL_SERVICE_OBJECT(1003, "Internal error: service object passed in was null"),
+ SERVICE_VALIDATION_ERR_EMPTY_SERVICE_ID(1004, "Internal error: service id was null/empty/blank"),
+ SERVICE_VALIDATION_ERR_INVALID_SERVICE_ID(1005, "No service found for id [{0}]"),
+ SERVICE_VALIDATION_ERR_INVALID_SERVICE_NAME(1006, "Service name[{0}] was null/empty/blank"),
+ SERVICE_VALIDATION_ERR_SERVICE_NAME_CONFICT(1007, "service with the name[{0}] already exists"),
+ SERVICE_VALIDATION_ERR_ID_NAME_CONFLICT(1008, "id/name conflict: another service already exists with name[{0}], its id is [{1}]"),
+ SERVICE_VALIDATION_ERR_MISSING_SERVICE_DEF(1009, "service def [{0}] was null/empty/blank"),
+ SERVICE_VALIDATION_ERR_INVALID_SERVICE_DEF(1010, "service def named[{0}] not found"),
+ SERVICE_VALIDATION_ERR_REQUIRED_PARM_MISSING(1011, "required configuration parameter is missing; missing parameters: {0}"),
+ ;
+
+
+ private static final Log LOG = LogFactory.getLog(ValidationErrorCode.class);
+
+ final int _errorCode;
+ final String _template;
+
+ ValidationErrorCode(int errorCode, String template) {
+ _errorCode = errorCode;
+ _template = template;
+ }
+
+ public String getMessage(Object... items) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug(String.format("<== ValidationErrorCode.getMessage(%s)", Arrays.toString(items)));
+ }
+
+ MessageFormat mf = new MessageFormat(_template);
+ String result = mf.format(items);
+
+ if (LOG.isDebugEnabled()) {
+ LOG.debug(String.format("<== ValidationErrorCode.getMessage(%s): %s", Arrays.toString(items), result));
+ }
+ return result;
+ }
+
+ public int getErrorCode() {
+ return _errorCode;
+ }
+
+ @Override
+ public String toString() {
+ return String.format("Code: %d, template: %s", _errorCode, _template);
+ }
+}
diff --git a/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerServiceValidator.java b/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerServiceValidator.java
index 615e385f28f..3cfaa3e7771 100644
--- a/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerServiceValidator.java
+++ b/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerServiceValidator.java
@@ -26,6 +26,7 @@
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.apache.ranger.plugin.errors.ValidationErrorCode;
import org.apache.ranger.plugin.model.RangerService;
import org.apache.ranger.plugin.model.RangerServiceDef;
import org.apache.ranger.plugin.store.ServiceStore;
@@ -67,16 +68,21 @@ boolean isValid(Long id, Action action, List failures)
boolean valid = true;
if (action != Action.DELETE) {
- failures.add(new ValidationFailureDetailsBuilder()
- .isAnInternalError()
- .becauseOf("unsupported action[" + action + "]; isValid(Long) is only supported for DELETE")
- .build());
+ ValidationErrorCode error = ValidationErrorCode.SERVICE_VALIDATION_ERR_UNSUPPORTED_ACTION;
+ failures.add(new RangerServiceValidationErrorBuilder()
+ .isAnInternalError()
+ .errorCode(error.getErrorCode())
+ .becauseOf(error.getMessage(action))
+ .build());
valid = false;
} else if (id == null) {
- failures.add(new ValidationFailureDetailsBuilder()
- .field("id")
- .isMissing()
- .build());
+ ValidationErrorCode error = ValidationErrorCode.SERVICE_VALIDATION_ERR_MISSING_FIELD;
+ failures.add(new RangerServiceValidationErrorBuilder()
+ .field("id")
+ .isMissing()
+ .errorCode(error.getErrorCode())
+ .becauseOf(error.getMessage(id))
+ .build());
valid = false;
} else if (getService(id) == null) {
if (LOG.isDebugEnabled()) {
@@ -100,32 +106,34 @@ boolean isValid(RangerService service, Action action, List inputParameters = getServiceConfigParameters(service);
Set missingParameters = Sets.difference(reqiredParameters, inputParameters);
if (!missingParameters.isEmpty()) {
- failures.add(new ValidationFailureDetailsBuilder()
- .field("configuration")
- .subField(missingParameters.iterator().next()) // we return any one parameter!
- .isMissing()
- .becauseOf("required configuration parameter is missing; missing parameters: " + missingParameters)
- .build());
+ ValidationErrorCode error = ValidationErrorCode.SERVICE_VALIDATION_ERR_REQUIRED_PARM_MISSING;
+ failures.add(new RangerServiceValidationErrorBuilder()
+ .field("configuration")
+ .subField(missingParameters.iterator().next()) // we return any one parameter!
+ .isMissing()
+ .errorCode(error.getErrorCode())
+ .becauseOf(error.getMessage(missingParameters))
+ .build());
valid = false;
}
}
@@ -201,4 +219,27 @@ boolean isValid(RangerService service, Action action, List may = ImmutableSet.copyOf(ValidationErrorCode.values());
+
+ // set of enums that must not hvae any subsequent placeholders in it
+ Set mustNot = new HashSet();
+
+ for (int i = 0; i < 5; i++) {
+ String token = String.format("{%d", i);
+ // check which ones should not have anymore substition varabile placehoders in them, {0}, {1}, etc.
+ for (ValidationErrorCode anEnum : may) {
+ if (!anEnum._template.contains(token)) {
+ // if template does not have {1} then it surely must not have {2}, {3}, etc.
+ mustNot.add(anEnum);
+ }
+ }
+ // check for incorrectly numbers substition variable placeholders
+ for (ValidationErrorCode anEnum : mustNot) {
+ assertFalse(anEnum.toString() + ": contains " + token + ". Check for wongly numberd substition variable placeholders.",
+ anEnum._template.contains(token));
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/agents-common/src/test/java/org/apache/ranger/plugin/model/validation/TestValidationFailureDetails.java b/agents-common/src/test/java/org/apache/ranger/plugin/model/validation/TestValidationFailureDetails.java
index cf929c69c6b..815d41c0b03 100644
--- a/agents-common/src/test/java/org/apache/ranger/plugin/model/validation/TestValidationFailureDetails.java
+++ b/agents-common/src/test/java/org/apache/ranger/plugin/model/validation/TestValidationFailureDetails.java
@@ -27,9 +27,6 @@
import static org.junit.Assert.assertEquals;
-/**
- * Created by alal on 6/17/15.
- */
public class TestValidationFailureDetails {
@Test
From eab51d41acca8d47dfef32fb8da1946844bec745 Mon Sep 17 00:00:00 2001
From: Alok Lal
Date: Mon, 3 Aug 2015 12:50:39 -0700
Subject: [PATCH 038/202] RANGER-593 User friendly error messages for service
def validation error failures
---
.../plugin/errors/ValidationErrorCode.java | 24 ++-
.../validation/RangerServiceDefValidator.java | 180 ++++++++++++------
.../errors/TestValidationErrorCode.java | 14 ++
3 files changed, 155 insertions(+), 63 deletions(-)
diff --git a/agents-common/src/main/java/org/apache/ranger/plugin/errors/ValidationErrorCode.java b/agents-common/src/main/java/org/apache/ranger/plugin/errors/ValidationErrorCode.java
index 77d16f5c0a9..c40efc92840 100644
--- a/agents-common/src/main/java/org/apache/ranger/plugin/errors/ValidationErrorCode.java
+++ b/agents-common/src/main/java/org/apache/ranger/plugin/errors/ValidationErrorCode.java
@@ -26,7 +26,7 @@
import java.util.Arrays;
public enum ValidationErrorCode {
-
+ // SERVICE VALIDATION
SERVICE_VALIDATION_ERR_UNSUPPORTED_ACTION(1001, "Internal error: unsupported action[{0}]; isValid(Long) is only supported for DELETE"),
SERVICE_VALIDATION_ERR_MISSING_FIELD(1002, "Internal error: missing field[{0}]"),
SERVICE_VALIDATION_ERR_NULL_SERVICE_OBJECT(1003, "Internal error: service object passed in was null"),
@@ -38,6 +38,28 @@ public enum ValidationErrorCode {
SERVICE_VALIDATION_ERR_MISSING_SERVICE_DEF(1009, "service def [{0}] was null/empty/blank"),
SERVICE_VALIDATION_ERR_INVALID_SERVICE_DEF(1010, "service def named[{0}] not found"),
SERVICE_VALIDATION_ERR_REQUIRED_PARM_MISSING(1011, "required configuration parameter is missing; missing parameters: {0}"),
+
+ // SERVICE-DEF VALIDATION
+ SERVICE_DEF_VALIDATION_ERR_UNSUPPORTED_ACTION(2001, "Internal error: unsupported action[{0}]; isValid(Long) is only supported for DELETE"),
+ SERVICE_DEF_VALIDATION_ERR_MISSING_FIELD(2002, "Internal error: missing field[{0}]"),
+ SERVICE_DEF_VALIDATION_ERR_NULL_SERVICE_DEF_OBJECT(2003, "Internal error: service def object passed in was null"),
+ SERVICE_DEF_VALIDATION_ERR_EMPTY_SERVICE_DEF_ID(2004, "Internal error: service def id was null/empty/blank"),
+ SERVICE_DEF_VALIDATION_ERR_INVALID_SERVICE_DEF_ID(2005, "No service def found for id [{0}]"),
+ SERVICE_DEF_VALIDATION_ERR_INVALID_SERVICE_DEF_NAME(2006, "Service def name[{0}] was null/empty/blank"),
+ SERVICE_DEF_VALIDATION_ERR_SERVICE_DEF_NAME_CONFICT(2007, "service def with the name[{0}] already exists"),
+ SERVICE_DEF_VALIDATION_ERR_ID_NAME_CONFLICT(2008, "id/name conflict: another service def already exists with name[{0}], its id is [{1}]"),
+ SERVICE_DEF_VALIDATION_ERR_IMPLIED_GRANT_UNKNOWN_ACCESS_TYPE(2009, "implied grant[{0}] contains an unknown access types[{1}]"),
+ SERVICE_DEF_VALIDATION_ERR_IMPLIED_GRANT_IMPLIES_ITSELF(2010, "implied grants list [{0}] for access type[{1}] contains itself"),
+ SERVICE_DEF_VALIDATION_ERR_POLICY_CONDITION_NULL_EVALUATOR(2011, "evaluator on policy condition definition[{0}] was null/empty!"),
+ SERVICE_DEF_VALIDATION_ERR_CONFIG_DEF_UNKNOWN_ENUM(2012, "subtype[{0}] of service def config[{1}] was not among defined enums[{2}]"),
+ SERVICE_DEF_VALIDATION_ERR_CONFIG_DEF_UNKNOWN_ENUM_VALUE(2013, "default value[{0}] of service def config[{1}] was not among the valid values[{2}] of enums[{3}]"),
+ SERVICE_DEF_VALIDATION_ERR_CONFIG_DEF_MISSING_TYPE(2014, "type of service def config[{0}] was null/empty"),
+ SERVICE_DEF_VALIDATION_ERR_CONFIG_DEF_INVALID_TYPE(2015, "type[{0}] of service def config[{1}] is not among valid types: {2}"),
+ SERVICE_DEF_VALIDATION_ERR_RESOURCE_GRAPH_INVALID(2016, "Resource graph implied by various resources, e.g. parent value is invalid. Valid graph must forest (union of disjoint trees)."),
+ SERVICE_DEF_VALIDATION_ERR_ENUM_DEF_NULL_OBJECT(2017, "Internal error: An enum def in enums collection is null"),
+ SERVICE_DEF_VALIDATION_ERR_ENUM_DEF_NO_VALUES(2018, "enum [{0}] does not have any elements"),
+ SERVICE_DEF_VALIDATION_ERR_ENUM_DEF_INVALID_DEFAULT_INDEX(2019, "default index[{0}] for enum [{1}] is invalid"),
+ SERVICE_DEF_VALIDATION_ERR_ENUM_DEF_NULL_ENUM_ELEMENT(2020, "An enum element in enum element collection of enum [{0}] is null"),
;
diff --git a/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerServiceDefValidator.java b/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerServiceDefValidator.java
index 32d0f1a1f53..75372c22462 100644
--- a/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerServiceDefValidator.java
+++ b/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerServiceDefValidator.java
@@ -31,6 +31,7 @@
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.apache.ranger.plugin.errors.ValidationErrorCode;
import org.apache.ranger.plugin.model.RangerServiceDef;
import org.apache.ranger.plugin.model.RangerServiceDef.RangerAccessTypeDef;
import org.apache.ranger.plugin.model.RangerServiceDef.RangerEnumDef;
@@ -78,15 +79,20 @@ boolean isValid(final Long id, final Action action, final List accessTypeDefs, final
boolean valid = true;
if (CollectionUtils.isEmpty(accessTypeDefs)) {
- failures.add(new ValidationFailureDetailsBuilder()
+ ValidationErrorCode error = ValidationErrorCode.SERVICE_DEF_VALIDATION_ERR_MISSING_FIELD;
+ failures.add(new RangerServiceDefValidationErrorBuilder()
.field("access types")
.isMissing()
- .becauseOf("access types collection was null/empty")
+ .errorCode(error.getErrorCode())
+ .becauseOf(error.getMessage("access types"))
.build());
valid = false;
} else {
@@ -248,22 +262,26 @@ boolean isValidAccessTypes(final List accessTypeDefs, final
Collection impliedGrants = getImpliedGrants(def);
Set unknownAccessTypes = Sets.difference(Sets.newHashSet(impliedGrants), accessNames);
if (!unknownAccessTypes.isEmpty()) {
- failures.add(new ValidationFailureDetailsBuilder()
+ ValidationErrorCode error = ValidationErrorCode.SERVICE_DEF_VALIDATION_ERR_IMPLIED_GRANT_UNKNOWN_ACCESS_TYPE;
+ failures.add(new RangerServiceDefValidationErrorBuilder()
.field("implied grants")
.subField(unknownAccessTypes.iterator().next()) // we return just on item here. Message has all unknow items
.isSemanticallyIncorrect()
- .becauseOf("implied grant[" + impliedGrants + "] contains an unknown access types[" + unknownAccessTypes + "]")
+ .errorCode(error.getErrorCode())
+ .becauseOf(error.getMessage(impliedGrants, unknownAccessTypes))
.build());
valid = false;
}
// implied grant should not imply itself!
String name = def.getName(); // note: this name could be null/blank/empty!
if (impliedGrants.contains(name)) {
- failures.add(new ValidationFailureDetailsBuilder()
+ ValidationErrorCode error = ValidationErrorCode.SERVICE_DEF_VALIDATION_ERR_IMPLIED_GRANT_IMPLIES_ITSELF;
+ failures.add(new RangerServiceDefValidationErrorBuilder()
.field("implied grants")
.subField(name)
.isSemanticallyIncorrect()
- .becauseOf("implied grants list [" + impliedGrants + "] for access type[" + name + "] contains itself")
+ .errorCode(error.getErrorCode())
+ .becauseOf(error.getMessage(impliedGrants, name))
.build());
valid = false;
}
@@ -292,13 +310,13 @@ boolean isValidPolicyConditions(List policyConditions,
String name = conditionDef.getName();
valid = isUnique(name, names, "policy condition def name", "policy condition defs", failures) && valid;
if (StringUtils.isBlank(conditionDef.getEvaluator())) {
- String reason = String.format("evaluator on policy condition definition[%s] was null/empty!", name);
- LOG.debug(reason);
- failures.add(new ValidationFailureDetailsBuilder()
+ ValidationErrorCode error = ValidationErrorCode.SERVICE_DEF_VALIDATION_ERR_POLICY_CONDITION_NULL_EVALUATOR;
+ failures.add(new RangerServiceDefValidationErrorBuilder()
.field("policy condition def evaluator")
.subField(name)
.isMissing()
- .becauseOf(reason)
+ .errorCode(error.getErrorCode())
+ .becauseOf(error.getMessage(name))
.build());
valid = false;
}
@@ -355,12 +373,13 @@ boolean isValidConfigOfEnumType(RangerServiceConfigDef configDef, List enumValues = getEnumValues(enumDef);
if (!enumValues.contains(defaultValue)) {
- String reason = String.format("default value[%s] of service def config[%s] was not among the valid values[%s] of enums[%s]", defaultValue, configName, enumValues, subType);
- failures.add(new ValidationFailureDetailsBuilder()
- .field("config def default value")
- .subField(configName)
- .isSemanticallyIncorrect()
- .becauseOf(reason)
- .build());
+ ValidationErrorCode error = ValidationErrorCode.SERVICE_DEF_VALIDATION_ERR_CONFIG_DEF_UNKNOWN_ENUM_VALUE;
+ failures.add(new RangerServiceDefValidationErrorBuilder()
+ .field("config def default value")
+ .subField(configName)
+ .isSemanticallyIncorrect()
+ .errorCode(error.getErrorCode())
+ .becauseOf(error.getMessage(defaultValue, configName, enumValues, subType))
+ .build());
valid = false;
}
}
@@ -397,21 +417,23 @@ boolean isValidConfigType(String type, String configName, List validTypes = ImmutableSet.of("bool", "enum", "int", "string", "password", "path");
if (StringUtils.isBlank(type)) {
- String reason = String.format("type of service def config[%s] was null/empty", configName);
- failures.add(new ValidationFailureDetailsBuilder()
+ ValidationErrorCode error = ValidationErrorCode.SERVICE_DEF_VALIDATION_ERR_CONFIG_DEF_MISSING_TYPE;
+ failures.add(new RangerServiceDefValidationErrorBuilder()
.field("config def type")
.subField(configName)
.isMissing()
- .becauseOf(reason)
+ .errorCode(error.getErrorCode())
+ .becauseOf(error.getMessage(configName))
.build());
valid = false;
} else if (!validTypes.contains(type)) {
- String reason = String.format("type[%s] of service def config[%s] is not among valid types: %s", type, configName, validTypes);
- failures.add(new ValidationFailureDetailsBuilder()
+ ValidationErrorCode error = ValidationErrorCode.SERVICE_DEF_VALIDATION_ERR_CONFIG_DEF_INVALID_TYPE;
+ failures.add(new RangerServiceDefValidationErrorBuilder()
.field("config def type")
.subField(configName)
.isSemanticallyIncorrect()
- .becauseOf(reason)
+ .errorCode(error.getErrorCode())
+ .becauseOf(error.getMessage(type, configName, validTypes))
.build());
valid = false;
}
@@ -430,11 +452,12 @@ boolean isValidResources(RangerServiceDef serviceDef, List resources = serviceDef.getResources();
if (CollectionUtils.isEmpty(resources)) {
- String reason = "service def resources collection was null/empty";
- failures.add(new ValidationFailureDetailsBuilder()
+ ValidationErrorCode error = ValidationErrorCode.SERVICE_DEF_VALIDATION_ERR_MISSING_FIELD;
+ failures.add(new RangerServiceDefValidationErrorBuilder()
.field("resources")
.isMissing()
- .becauseOf(reason)
+ .errorCode(error.getErrorCode())
+ .becauseOf(error.getMessage("resources"))
.build());
valid = false;
} else {
@@ -463,10 +486,12 @@ boolean isValidResourceGraph(RangerServiceDef serviceDef, List enumDefs, List ids = new HashSet();
for (RangerEnumDef enumDef : enumDefs) {
if (enumDef == null) {
- failures.add(new ValidationFailureDetailsBuilder()
+ ValidationErrorCode error = ValidationErrorCode.SERVICE_DEF_VALIDATION_ERR_ENUM_DEF_NULL_OBJECT;
+ failures.add(new RangerServiceDefValidationErrorBuilder()
.field("enum def")
.isMissing()
- .becauseOf("An enum def in enums collection is null")
+ .errorCode(error.getErrorCode())
+ .becauseOf(error.getMessage())
.build());
valid = false;
} else {
@@ -511,11 +538,13 @@ boolean isValidEnums(List enumDefs, List enumDefs, List= enumDef.getElements().size()) { // max index is one less than the size of the elements list
- failures.add(new ValidationFailureDetailsBuilder()
+ ValidationErrorCode error = ValidationErrorCode.SERVICE_DEF_VALIDATION_ERR_ENUM_DEF_INVALID_DEFAULT_INDEX;
+ failures.add(new RangerServiceDefValidationErrorBuilder()
.field("enum default index")
.subField(enumName)
.isSemanticallyIncorrect()
- .becauseOf("default index[" + defaultIndex + "] for enum [" + enumName + "] is invalid")
+ .errorCode(error.getErrorCode())
+ .becauseOf(error.getMessage(defaultIndex, enumName))
.build());
valid = false;
}
@@ -556,11 +587,13 @@ boolean isValidEnumElements(List enumElementsDefs, List ids = new HashSet();
for (RangerEnumElementDef elementDef : enumElementsDefs) {
if (elementDef == null) {
- failures.add(new ValidationFailureDetailsBuilder()
+ ValidationErrorCode error = ValidationErrorCode.SERVICE_DEF_VALIDATION_ERR_ENUM_DEF_NULL_ENUM_ELEMENT;
+ failures.add(new RangerServiceDefValidationErrorBuilder()
.field("enum element")
.subField(enumName)
.isMissing()
- .becauseOf("An enum element in enum element collection of enum [" + enumName + "] is null")
+ .errorCode(error.getErrorCode())
+ .becauseOf(error.getMessage(enumName))
.build());
valid = false;
} else {
@@ -575,4 +608,27 @@ boolean isValidEnumElements(List enumElementsDefs, List errorCodes = new HashSet<>();
+ for (ValidationErrorCode anEnum : ValidationErrorCode.values()) {
+ int errorCode = anEnum.getErrorCode();
+ // errorCode that we see must not have been seen so far.
+ assertFalse("ValidationErrorCode: error code [" + errorCode + "] used multiple times!", errorCodes.contains(errorCode));
+ errorCodes.add(errorCode);
+ }
+ }
}
\ No newline at end of file
From 77e3408e1a72637936690f0ba0cee34c60068be6 Mon Sep 17 00:00:00 2001
From: Alok Lal
Date: Tue, 4 Aug 2015 10:38:44 -0700
Subject: [PATCH 039/202] RANGER-594 User friendly error messages for policy
validation error failures and unify error processing for all 3 types
validations
---
.../plugin/errors/ValidationErrorCode.java | 25 ++
.../validation/RangerPolicyValidator.java | 361 ++++++------------
.../validation/RangerServiceDefValidator.java | 67 ++--
.../validation/RangerServiceValidator.java | 45 +--
.../validation/ValidationFailureDetails.java | 21 +-
.../ValidationFailureDetailsBuilder.java | 2 +-
.../TestValidationFailureDetails.java | 55 ---
7 files changed, 185 insertions(+), 391 deletions(-)
delete mode 100644 agents-common/src/test/java/org/apache/ranger/plugin/model/validation/TestValidationFailureDetails.java
diff --git a/agents-common/src/main/java/org/apache/ranger/plugin/errors/ValidationErrorCode.java b/agents-common/src/main/java/org/apache/ranger/plugin/errors/ValidationErrorCode.java
index c40efc92840..b458394d6aa 100644
--- a/agents-common/src/main/java/org/apache/ranger/plugin/errors/ValidationErrorCode.java
+++ b/agents-common/src/main/java/org/apache/ranger/plugin/errors/ValidationErrorCode.java
@@ -60,6 +60,31 @@ public enum ValidationErrorCode {
SERVICE_DEF_VALIDATION_ERR_ENUM_DEF_NO_VALUES(2018, "enum [{0}] does not have any elements"),
SERVICE_DEF_VALIDATION_ERR_ENUM_DEF_INVALID_DEFAULT_INDEX(2019, "default index[{0}] for enum [{1}] is invalid"),
SERVICE_DEF_VALIDATION_ERR_ENUM_DEF_NULL_ENUM_ELEMENT(2020, "An enum element in enum element collection of enum [{0}] is null"),
+
+ // POLICY VALIDATION
+ POLICY_VALIDATION_ERR_UNSUPPORTED_ACTION(3001, "Internal error: method signature isValid(Long) is only supported for DELETE"),
+ POLICY_VALIDATION_ERR_MISSING_FIELD(3002, "Internal error: missing field[{0}]"),
+ POLICY_VALIDATION_ERR_NULL_POLICY_OBJECT(3003, "Internal error: policy object passed in was null"),
+ POLICY_VALIDATION_ERR_INVALID_POLICY_ID(3004, "Invalid policy id provided for update: no policy found for id[{0}]"),
+ POLICY_VALIDATION_ERR_POLICY_NAME_MULTIPLE_POLICIES_WITH_SAME_NAME(3005, "Internal error: multiple policies found with the name[{0}]"),
+ POLICY_VALIDATION_ERR_POLICY_NAME_CONFLICT(3006, "id/name conflict: another policy already exists with name[{0}] for service[{1}, its id is[{2}]"),
+ POLICY_VALIDATION_ERR_INVALID_SERVICE_NAME(3007, "no service found with name[{0}]"),
+ POLICY_VALIDATION_ERR_MISSING_POLICY_ITEMS(3008, "at least one policy item must be specified if audit isn't enabled"),
+ POLICY_VALIDATION_ERR_MISSING_SERVICE_DEF(3009, "Internal error: Service def[{0}] of policy's service[{1}] does not exist!"),
+ POLICY_VALIDATION_ERR_DUPLICATE_POLICY_RESOURCE(3010, "another policy[{0}] with matching resources[{1}] exists for service[{2}]!"),
+ POLICY_VALIDATION_ERR_INVALID_RESOURCE_NO_COMPATIBLE_HIERARCHY(3011, "policy resources [{0}] are not compatible with any resource hierarchy for service def[{1}]! Valid hierarchies are: {2}"),
+ POLICY_VALIDATION_ERR_INVALID_RESOURCE_MISSING_MANDATORY(3012, "policy is missing required resources. Mandatory resources of potential hierarchies are: {0}"),
+ POLICY_VALIDATION_ERR_NULL_RESOURCE_DEF(3013, "Internal error: a resource-def on resource def collection of service-def[{0}] was null"),
+ POLICY_VALIDATION_ERR_MISSING_RESOURCE_DEF_NAME(3014, "Internal error: name of a resource-def on resource def collection of service-def[{0}] was null"),
+ POLICY_VALIDATION_ERR_EXCLUDES_NOT_SUPPORTED(3015, "isExcludes specified as [{0}] for resource [{1}] which doesn't support isExcludes"),
+ POLICY_VALIDATION_ERR_EXCLUDES_REQUIRES_ADMIN(3016, "isExcludes specified as [{0}] for resource [{1}]. Insufficient permissions to create excludes policy."),
+ POLICY_VALIDATION_ERR_RECURSIVE_NOT_SUPPORTED(3017, "isRecursive specified as [{0}] for resource [{1}] which doesn't support isRecursive"),
+ POLICY_VALIDATION_ERR_INVALID_RESOURCE_VALUE_REGEX(3018, "Value[{0}] of resource[{1}] does not conform to the validation regex[{2}] defined on the service-def[{3}]"),
+ POLICY_VALIDATION_ERR_NULL_POLICY_ITEM(3019, "policy items object was null"),
+ POLICY_VALIDATION_ERR_MISSING_USER_AND_GROUPS(3020, "both users and user-groups collections on the policy item were null/empty"),
+ POLICY_VALIDATION_ERR_NULL_POLICY_ITEM_ACCESS(3021, "policy items access object was null"),
+ POLICY_VALIDATION_ERR_POLICY_ITEM_ACCESS_TYPE_INVALID(3022, "access type[{0}] not among valid types for service[{1}]"),
+ POLICY_VALIDATION_ERR_POLICY_ITEM_ACCESS_TYPE_DENY(3023, "access type is set to deny. Currently deny access types are not supported."),
;
diff --git a/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerPolicyValidator.java b/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerPolicyValidator.java
index 88170490ee9..da817c69996 100644
--- a/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerPolicyValidator.java
+++ b/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerPolicyValidator.java
@@ -25,6 +25,7 @@
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.apache.ranger.plugin.errors.ValidationErrorCode;
import org.apache.ranger.plugin.model.RangerPolicy;
import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem;
import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemAccess;
@@ -71,19 +72,22 @@ boolean isValid(Long id, Action action, List failures)
boolean valid = true;
if (action != Action.DELETE) {
- failures.add(new RangerPolicyValidationErrorBuilder()
+ ValidationErrorCode error = ValidationErrorCode.POLICY_VALIDATION_ERR_UNSUPPORTED_ACTION;
+ failures.add(new ValidationFailureDetailsBuilder()
.isAnInternalError()
- .becauseOf("method signature isValid(Long) is only supported for DELETE")
- .errorCode(ErrorCode.InternalError_InvalidMethodInvocation)
+ .becauseOf(error.getMessage())
+ .errorCode(error.getErrorCode())
.build());
valid = false;
} else if (id == null) {
- failures.add(new RangerPolicyValidationErrorBuilder()
- .becauseOf("policy id was null/missing")
- .field("id")
- .isMissing()
- .errorCode(ErrorCode.Missing_PolicyId_Delete)
- .build());
+ ValidationErrorCode error = ValidationErrorCode.POLICY_VALIDATION_ERR_MISSING_FIELD;
+ failures.add(new ValidationFailureDetailsBuilder()
+ .becauseOf("policy id was null/missing")
+ .field("id")
+ .isMissing()
+ .errorCode(error.getErrorCode())
+ .becauseOf(error.getMessage("id"))
+ .build());
valid = false;
} else if (getPolicy(id) == null) {
if (LOG.isDebugEnabled()) {
@@ -107,34 +111,33 @@ boolean isValid(RangerPolicy policy, Action action, boolean isAdmin, List policies = getPolicies(serviceName, policyName);
if (CollectionUtils.isNotEmpty(policies)) {
if (policies.size() > 1) {
- failures.add(new RangerPolicyValidationErrorBuilder()
+ ValidationErrorCode error = ValidationErrorCode.POLICY_VALIDATION_ERR_POLICY_NAME_MULTIPLE_POLICIES_WITH_SAME_NAME;
+ failures.add(new ValidationFailureDetailsBuilder()
.field("name")
.isAnInternalError()
- .becauseOf("multiple policies found with the name[" + policyName + "]")
- .errorCode(ErrorCode.InternalError_Data_MultiplePoliciesSameName)
+ .becauseOf(error.getMessage(policyName))
+ .errorCode(error.getErrorCode())
.build());
valid = false;
} else if (action == Action.CREATE) { // size == 1
- failures.add(new RangerPolicyValidationErrorBuilder()
+ ValidationErrorCode error = ValidationErrorCode.POLICY_VALIDATION_ERR_POLICY_NAME_CONFLICT;
+ failures.add(new ValidationFailureDetailsBuilder()
.field("policy name")
.isSemanticallyIncorrect()
- .becauseOf("A policy already exists with name[" + policyName + "] for service[" + serviceName + "]; its id is[" + policies.iterator().next().getId() + "]")
- .errorCode(ErrorCode.Duplicate_PolicyName_Create)
+ .becauseOf(error.getMessage(policyName, serviceName, policies.iterator().next().getId()))
+ .errorCode(error.getErrorCode())
.build());
valid = false;
} else if (!policies.iterator().next().getId().equals(id)) { // size == 1 && action == UPDATE
- failures.add(new RangerPolicyValidationErrorBuilder()
+ ValidationErrorCode error = ValidationErrorCode.POLICY_VALIDATION_ERR_POLICY_NAME_CONFLICT;
+ failures.add(new ValidationFailureDetailsBuilder()
.field("id/name")
.isSemanticallyIncorrect()
- .errorCode(ErrorCode.Duplicate_PolicyName_Update)
- .becauseOf("id/name conflict: another policy already exists with name[" + policyName + "], its id is[" + policies.iterator().next().getId() + "]")
+ .becauseOf(error.getMessage(policyName, serviceName, policies.iterator().next().getId()))
+ .errorCode(error.getErrorCode())
.build());
valid = false;
}
@@ -184,21 +189,23 @@ boolean isValid(RangerPolicy policy, Action action, boolean isAdmin, List policies = getPoliciesForResourceSignature(policy.getService(), signature);
if (CollectionUtils.isNotEmpty(policies)) {
+ ValidationErrorCode error = ValidationErrorCode.POLICY_VALIDATION_ERR_DUPLICATE_POLICY_RESOURCE;
RangerPolicy matchedPolicy = policies.iterator().next();
// there shouldn't be a matching policy for create. During update only match should be to itself
if (action == Action.CREATE || (action == Action.UPDATE && (policies.size() > 1 || !matchedPolicy.getId().equals(policy.getId())))) {
- String message = String.format("another policy[%s] with matching resources[%s] exists for service[%s]!",
- matchedPolicy.getName(), matchedPolicy.getResources(), policy.getService());
- failures.add(new RangerPolicyValidationErrorBuilder()
- .field("resources")
- .isSemanticallyIncorrect()
- .becauseOf(message)
- .errorCode(ErrorCode.Duplicate_PolicyResource)
- .build());
+ failures.add(new ValidationFailureDetailsBuilder()
+ .field("resources")
+ .isSemanticallyIncorrect()
+ .becauseOf(error.getMessage(matchedPolicy.getName(), matchedPolicy.getResources(), policy.getService()))
+ .errorCode(error.getErrorCode())
+ .build());
valid = false;
}
}
@@ -327,15 +333,13 @@ boolean isValidResourceNames(final RangerPolicy policy, final List> candidateHierarchies = filterHierarchies_hierarchyHasAllPolicyResources(policyResources, hierarchies, defHelper);
if (candidateHierarchies.isEmpty()) {
- // let's build a helpful message for user
- String message = String.format("policy resources %s are not compatible with any resource hierarchy for service def[%s]! Valid hierarchies are: %s",
- policyResources.toString(), serviceDef.getName(), toStringHierarchies_all(hierarchies, defHelper));
- failures.add(new RangerPolicyValidationErrorBuilder()
+ ValidationErrorCode error = ValidationErrorCode.POLICY_VALIDATION_ERR_INVALID_RESOURCE_NO_COMPATIBLE_HIERARCHY;
+ failures.add(new ValidationFailureDetailsBuilder()
.field("policy resources")
.subField("incompatible")
.isSemanticallyIncorrect()
- .becauseOf(message)
- .errorCode(ErrorCode.Invalid_PolicyResource_NoCompatibleHierarchy)
+ .becauseOf(error.getMessage(policyResources.toString(), serviceDef.getName(), toStringHierarchies_all(hierarchies, defHelper)))
+ .errorCode(error.getErrorCode())
.build());
valid = false;
} else {
@@ -349,12 +353,13 @@ boolean isValidResourceNames(final RangerPolicy policy, final List> validHierarchies = filterHierarchies_mandatoryResourcesSpecifiedInPolicy(policyResources, candidateHierarchies, defHelper);
if (validHierarchies.isEmpty()) {
- failures.add(new RangerPolicyValidationErrorBuilder()
+ ValidationErrorCode error = ValidationErrorCode.POLICY_VALIDATION_ERR_INVALID_RESOURCE_MISSING_MANDATORY;
+ failures.add(new ValidationFailureDetailsBuilder()
.field("policy resources")
.subField("missing mandatory")
.isSemanticallyIncorrect()
- .errorCode(ErrorCode.Invalid_PolicyResource_MissingMandatory)
- .becauseOf("policy is missing required resources. Mandatory resources of potential hierarchies are: " + toStringHierarchies_mandatory(candidateHierarchies, defHelper))
+ .becauseOf(error.getMessage(toStringHierarchies_mandatory(candidateHierarchies, defHelper)))
+ .errorCode(error.getErrorCode())
.build());
valid = false;
} else {
@@ -457,19 +462,21 @@ boolean isValidResourceFlags(final Map inputPolicy
Map policyResources = getPolicyResourceWithLowerCaseKeys(inputPolicyResources);
for (RangerResourceDef resourceDef : resourceDefs) {
if (resourceDef == null) {
- failures.add(new RangerPolicyValidationErrorBuilder()
+ ValidationErrorCode error = ValidationErrorCode.POLICY_VALIDATION_ERR_NULL_RESOURCE_DEF;
+ failures.add(new ValidationFailureDetailsBuilder()
.field("resource-def")
.isAnInternalError()
- .errorCode(ErrorCode.InternalError_Data_NullResourceDef)
- .becauseOf("a resource-def on resource def collection of service-def[" + serviceDefName + "] was null")
+ .becauseOf(error.getMessage(serviceDefName))
+ .errorCode(error.getErrorCode())
.build());
valid = false;
} else if (StringUtils.isBlank(resourceDef.getName())) {
- failures.add(new RangerPolicyValidationErrorBuilder()
+ ValidationErrorCode error = ValidationErrorCode.POLICY_VALIDATION_ERR_MISSING_RESOURCE_DEF_NAME;
+ failures.add(new ValidationFailureDetailsBuilder()
.field("resource-def-name")
.isAnInternalError()
- .errorCode(ErrorCode.InternalError_Data_NullResourceDefName)
- .becauseOf("name of a resource-def on resource def collection of service-def[" + serviceDefName + "] was null")
+ .becauseOf(error.getMessage(serviceDefName))
+ .errorCode(error.getErrorCode())
.build());
valid = false;
} else {
@@ -483,34 +490,37 @@ boolean isValidResourceFlags(final Map inputPolicy
boolean excludesSupported = Boolean.TRUE.equals(resourceDef.getExcludesSupported()); // could be null
boolean policyResourceIsExcludes = Boolean.TRUE.equals(policyResource.getIsExcludes()); // could be null
if (policyResourceIsExcludes && !excludesSupported) {
- failures.add(new RangerPolicyValidationErrorBuilder()
+ ValidationErrorCode error = ValidationErrorCode.POLICY_VALIDATION_ERR_EXCLUDES_NOT_SUPPORTED;
+ failures.add(new ValidationFailureDetailsBuilder()
.field("isExcludes")
.subField(resourceName)
.isSemanticallyIncorrect()
- .errorCode(ErrorCode.Invalid_Excludes_NotSupported)
- .becauseOf("isExcludes specified as [" + policyResourceIsExcludes + "] for resource [" + resourceName + "] which doesn't support isExcludes")
+ .becauseOf(error.getMessage(policyResourceIsExcludes, resourceName))
+ .errorCode(error.getErrorCode())
.build());
valid = false;
}
if (policyResourceIsExcludes && !isAdmin) {
- failures.add(new RangerPolicyValidationErrorBuilder()
+ ValidationErrorCode error = ValidationErrorCode.POLICY_VALIDATION_ERR_EXCLUDES_REQUIRES_ADMIN;
+ failures.add(new ValidationFailureDetailsBuilder()
.field("isExcludes")
.subField("isAdmin")
.isSemanticallyIncorrect()
- .becauseOf("isExcludes specified as [" + policyResourceIsExcludes + "] for resource [" + resourceName + "]. Insufficient permissions to create excludes policy.")
- .errorCode(ErrorCode.Invalid_Excludes_RequiresAdmin)
+ .becauseOf(error.getMessage(policyResourceIsExcludes, resourceName))
+ .errorCode(error.getErrorCode())
.build());
valid = false;
}
boolean recursiveSupported = Boolean.TRUE.equals(resourceDef.getRecursiveSupported());
boolean policyIsRecursive = Boolean.TRUE.equals(policyResource.getIsRecursive());
if (policyIsRecursive && !recursiveSupported) {
- failures.add(new RangerPolicyValidationErrorBuilder()
+ ValidationErrorCode error = ValidationErrorCode.POLICY_VALIDATION_ERR_RECURSIVE_NOT_SUPPORTED;
+ failures.add(new ValidationFailureDetailsBuilder()
.field("isRecursive")
.subField(resourceName)
.isSemanticallyIncorrect()
- .becauseOf("isRecursive specified as [" + policyIsRecursive + "] for resource [" + resourceName + "] which doesn't support isRecursive")
- .errorCode(ErrorCode.Invalid_Recursive_NotSupported)
+ .becauseOf(error.getMessage(policyIsRecursive, resourceName))
+ .errorCode(error.getErrorCode())
.build());
valid = false;
}
@@ -541,14 +551,13 @@ boolean isValidResourceValues(Map resourceMap, Lis
if (StringUtils.isBlank(aValue)) {
LOG.debug("resource value was blank");
} else if (!aValue.matches(regEx)) {
- String message = String.format("Value[%s] of resource[%s] does not conform to the validation regex[%s] defined on the service-def[%s]", aValue, name, regEx, serviceDef.getName());
- LOG.debug(message);
- failures.add(new RangerPolicyValidationErrorBuilder()
+ ValidationErrorCode error = ValidationErrorCode.POLICY_VALIDATION_ERR_INVALID_RESOURCE_VALUE_REGEX;
+ failures.add(new ValidationFailureDetailsBuilder()
.field("resource-values")
.subField(name)
.isSemanticallyIncorrect()
- .becauseOf(message)
- .errorCode(ErrorCode.Invalid_ResourceValue_RegEx)
+ .becauseOf(error.getMessage(aValue, name, regEx, serviceDef.getName()))
+ .errorCode(error.getErrorCode())
.build());
valid = false;
}
@@ -573,11 +582,12 @@ boolean isValidPolicyItems(List policyItems, List accesses, List accessTypes = getAccessTypes(serviceDef);
for (RangerPolicyItemAccess access : accesses) {
if (access == null) {
- failures.add(new RangerPolicyValidationErrorBuilder()
+ ValidationErrorCode error = ValidationErrorCode.POLICY_VALIDATION_ERR_NULL_POLICY_ITEM_ACCESS;
+ failures.add(new ValidationFailureDetailsBuilder()
.field("policy item access")
.isMissing()
- .becauseOf("policy items access object was null")
- .errorCode(ErrorCode.InternalError_Data_NullPolicyItemAccess)
+ .becauseOf(error.getMessage())
+ .errorCode(error.getErrorCode())
.build());
valid = false;
} else {
@@ -681,34 +694,33 @@ boolean isValidPolicyItemAccess(RangerPolicyItemAccess access, List _TemplateId2Template = createMap(MessageTemplateData);
-
- static int[][] ErrorCode2MessageTemplateData = new int[][] {
- { ErrorCode.InternalError_InvalidMethodInvocation, MessageId.InternalError},
- { ErrorCode.Missing_PolicyId_Delete, MessageId.MissingField},
- { ErrorCode.Missing_PolicyObject, MessageId.InternalError},
- { ErrorCode.Missing_PolicyId_Update, MessageId.MissingField},
- { ErrorCode.Invalid_PolicyId, MessageId.InvalidField},
- { ErrorCode.Missing_PolicyName, MessageId.MissingField},
- { ErrorCode.InternalError_Data_MultiplePoliciesSameName, MessageId.InternalError_BadData},
- { ErrorCode.Duplicate_PolicyName_Create, MessageId.DuplicateValue},
- { ErrorCode.Duplicate_PolicyName_Update, MessageId.DuplicateValue},
- { ErrorCode.Missing_ServiceName, MessageId.MissingField},
- { ErrorCode.Invalid_ServiceName, MessageId.InvalidField},
- { ErrorCode.Missing_PolicyItems, MessageId.MissingField},
- { ErrorCode.InternalError_Data_MissingServiceDef, MessageId.InternalError_BadData},
- { ErrorCode.Duplicate_PolicyResource, MessageId.DuplicateValue},
- { ErrorCode.Invalid_PolicyResource_NoCompatibleHierarchy, MessageId.InvalidField},
- { ErrorCode.Invalid_PolicyResource_MissingMandatory, MessageId.MissingField},
- { ErrorCode.InternalError_Data_NullResourceDef, MessageId.InternalError_BadData},
- { ErrorCode.InternalError_Data_NullResourceDefName, MessageId.InternalError_BadData},
- { ErrorCode.Invalid_Excludes_NotSupported, MessageId.InvalidField},
- { ErrorCode.Invalid_Excludes_RequiresAdmin, MessageId.InvalidField},
- { ErrorCode.Invalid_Recursive_NotSupported, MessageId.InvalidField},
- { ErrorCode.Invalid_ResourceValue_RegEx, MessageId.InvalidField},
- { ErrorCode.InternalError_Data_NullPolicyItem, MessageId.InternalError_BadData},
- { ErrorCode.Missing_PolicyItemAccesses, MessageId.MissingField},
- { ErrorCode.Missing_PolicyItemUserGroup, MessageId.MissingField},
- { ErrorCode.InternalError_Data_NullPolicyItemAccess, MessageId.InternalError_BadData},
- { ErrorCode.Missing_PolicyItemAccessType, MessageId.MissingField},
- { ErrorCode.Invalid_PolicyItemAccessType, MessageId.InvalidField},
- { ErrorCode.Invalid_PolicyItemAccessType_Deny, MessageId.InvalidField},
-
- };
- static final Map _ErrorCode2MessageTemplate = createMap(ErrorCode2MessageTemplateData);
-
}
diff --git a/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerServiceDefValidator.java b/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerServiceDefValidator.java
index 75372c22462..0507fc4de8e 100644
--- a/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerServiceDefValidator.java
+++ b/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerServiceDefValidator.java
@@ -80,7 +80,7 @@ boolean isValid(final Long id, final Action action, final List accessTypeDefs, final
boolean valid = true;
if (CollectionUtils.isEmpty(accessTypeDefs)) {
ValidationErrorCode error = ValidationErrorCode.SERVICE_DEF_VALIDATION_ERR_MISSING_FIELD;
- failures.add(new RangerServiceDefValidationErrorBuilder()
+ failures.add(new ValidationFailureDetailsBuilder()
.field("access types")
.isMissing()
.errorCode(error.getErrorCode())
@@ -263,7 +263,7 @@ boolean isValidAccessTypes(final List accessTypeDefs, final
Set unknownAccessTypes = Sets.difference(Sets.newHashSet(impliedGrants), accessNames);
if (!unknownAccessTypes.isEmpty()) {
ValidationErrorCode error = ValidationErrorCode.SERVICE_DEF_VALIDATION_ERR_IMPLIED_GRANT_UNKNOWN_ACCESS_TYPE;
- failures.add(new RangerServiceDefValidationErrorBuilder()
+ failures.add(new ValidationFailureDetailsBuilder()
.field("implied grants")
.subField(unknownAccessTypes.iterator().next()) // we return just on item here. Message has all unknow items
.isSemanticallyIncorrect()
@@ -276,7 +276,7 @@ boolean isValidAccessTypes(final List accessTypeDefs, final
String name = def.getName(); // note: this name could be null/blank/empty!
if (impliedGrants.contains(name)) {
ValidationErrorCode error = ValidationErrorCode.SERVICE_DEF_VALIDATION_ERR_IMPLIED_GRANT_IMPLIES_ITSELF;
- failures.add(new RangerServiceDefValidationErrorBuilder()
+ failures.add(new ValidationFailureDetailsBuilder()
.field("implied grants")
.subField(name)
.isSemanticallyIncorrect()
@@ -311,7 +311,7 @@ boolean isValidPolicyConditions(List policyConditions,
valid = isUnique(name, names, "policy condition def name", "policy condition defs", failures) && valid;
if (StringUtils.isBlank(conditionDef.getEvaluator())) {
ValidationErrorCode error = ValidationErrorCode.SERVICE_DEF_VALIDATION_ERR_POLICY_CONDITION_NULL_EVALUATOR;
- failures.add(new RangerServiceDefValidationErrorBuilder()
+ failures.add(new ValidationFailureDetailsBuilder()
.field("policy condition def evaluator")
.subField(name)
.isMissing()
@@ -374,7 +374,7 @@ boolean isValidConfigOfEnumType(RangerServiceConfigDef configDef, List enumValues = getEnumValues(enumDef);
if (!enumValues.contains(defaultValue)) {
ValidationErrorCode error = ValidationErrorCode.SERVICE_DEF_VALIDATION_ERR_CONFIG_DEF_UNKNOWN_ENUM_VALUE;
- failures.add(new RangerServiceDefValidationErrorBuilder()
+ failures.add(new ValidationFailureDetailsBuilder()
.field("config def default value")
.subField(configName)
.isSemanticallyIncorrect()
@@ -418,7 +418,7 @@ boolean isValidConfigType(String type, String configName, List validTypes = ImmutableSet.of("bool", "enum", "int", "string", "password", "path");
if (StringUtils.isBlank(type)) {
ValidationErrorCode error = ValidationErrorCode.SERVICE_DEF_VALIDATION_ERR_CONFIG_DEF_MISSING_TYPE;
- failures.add(new RangerServiceDefValidationErrorBuilder()
+ failures.add(new ValidationFailureDetailsBuilder()
.field("config def type")
.subField(configName)
.isMissing()
@@ -428,7 +428,7 @@ boolean isValidConfigType(String type, String configName, List resources = serviceDef.getResources();
if (CollectionUtils.isEmpty(resources)) {
ValidationErrorCode error = ValidationErrorCode.SERVICE_DEF_VALIDATION_ERR_MISSING_FIELD;
- failures.add(new RangerServiceDefValidationErrorBuilder()
+ failures.add(new ValidationFailureDetailsBuilder()
.field("resources")
.isMissing()
.errorCode(error.getErrorCode())
@@ -487,7 +487,7 @@ boolean isValidResourceGraph(RangerServiceDef serviceDef, List enumDefs, List enumDefs, List enumDefs, List= enumDef.getElements().size()) { // max index is one less than the size of the elements list
ValidationErrorCode error = ValidationErrorCode.SERVICE_DEF_VALIDATION_ERR_ENUM_DEF_INVALID_DEFAULT_INDEX;
- failures.add(new RangerServiceDefValidationErrorBuilder()
+ failures.add(new ValidationFailureDetailsBuilder()
.field("enum default index")
.subField(enumName)
.isSemanticallyIncorrect()
@@ -588,7 +588,7 @@ boolean isValidEnumElements(List enumElementsDefs, List enumElementsDefs, List failures)
boolean valid = true;
if (action != Action.DELETE) {
ValidationErrorCode error = ValidationErrorCode.SERVICE_VALIDATION_ERR_UNSUPPORTED_ACTION;
- failures.add(new RangerServiceValidationErrorBuilder()
+ failures.add(new ValidationFailureDetailsBuilder()
.isAnInternalError()
.errorCode(error.getErrorCode())
.becauseOf(error.getMessage(action))
@@ -77,7 +77,7 @@ boolean isValid(Long id, Action action, List failures)
valid = false;
} else if (id == null) {
ValidationErrorCode error = ValidationErrorCode.SERVICE_VALIDATION_ERR_MISSING_FIELD;
- failures.add(new RangerServiceValidationErrorBuilder()
+ failures.add(new ValidationFailureDetailsBuilder()
.field("id")
.isMissing()
.errorCode(error.getErrorCode())
@@ -107,7 +107,7 @@ boolean isValid(RangerService service, Action action, List missingParameters = Sets.difference(reqiredParameters, inputParameters);
if (!missingParameters.isEmpty()) {
ValidationErrorCode error = ValidationErrorCode.SERVICE_VALIDATION_ERR_REQUIRED_PARM_MISSING;
- failures.add(new RangerServiceValidationErrorBuilder()
+ failures.add(new ValidationFailureDetailsBuilder()
.field("configuration")
.subField(missingParameters.iterator().next()) // we return any one parameter!
.isMissing()
@@ -219,27 +219,4 @@ boolean isValid(RangerService service, Action action, List
Date: Tue, 18 Aug 2015 16:27:14 +0530
Subject: [PATCH 040/202] RANGER-618 : KMS gets slower in key creation once
Database grows
Signed-off-by: Velmurugan Periasamy
---
.../hadoop/crypto/key/RangerKeyStore.java | 20 +++++++++++++------
1 file changed, 14 insertions(+), 6 deletions(-)
diff --git a/kms/src/main/java/org/apache/hadoop/crypto/key/RangerKeyStore.java b/kms/src/main/java/org/apache/hadoop/crypto/key/RangerKeyStore.java
index dc8efde6e25..ff82f53eb3f 100644
--- a/kms/src/main/java/org/apache/hadoop/crypto/key/RangerKeyStore.java
+++ b/kms/src/main/java/org/apache/hadoop/crypto/key/RangerKeyStore.java
@@ -83,6 +83,7 @@ private static final class SecretKeyEntry {
}
private Hashtable keyEntries = new Hashtable();
+ private Hashtable deltaEntries = new Hashtable();
RangerKeyStore() {
}
@@ -136,7 +137,7 @@ public Date engineGetCreationDate(String alias) {
public void addKeyEntry(String alias, Key key, char[] password, String cipher, int bitLength, String description, int version, String attributes)
throws KeyStoreException
{
- synchronized(keyEntries) {
+ synchronized(deltaEntries) {
try {
Class> c = null;
@@ -163,7 +164,8 @@ public void addKeyEntry(String alias, Key key, char[] password, String cipher, i
entry.description = description;
entry.version = version;
entry.attributes = attributes;
- keyEntries.put(alias.toLowerCase(), entry);
+ deltaEntries.put(alias.toLowerCase(), entry);
+ keyEntries.put(alias.toLowerCase(), entry);
} catch (Exception e) {
logger.error(e.getMessage());
throw new KeyStoreException(e.getMessage());
@@ -177,7 +179,8 @@ public void engineDeleteEntry(String alias)
{
synchronized(keyEntries) {
dbOperationDelete(convertAlias(alias));
- keyEntries.remove(convertAlias(alias));
+ keyEntries.remove(convertAlias(alias));
+ deltaEntries.remove(convertAlias(alias));
}
}
@@ -214,7 +217,7 @@ public int engineSize() {
public void engineStore(OutputStream stream, char[] password)
throws IOException, NoSuchAlgorithmException, CertificateException
{
- synchronized(keyEntries) {
+ synchronized(deltaEntries) {
// password is mandatory when storing
if (password == null) {
throw new IllegalArgumentException("Ranger Master Key can't be null");
@@ -223,7 +226,7 @@ public void engineStore(OutputStream stream, char[] password)
MessageDigest md = getKeyedMessageDigest(password);
byte digest[] = md.digest();
- for (Enumeration e = keyEntries.keys(); e.hasMoreElements();) {
+ for (Enumeration e = deltaEntries.keys(); e.hasMoreElements();) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(new DigestOutputStream(baos, md));
@@ -231,7 +234,7 @@ public void engineStore(OutputStream stream, char[] password)
try{
String alias = e.nextElement();
- Object entry = keyEntries.get(alias);
+ Object entry = deltaEntries.get(alias);
oos = new ObjectOutputStream(dos);
oos.writeObject(((SecretKeyEntry)entry).sealedKey);
@@ -250,6 +253,7 @@ public void engineStore(OutputStream stream, char[] password)
}
}
}
+ clearDeltaEntires();
}
}
@@ -537,4 +541,8 @@ public void engineLoadKeyStoreFile(InputStream stream, char[] storePass, char[]
}
}
+ public void clearDeltaEntires(){
+ deltaEntries.clear();
+ }
+
}
\ No newline at end of file
From c35384545848ffb713be0b9c59a35578022ec413 Mon Sep 17 00:00:00 2001
From: Gautam Borad
Date: Tue, 25 Aug 2015 09:56:37 +0530
Subject: [PATCH 041/202] RANGER-623 : Enable plugin scripts should handle file
permissions for certain umask value
Signed-off-by: Velmurugan Periasamy
---
agents-common/scripts/enable-agent.sh | 4 ++++
1 file changed, 4 insertions(+)
diff --git a/agents-common/scripts/enable-agent.sh b/agents-common/scripts/enable-agent.sh
index 9f677098c3c..55130a59996 100755
--- a/agents-common/scripts/enable-agent.sh
+++ b/agents-common/scripts/enable-agent.sh
@@ -454,6 +454,10 @@ then
fi
fi
done
+ if [ "${HCOMPONENT_NAME}" = "hbase" ] || [ "${HCOMPONENT_NAME}" = "storm" ];
+ then
+ chmod 644 ${HCOMPONENT_CONF_DIR}/*
+ fi
fi
#
From 7ccb14e53a0b79f478a010058872de25bb1e2197 Mon Sep 17 00:00:00 2001
From: Gautam Borad
Date: Mon, 31 Aug 2015 15:34:09 +0530
Subject: [PATCH 042/202] RANGER-628 : Make filters for ranger-admin search
binds configurable
Signed-off-by: Velmurugan Periasamy
---
security-admin/scripts/install.properties | 6 +++++-
security-admin/scripts/setup.sh | 8 ++++++++
.../handler/RangerAuthenticationProvider.java | 18 +++++++++++++-----
.../resources/conf.dist/ranger-admin-site.xml | 10 ++++++++++
4 files changed, 36 insertions(+), 6 deletions(-)
diff --git a/security-admin/scripts/install.properties b/security-admin/scripts/install.properties
index 4618ee3b44a..eb0c7ecb3b6 100644
--- a/security-admin/scripts/install.properties
+++ b/security-admin/scripts/install.properties
@@ -47,7 +47,7 @@ SQL_CONNECTOR_JAR=/usr/share/java/mysql-connector-java.jar
# DB password for the DB admin user-id
# **************************************************************************
# ** If the password is left empty or not-defined here,
-# ** it will be prompted to enter the password during installation process
+# ** it will try with blank password during installation process
# **************************************************************************
#
#db_root_user=root|SYS|postgres|sa|dba
@@ -138,6 +138,7 @@ authServicePort=5151
#xa_ldap_bind_dn="cn=admin,ou=users,dc=xasecure,dc=net"
#xa_ldap_bind_password=
#xa_ldap_referral=follow|ignore
+#xa_ldap_userSearchFilter="(uid={0})"
xa_ldap_url=
xa_ldap_userDNpattern=
@@ -148,6 +149,7 @@ xa_ldap_base_dn=
xa_ldap_bind_dn=
xa_ldap_bind_password=
xa_ldap_referral=
+xa_ldap_userSearchFilter=
####ACTIVE_DIRECTORY settings - Required only if have selected AD authentication ####
#
# Sample Settings
@@ -158,6 +160,7 @@ xa_ldap_referral=
#xa_ldap_ad_bind_dn="cn=administrator,ou=users,dc=xasecure,dc=net"
#xa_ldap_ad_bind_password=
#xa_ldap_ad_referral=follow|ignore
+#xa_ldap_ad_userSearchFilter="(sAMAccountName={0})"
xa_ldap_ad_domain=
xa_ldap_ad_url=
@@ -165,6 +168,7 @@ xa_ldap_ad_base_dn=
xa_ldap_ad_bind_dn=
xa_ldap_ad_bind_password=
xa_ldap_ad_referral=
+xa_ldap_ad_userSearchFilter=
# -----------------------------------------------------------
#
diff --git a/security-admin/scripts/setup.sh b/security-admin/scripts/setup.sh
index e0b14c5ae23..bae62986a66 100755
--- a/security-admin/scripts/setup.sh
+++ b/security-admin/scripts/setup.sh
@@ -1330,6 +1330,10 @@ do_authentication_setup(){
newPropertyValue="${xa_ldap_referral}"
updatePropertyToFilePy $propertyName $newPropertyValue $ldap_file
+ propertyName=ranger.ldap.user.searchfilter
+ newPropertyValue="${xa_ldap_userSearchFilter}"
+ updatePropertyToFilePy $propertyName $newPropertyValue $ldap_file
+
keystore="${cred_keystore_filename}"
if [ "${keystore}" != "" ]
@@ -1411,6 +1415,10 @@ do_authentication_setup(){
newPropertyValue="${xa_ldap_ad_referral}"
updatePropertyToFilePy $propertyName $newPropertyValue $ldap_file
+ propertyName=ranger.ldap.ad.user.searchfilter
+ newPropertyValue="${xa_ldap_ad_userSearchFilter}"
+ updatePropertyToFilePy $propertyName $newPropertyValue $ldap_file
+
keystore="${cred_keystore_filename}"
if [ "${keystore}" != "" ]
diff --git a/security-admin/src/main/java/org/apache/ranger/security/handler/RangerAuthenticationProvider.java b/security-admin/src/main/java/org/apache/ranger/security/handler/RangerAuthenticationProvider.java
index 1f1d957b1e4..abf4db47834 100644
--- a/security-admin/src/main/java/org/apache/ranger/security/handler/RangerAuthenticationProvider.java
+++ b/security-admin/src/main/java/org/apache/ranger/security/handler/RangerAuthenticationProvider.java
@@ -363,6 +363,7 @@ private Authentication getADBindAuthentication(Authentication authentication) {
String rangerADBindPassword = PropertiesUtil.getProperty("ranger.ldap.ad.bind.password", "");
String rangerLdapDefaultRole = PropertiesUtil.getProperty("ranger.ldap.default.role", "ROLE_USER");
String rangerLdapReferral = PropertiesUtil.getProperty("ranger.ldap.ad.referral", "follow");
+ String rangerLdapUserSearchFilter = PropertiesUtil.getProperty("ranger.ldap.ad.user.searchfilter", "(sAMAccountName={0})");
String userName = authentication.getName();
String userPassword = "";
if (authentication.getCredentials() != null) {
@@ -378,8 +379,11 @@ private Authentication getADBindAuthentication(Authentication authentication) {
ldapContextSource.setPooled(true);
ldapContextSource.afterPropertiesSet();
- String searchFilter="(sAMAccountName={0})";
- FilterBasedLdapUserSearch userSearch=new FilterBasedLdapUserSearch(rangerLdapADBase, searchFilter,ldapContextSource);
+ //String searchFilter="(sAMAccountName={0})";
+ if(rangerLdapUserSearchFilter==null||rangerLdapUserSearchFilter.trim().isEmpty()){
+ rangerLdapUserSearchFilter="(sAMAccountName={0})";
+ }
+ FilterBasedLdapUserSearch userSearch=new FilterBasedLdapUserSearch(rangerLdapADBase, rangerLdapUserSearchFilter,ldapContextSource);
userSearch.setSearchSubtree(true);
BindAuthenticator bindAuthenticator = new BindAuthenticator(ldapContextSource);
@@ -417,6 +421,7 @@ private Authentication getLdapBindAuthentication(Authentication authentication)
String rangerLdapBindDN = PropertiesUtil.getProperty("ranger.ldap.bind.dn", "");
String rangerLdapBindPassword = PropertiesUtil.getProperty("ranger.ldap.bind.password", "");
String rangerLdapReferral = PropertiesUtil.getProperty("ranger.ldap.referral", "follow");
+ String rangerLdapUserSearchFilter = PropertiesUtil.getProperty("ranger.ldap.user.searchfilter", "(uid={0})");
String userName = authentication.getName();
String userPassword = "";
if (authentication.getCredentials() != null) {
@@ -428,7 +433,7 @@ private Authentication getLdapBindAuthentication(Authentication authentication)
ldapContextSource.setPassword(rangerLdapBindPassword);
ldapContextSource.setReferral(rangerLdapReferral);
ldapContextSource.setCacheEnvironmentProperties(false);
- ldapContextSource.setAnonymousReadOnly(true);
+ ldapContextSource.setAnonymousReadOnly(false);
ldapContextSource.setPooled(true);
ldapContextSource.afterPropertiesSet();
@@ -437,8 +442,11 @@ private Authentication getLdapBindAuthentication(Authentication authentication)
defaultLdapAuthoritiesPopulator.setGroupSearchFilter(rangerLdapGroupSearchFilter);
defaultLdapAuthoritiesPopulator.setIgnorePartialResultException(true);
- String searchFilter="(uid={0})";
- FilterBasedLdapUserSearch userSearch=new FilterBasedLdapUserSearch(rangerLdapBase, searchFilter,ldapContextSource);
+ //String searchFilter="(uid={0})";
+ if(rangerLdapUserSearchFilter==null||rangerLdapUserSearchFilter.trim().isEmpty()){
+ rangerLdapUserSearchFilter="(uid={0})";
+ }
+ FilterBasedLdapUserSearch userSearch=new FilterBasedLdapUserSearch(rangerLdapBase, rangerLdapUserSearchFilter,ldapContextSource);
userSearch.setSearchSubtree(true);
BindAuthenticator bindAuthenticator = new BindAuthenticator(ldapContextSource);
diff --git a/security-admin/src/main/resources/conf.dist/ranger-admin-site.xml b/security-admin/src/main/resources/conf.dist/ranger-admin-site.xml
index 822a5075882..6009693bbe8 100644
--- a/security-admin/src/main/resources/conf.dist/ranger-admin-site.xml
+++ b/security-admin/src/main/resources/conf.dist/ranger-admin-site.xml
@@ -217,4 +217,14 @@
+
+ ranger.ldap.user.searchfilter
+ (uid={0})
+
+
+
+ ranger.ldap.ad.user.searchfilter
+ (sAMAccountName={0})
+
+
From 44a23ef788692b37d2375142b9074677f2df92dc Mon Sep 17 00:00:00 2001
From: Gautam Borad
Date: Thu, 3 Sep 2015 03:25:19 +0530
Subject: [PATCH 043/202] RANGER-637 : Make REFERRAL property in Ranger User
sync configurable
Signed-off-by: Velmurugan Periasamy
---
jisql/src/main/java/org/apache/util/sql/Jisql.java | 1 -
.../ldapusersync/process/LdapUserGroupBuilder.java | 7 ++++---
.../unixusersync/config/UserGroupSyncConfig.java | 14 ++++++++++++++
unixauthservice/scripts/install.properties | 2 ++
.../scripts/templates/installprop2xml.properties | 1 +
.../scripts/templates/ranger-ugsync-template.xml | 4 ++++
6 files changed, 25 insertions(+), 4 deletions(-)
diff --git a/jisql/src/main/java/org/apache/util/sql/Jisql.java b/jisql/src/main/java/org/apache/util/sql/Jisql.java
index 9c743564a44..cf7563c7130 100644
--- a/jisql/src/main/java/org/apache/util/sql/Jisql.java
+++ b/jisql/src/main/java/org/apache/util/sql/Jisql.java
@@ -755,7 +755,6 @@ private void printAllExceptions(SQLException sqle) {
+ sqle.getErrorCode());
sqle = sqle.getNextException();
}
- System.out.println("java.library.path:"+System.getProperty("java.library.path"));
}
/**
diff --git a/ugsync/src/main/java/org/apache/ranger/ldapusersync/process/LdapUserGroupBuilder.java b/ugsync/src/main/java/org/apache/ranger/ldapusersync/process/LdapUserGroupBuilder.java
index 93893ef8a61..66c6e284bbe 100644
--- a/ugsync/src/main/java/org/apache/ranger/ldapusersync/process/LdapUserGroupBuilder.java
+++ b/ugsync/src/main/java/org/apache/ranger/ldapusersync/process/LdapUserGroupBuilder.java
@@ -57,7 +57,7 @@ public class LdapUserGroupBuilder implements UserGroupSource {
private String ldapBindDn;
private String ldapBindPassword;
private String ldapAuthenticationMechanism;
-
+ private String ldapReferral;
private String searchBase;
private String userSearchBase;
@@ -135,7 +135,7 @@ private void createLdapContext() throws Throwable {
ldapBindPassword = config.getLdapBindPassword();
//ldapBindPassword = "admin-password";
ldapAuthenticationMechanism = config.getLdapAuthenticationMechanism();
-
+ ldapReferral = config.getContextReferral();
Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
@@ -144,7 +144,7 @@ private void createLdapContext() throws Throwable {
env.put(Context.SECURITY_PRINCIPAL, ldapBindDn);
env.put(Context.SECURITY_CREDENTIALS, ldapBindPassword);
env.put(Context.SECURITY_AUTHENTICATION, ldapAuthenticationMechanism);
- env.put(Context.REFERRAL, "follow") ;
+ env.put(Context.REFERRAL, ldapReferral) ;
ldapContext = new InitialLdapContext(env, null);
@@ -235,6 +235,7 @@ private void createLdapContext() throws Throwable {
+ ", groupMemberAttributeName: " + groupMemberAttributeName
+ ", groupNameAttribute: " + groupNameAttribute
+ ", groupUserMapSyncEnabled: " + groupUserMapSyncEnabled
+ + ", ldapReferral: " + ldapReferral
);
}
diff --git a/ugsync/src/main/java/org/apache/ranger/unixusersync/config/UserGroupSyncConfig.java b/ugsync/src/main/java/org/apache/ranger/unixusersync/config/UserGroupSyncConfig.java
index f8b68f2e644..7240fce840a 100644
--- a/ugsync/src/main/java/org/apache/ranger/unixusersync/config/UserGroupSyncConfig.java
+++ b/ugsync/src/main/java/org/apache/ranger/unixusersync/config/UserGroupSyncConfig.java
@@ -172,6 +172,8 @@ public class UserGroupSyncConfig {
private static final String DEFAULT_POLICYMGR_PASSWORD = "rangerusersync";
private static final String SYNC_SOURCE = "ranger.usersync.sync.source";
+ private static final String LGSYNC_REFERRAL = "ranger.usersync.ldap.referral";
+ private static final String DEFAULT_LGSYNC_REFERRAL = "ignore";
private Properties prop = new Properties() ;
private static volatile UserGroupSyncConfig me = null ;
@@ -715,4 +717,16 @@ public String getSyncSource() {
}
return syncSource;
}
+ public String getContextReferral() {
+ String referral="ignore";
+ if(prop!=null && prop.containsKey(LGSYNC_REFERRAL)){
+ referral=prop.getProperty(LGSYNC_REFERRAL);
+ if(referral==null||referral.trim().isEmpty()){
+ referral=DEFAULT_LGSYNC_REFERRAL;
+ }else{
+ referral=referral.trim().toLowerCase();
+ }
+ }
+ return referral;
+ }
}
diff --git a/unixauthservice/scripts/install.properties b/unixauthservice/scripts/install.properties
index 521562086c0..f206d0a8aff 100644
--- a/unixauthservice/scripts/install.properties
+++ b/unixauthservice/scripts/install.properties
@@ -169,3 +169,5 @@ SYNC_PAGED_RESULTS_ENABLED=
# search results would be returned page by page with the specified number of entries per page
# default value: 500
SYNC_PAGED_RESULTS_SIZE=
+#LDAP context referral could be ignore or follow
+SYNC_LDAP_REFERRAL =ignore
diff --git a/unixauthservice/scripts/templates/installprop2xml.properties b/unixauthservice/scripts/templates/installprop2xml.properties
index f102b5244d8..77b8eac50ce 100644
--- a/unixauthservice/scripts/templates/installprop2xml.properties
+++ b/unixauthservice/scripts/templates/installprop2xml.properties
@@ -48,3 +48,4 @@ AUTH_SSL_KEYSTORE_PASSWORD = ranger.usersync.keystore.password
AUTH_SSL_TRUSTSTORE_FILE = ranger.usersync.truststore.file
AUTH_SSL_TRUSTSTORE_PASSWORD = ranger.usersync.truststore.password
AUTH_SSL_ENABLED = ranger.usersync.enabled
+SYNC_LDAP_REFERRAL = ranger.usersync.ldap.referral
diff --git a/unixauthservice/scripts/templates/ranger-ugsync-template.xml b/unixauthservice/scripts/templates/ranger-ugsync-template.xml
index 268deb3cf0d..2bf55621718 100644
--- a/unixauthservice/scripts/templates/ranger-ugsync-template.xml
+++ b/unixauthservice/scripts/templates/ranger-ugsync-template.xml
@@ -181,4 +181,8 @@
ranger.usersync.sync.source
+
+ ranger.usersync.ldap.referral
+
+
From 28f7d1f56351496469b7028af2ccaf49f7046e8a Mon Sep 17 00:00:00 2001
From: Gautam Borad
Date: Wed, 2 Sep 2015 16:59:30 +0530
Subject: [PATCH 044/202] RANGER-638 : Ranger admin should redirect back to
login page when login cookies are no longer valid.
Signed-off-by: Velmurugan Periasamy
---
security-admin/src/main/webapp/scripts/utils/XAUtils.js | 3 +++
1 file changed, 3 insertions(+)
diff --git a/security-admin/src/main/webapp/scripts/utils/XAUtils.js b/security-admin/src/main/webapp/scripts/utils/XAUtils.js
index a83b22a5da7..6d84d1cf7d9 100644
--- a/security-admin/src/main/webapp/scripts/utils/XAUtils.js
+++ b/security-admin/src/main/webapp/scripts/utils/XAUtils.js
@@ -1012,6 +1012,9 @@ define(function(require) {
var XAGlobals = require('utils/XAGlobals');
var that = this;
var vXPortalUser = SessionMgr.getUserProfile();
+ if(_.isEmpty(vXPortalUser.attributes)){
+ return controller;
+ }
var denyControllerActions = [];
var denyModulesObj = [];
var userModuleNames = _.pluck(vXPortalUser.get('userPermList'),'moduleName');
From 72b4df5c011e750e426f7d4b6b6f8729be62752b Mon Sep 17 00:00:00 2001
From: Alok Lal
Date: Tue, 8 Sep 2015 12:31:08 -0700
Subject: [PATCH 045/202] RANGER-639 Package commons-lang, which is a required
dependency, as part of storm plugin
Signed-off-by: sneethiraj
---
src/main/assembly/storm-agent.xml | 27 ++++++++++++++-------------
1 file changed, 14 insertions(+), 13 deletions(-)
diff --git a/src/main/assembly/storm-agent.xml b/src/main/assembly/storm-agent.xml
index aacdb78d185..22a75a7ed87 100644
--- a/src/main/assembly/storm-agent.xml
+++ b/src/main/assembly/storm-agent.xml
@@ -42,27 +42,28 @@
org.eclipse.persistence:eclipselink
org.eclipse.persistence:javax.persistence
commons-collections:commons-collections
- com.sun.jersey:jersey-bundle
+ com.sun.jersey:jersey-bundle
commons-logging:commons-logging:jar:${commons.logging.version}
com.google.guava:guava:jar:${guava.version}
org.codehaus.jackson:jackson-jaxrs:jar:${codehaus.jackson.version}
org.codehaus.jackson:jackson-core-asl:jar:${codehaus.jackson.storm.version}
org.codehaus.jackson:jackson-mapper-asl:jar:${codehaus.jackson.storm.version}
- org.apache.httpcomponents:httpclient:jar:${httpcomponent.httpclient.version}
- org.apache.httpcomponents:httpcore:jar:${httpcomponent.httpcore.version}
- org.apache.httpcomponents:httpmime:jar:${httpcomponent.httpmime.version}
- org.noggit:noggit:jar:${noggit.version}
- com.google.protobuf:protobuf-java:jar:${protobuf-java.version}
- org.apache.hadoop:hadoop-hdfs:jar:${hadoop.version}
- org.apache.htrace:htrace-core:jar:${htrace-core.version}
- commons-cli:commons-cli:jar:${commons.cli.version}
+ org.apache.httpcomponents:httpclient:jar:${httpcomponent.httpclient.version}
+ org.apache.httpcomponents:httpcore:jar:${httpcomponent.httpcore.version}
+ org.apache.httpcomponents:httpmime:jar:${httpcomponent.httpmime.version}
+ org.noggit:noggit:jar:${noggit.version}
+ com.google.protobuf:protobuf-java:jar:${protobuf-java.version}
+ org.apache.hadoop:hadoop-hdfs:jar:${hadoop.version}
+ org.apache.htrace:htrace-core:jar:${htrace-core.version}
+ commons-cli:commons-cli:jar:${commons.cli.version}
+ commons-lang:commons-lang:jar:${commons.lang.version}
/install/lib
false
- 755
- 644
+ 755
+ 644
commons-cli:commons-cli
commons-collections:commons-collections
@@ -76,8 +77,8 @@
org.slf4j:slf4j-api:jar:${slf4j-api.version}
org.apache.hadoop:hadoop-common:jar:${hadoop-common.version}
org.apache.hadoop:hadoop-auth:jar:${hadoop-common.version}
- security_plugins.ranger-plugins-cred:ranger-plugins-cred
- org.apache.ranger:credentialbuilder
+ security_plugins.ranger-plugins-cred:ranger-plugins-cred
+ org.apache.ranger:credentialbuilder
From a3c9d8c6b1b4f72b0ef6c23abb49693c2c73e504 Mon Sep 17 00:00:00 2001
From: Gautam Borad
Date: Wed, 9 Sep 2015 14:55:19 +0530
Subject: [PATCH 046/202] RANGER-642 : Update USERSEARCHFILTER for Ranger
Authentication on Windows
Signed-off-by: Velmurugan Periasamy
---
security-admin/src/bin/ranger_install.py | 8 ++++++++
1 file changed, 8 insertions(+)
diff --git a/security-admin/src/bin/ranger_install.py b/security-admin/src/bin/ranger_install.py
index 2970715219f..99c8ab831b5 100644
--- a/security-admin/src/bin/ranger_install.py
+++ b/security-admin/src/bin/ranger_install.py
@@ -944,6 +944,10 @@ def update_properties():
propertyName="ranger.ldap.referral"
newPropertyValue=os.getenv("RANGER_LDAP_REFERRAL")
updatePropertyToFilePy(propertyName ,newPropertyValue ,to_file_ranger)
+
+ propertyName="ranger.ldap.user.searchfilter"
+ newPropertyValue=os.getenv("RANGER_LDAP_USERSEARCHFILTER")
+ updatePropertyToFilePy(propertyName ,newPropertyValue ,to_file_ranger)
elif os.getenv("RANGER_AUTHENTICATION_METHOD") == "ACTIVE_DIRECTORY":
propertyName="ranger.authentication.method"
@@ -974,6 +978,10 @@ def update_properties():
newPropertyValue=os.getenv("RANGER_LDAP_AD_REFERRAL")
updatePropertyToFilePy(propertyName ,newPropertyValue ,to_file_ranger)
+ propertyName="ranger.ldap.ad.user.searchfilter"
+ newPropertyValue=os.getenv("RANGER_LDAP_AD_USERSEARCHFILTER")
+ updatePropertyToFilePy(propertyName ,newPropertyValue ,to_file_ranger)
+
def setup_authentication(authentication_method, xmlPath):
if authentication_method == "UNIX":
# log("Setting up UNIX authentication for : " + xmlPath,"debug")
From 8d7b6cd7387975b038bd3decd2d671687702309e Mon Sep 17 00:00:00 2001
From: Abhay Kulkarni
Date: Wed, 9 Sep 2015 15:03:54 -0700
Subject: [PATCH 047/202] RANGER-621 - Updated Solr service-def to fix
incorrect impliedGrants
Signed-off-by: Madhan Neethiraj
---
.../main/resources/service-defs/ranger-servicedef-solr.json | 4 +---
1 file changed, 1 insertion(+), 3 deletions(-)
diff --git a/agents-common/src/main/resources/service-defs/ranger-servicedef-solr.json b/agents-common/src/main/resources/service-defs/ranger-servicedef-solr.json
index bc27352b06d..2f12721e101 100644
--- a/agents-common/src/main/resources/service-defs/ranger-servicedef-solr.json
+++ b/agents-common/src/main/resources/service-defs/ranger-servicedef-solr.json
@@ -49,11 +49,9 @@
"name":"solr_admin",
"label":"Solr Admin",
"impliedGrants":[
- "query,update,others"
+ "query","update","others"
]
-
}
-
],
"configs":[
{
From 9adc04efd568746d98232efbcaa1b7525c5ee3a4 Mon Sep 17 00:00:00 2001
From: Gautam Borad
Date: Thu, 3 Sep 2015 17:51:20 +0530
Subject: [PATCH 048/202] RANGER-641 : Ranger KMS startup fails if java not set
and started using service
Signed-off-by: Velmurugan Periasamy
---
kms/scripts/ranger-kms | 4 ++++
kms/scripts/setup.sh | 6 +++---
2 files changed, 7 insertions(+), 3 deletions(-)
diff --git a/kms/scripts/ranger-kms b/kms/scripts/ranger-kms
index 805ebcc0020..dfde6d5c63b 100755
--- a/kms/scripts/ranger-kms
+++ b/kms/scripts/ranger-kms
@@ -32,6 +32,10 @@ RANGER_KMS_EWS_LIB_DIR="${RANGER_KMS_EWS_DIR}/webapp/WEB-INF/classes/lib"
JAVA_OPTS=" ${JAVA_OPTS} -XX:MaxPermSize=256m -Xmx1024m -Xms1024m "
+if [ -f ${RANGER_KMS_DIR}/ews/webapp/WEB-INF/classes/conf/java_home.sh ]; then
+ . ${RANGER_KMS_DIR}/ews/webapp/WEB-INF/classes/conf/java_home.sh
+fi
+
for custom_env_script in `find ${RANGER_KMS_DIR}/ews/webapp/WEB-INF/classes/conf/ -name "ranger-kms-env*"`; do
if [ -f $custom_env_script ]; then
. $custom_env_script
diff --git a/kms/scripts/setup.sh b/kms/scripts/setup.sh
index 2e7dd8ecd65..e0c3136cbc3 100755
--- a/kms/scripts/setup.sh
+++ b/kms/scripts/setup.sh
@@ -326,7 +326,7 @@ setup_kms(){
log "[I] Adding ranger kms provider as services in hadoop-common jar"
for f in lib/hadoop-common*.jar
do
- jar -uf ${f} META-INF/services/org.apache.hadoop.crypto.key.KeyProviderFactory
+ ${JAVA_HOME}/bin/jar -uf ${f} META-INF/services/org.apache.hadoop.crypto.key.KeyProviderFactory
chown ${unix_user}:${unix_group} ${f}
done
cd ${oldP}
@@ -334,8 +334,8 @@ setup_kms(){
update_properties() {
newPropertyValue=''
- #echo "export JAVA_HOME=${JAVA_HOME}" > ${WEBAPP_ROOT}/WEB-INF/classes/conf/java_home.sh
- #chmod a+rx ${WEBAPP_ROOT}/WEB-INF/classes/conf/java_home.sh
+ echo "export JAVA_HOME=${JAVA_HOME}" > ${WEBAPP_ROOT}/WEB-INF/classes/conf/java_home.sh
+ chmod a+rx ${WEBAPP_ROOT}/WEB-INF/classes/conf/java_home.sh
to_file=$PWD/ews/webapp/WEB-INF/classes/conf/dbks-site.xml
From ff75b9baf10e97b25cd480c49c576ee09a3c8bb3 Mon Sep 17 00:00:00 2001
From: Alok Lal
Date: Fri, 28 Aug 2015 18:19:56 -0700
Subject: [PATCH 049/202] RANGER-627 Add start/stop/progress log messages so
processing of Audit's JVM shutdown hooks can be monitored
---
.../audit/provider/AsyncAuditProvider.java | 48 +++++++++++++------
.../audit/provider/AuditProviderFactory.java | 9 +++-
.../audit/provider/DbAuditProvider.java | 15 +-----
.../provider/MultiDestAuditProvider.java | 10 ++--
4 files changed, 47 insertions(+), 35 deletions(-)
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/provider/AsyncAuditProvider.java b/agents-audit/src/main/java/org/apache/ranger/audit/provider/AsyncAuditProvider.java
index f469d801e82..446ef95e4f8 100644
--- a/agents-audit/src/main/java/org/apache/ranger/audit/provider/AsyncAuditProvider.java
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/provider/AsyncAuditProvider.java
@@ -42,6 +42,9 @@ public class AsyncAuditProvider extends MultiDestAuditProvider implements
private int mMaxQueueSize = 10 * 1024;
private int mMaxFlushInterval = 5000; // 5 seconds
+ private static final int mStopLoopIntervalSecs = 1; // 1 second
+ private static final int mWaitToCompleteLoopIntervalSecs = 1; // 1 second
+
// Summary of logs handled
private AtomicLong lifeTimeInLogCount = new AtomicLong(0); // Total count, including drop count
private AtomicLong lifeTimeOutLogCount = new AtomicLong(0);
@@ -110,15 +113,24 @@ public void start() {
@Override
public void stop() {
- mThread.interrupt();
-
+ LOG.info("==> AsyncAuditProvider.stop()");
try {
- mThread.join();
- } catch (InterruptedException excp) {
- LOG.error("AsyncAuditProvider.stop(): failed while waiting for thread to exit", excp);
- }
+ LOG.info("Interrupting child thread of " + mName + "..." );
+ mThread.interrupt();
+ while (mThread.isAlive()) {
+ try {
+ LOG.info(String.format("Waiting for child thread of %s to exit. Sleeping for %d secs", mName, mStopLoopIntervalSecs));
+ mThread.join(mStopLoopIntervalSecs * 1000);
+ } catch (InterruptedException e) {
+ LOG.warn("Interrupted while waiting for child thread to join! Proceeding with stop", e);
+ break;
+ }
+ }
- super.stop();
+ super.stop();
+ } finally {
+ LOG.info("<== AsyncAuditProvider.stop()");
+ }
}
@Override
@@ -144,6 +156,7 @@ public void run() {
flush();
}
} catch (InterruptedException excp) {
+ LOG.info("AsyncAuditProvider.run - Interrupted! Breaking out of while loop.");
break;
} catch (Exception excp) {
logFailedEvent(event, excp);
@@ -237,16 +250,21 @@ private boolean isEmpty() {
public void waitToComplete(long maxWaitSeconds) {
LOG.debug("==> AsyncAuditProvider.waitToComplete()");
- for (long waitTime = 0; !isEmpty()
- && (maxWaitSeconds <= 0 || maxWaitSeconds > waitTime); waitTime++) {
- try {
- Thread.sleep(1000);
- } catch (Exception excp) {
- // ignore
+ try {
+ for (long waitTime = 0; !isEmpty()
+ && (maxWaitSeconds <= 0 || maxWaitSeconds > waitTime); waitTime += mWaitToCompleteLoopIntervalSecs) {
+ try {
+ LOG.info(String.format("%d messages yet to be flushed by %s. Sleeoping for %d sec", mQueue.size(), mName, mWaitToCompleteLoopIntervalSecs));
+ Thread.sleep(mWaitToCompleteLoopIntervalSecs * 1000);
+ } catch (InterruptedException excp) {
+ // someone really wants service to exit, abandon unwritten audits and exit.
+ LOG.warn("Caught interrupted exception! " + mQueue.size() + " messages still unflushed! Won't wait for queue to flush, exiting...", excp);
+ break;
+ }
}
+ } finally {
+ LOG.debug("<== AsyncAuditProvider.waitToComplete()");
}
-
- LOG.debug("<== AsyncAuditProvider.waitToComplete()");
}
private long getTimeTillNextFlush() {
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/provider/AuditProviderFactory.java b/agents-audit/src/main/java/org/apache/ranger/audit/provider/AuditProviderFactory.java
index 1146e0bde52..723b5285ee5 100644
--- a/agents-audit/src/main/java/org/apache/ranger/audit/provider/AuditProviderFactory.java
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/provider/AuditProviderFactory.java
@@ -451,8 +451,13 @@ public JVMShutdownHook(AuditHandler provider) {
}
public void run() {
- mProvider.waitToComplete();
- mProvider.stop();
+ LOG.info("==> JVMShutdownHook.run()");
+ try {
+ mProvider.waitToComplete();
+ mProvider.stop();
+ } finally {
+ LOG.info("<== JVMShutdownHook.run()");
+ }
}
}
}
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/provider/DbAuditProvider.java b/agents-audit/src/main/java/org/apache/ranger/audit/provider/DbAuditProvider.java
index f23f17d21e9..8319d36a72d 100644
--- a/agents-audit/src/main/java/org/apache/ranger/audit/provider/DbAuditProvider.java
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/provider/DbAuditProvider.java
@@ -106,7 +106,7 @@ public boolean log(AuditEventBase event) {
try {
if(preCreate(event)) {
DaoManager daoMgr = daoManager;
-
+
if(daoMgr != null) {
event.persist(daoMgr);
@@ -120,6 +120,7 @@ public boolean log(AuditEventBase event) {
logFailedEvent(event);
}
}
+ LOG.debug("<== DbAuditProvider.log()");
return isSuccess;
}
@@ -167,18 +168,6 @@ public void stop() {
cleanUp();
}
-
- @Override
- public void waitToComplete() {
- LOG.info("DbAuditProvider.waitToComplete()");
- waitToComplete(-1);
- }
-
- @Override
- public void waitToComplete(long timeout) {
- LOG.info("DbAuditProvider.waitToComplete():timeout=" + timeout);
-
- }
@Override
public void flush() {
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/provider/MultiDestAuditProvider.java b/agents-audit/src/main/java/org/apache/ranger/audit/provider/MultiDestAuditProvider.java
index 26108ca5ab4..282f5abfa0b 100644
--- a/agents-audit/src/main/java/org/apache/ranger/audit/provider/MultiDestAuditProvider.java
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/provider/MultiDestAuditProvider.java
@@ -161,7 +161,7 @@ public void start() {
try {
provider.start();
} catch (Throwable excp) {
- LOG.error("AsyncAuditProvider.start(): failed for provider { "
+ LOG.error("MultiDestAuditProvider.start(): failed for provider { "
+ provider.getClass().getName() + " }", excp);
}
}
@@ -173,7 +173,7 @@ public void stop() {
try {
provider.stop();
} catch (Throwable excp) {
- LOG.error("AsyncAuditProvider.stop(): failed for provider { "
+ LOG.error("MultiDestAuditProvider.stop(): failed for provider { "
+ provider.getClass().getName() + " }", excp);
}
}
@@ -186,7 +186,7 @@ public void waitToComplete() {
provider.waitToComplete();
} catch (Throwable excp) {
LOG.error(
- "AsyncAuditProvider.waitToComplete(): failed for provider { "
+ "MultiDestAuditProvider.waitToComplete(): failed for provider { "
+ provider.getClass().getName() + " }", excp);
}
}
@@ -199,7 +199,7 @@ public void waitToComplete(long timeout) {
provider.waitToComplete(timeout);
} catch (Throwable excp) {
LOG.error(
- "AsyncAuditProvider.waitToComplete(): failed for provider { "
+ "MultiDestAuditProvider.waitToComplete(): failed for provider { "
+ provider.getClass().getName() + " }", excp);
}
}
@@ -211,7 +211,7 @@ public void flush() {
try {
provider.flush();
} catch (Throwable excp) {
- LOG.error("AsyncAuditProvider.flush(): failed for provider { "
+ LOG.error("MultiDestAuditProvider.flush(): failed for provider { "
+ provider.getClass().getName() + " }", excp);
}
}
From e6ac04c570f59689076c6d8d78d922b3c579c0f3 Mon Sep 17 00:00:00 2001
From: Alok Lal
Date: Fri, 4 Sep 2015 18:42:05 -0700
Subject: [PATCH 050/202] RANGER-632 Simplify policy and service-def validation
related error messages that would be seen by the user.
Signed-off-by: Alok Lal
---
.../plugin/errors/ValidationErrorCode.java | 36 +++++++++--------
.../validation/RangerPolicyValidator.java | 39 +++++++++++++------
.../validation/ValidationFailureDetails.java | 2 +-
3 files changed, 48 insertions(+), 29 deletions(-)
diff --git a/agents-common/src/main/java/org/apache/ranger/plugin/errors/ValidationErrorCode.java b/agents-common/src/main/java/org/apache/ranger/plugin/errors/ValidationErrorCode.java
index b458394d6aa..72f7205291c 100644
--- a/agents-common/src/main/java/org/apache/ranger/plugin/errors/ValidationErrorCode.java
+++ b/agents-common/src/main/java/org/apache/ranger/plugin/errors/ValidationErrorCode.java
@@ -32,12 +32,12 @@ public enum ValidationErrorCode {
SERVICE_VALIDATION_ERR_NULL_SERVICE_OBJECT(1003, "Internal error: service object passed in was null"),
SERVICE_VALIDATION_ERR_EMPTY_SERVICE_ID(1004, "Internal error: service id was null/empty/blank"),
SERVICE_VALIDATION_ERR_INVALID_SERVICE_ID(1005, "No service found for id [{0}]"),
- SERVICE_VALIDATION_ERR_INVALID_SERVICE_NAME(1006, "Service name[{0}] was null/empty/blank"),
- SERVICE_VALIDATION_ERR_SERVICE_NAME_CONFICT(1007, "service with the name[{0}] already exists"),
- SERVICE_VALIDATION_ERR_ID_NAME_CONFLICT(1008, "id/name conflict: another service already exists with name[{0}], its id is [{1}]"),
- SERVICE_VALIDATION_ERR_MISSING_SERVICE_DEF(1009, "service def [{0}] was null/empty/blank"),
- SERVICE_VALIDATION_ERR_INVALID_SERVICE_DEF(1010, "service def named[{0}] not found"),
- SERVICE_VALIDATION_ERR_REQUIRED_PARM_MISSING(1011, "required configuration parameter is missing; missing parameters: {0}"),
+ SERVICE_VALIDATION_ERR_INVALID_SERVICE_NAME(1006, "Missing service name"),
+ SERVICE_VALIDATION_ERR_SERVICE_NAME_CONFICT(1007, "Duplicate service name: name=[{0}]"),
+ SERVICE_VALIDATION_ERR_ID_NAME_CONFLICT(1008, "Duplicate service name: name=[{0}], id=[{1}]"),
+ SERVICE_VALIDATION_ERR_MISSING_SERVICE_DEF(1009, "Missing service def"),
+ SERVICE_VALIDATION_ERR_INVALID_SERVICE_DEF(1010, "Service def not found: service-def-name=[{0}]"),
+ SERVICE_VALIDATION_ERR_REQUIRED_PARM_MISSING(1011, "Missing required configuration parameter(s): missing parameters={0}"),
// SERVICE-DEF VALIDATION
SERVICE_DEF_VALIDATION_ERR_UNSUPPORTED_ACTION(2001, "Internal error: unsupported action[{0}]; isValid(Long) is only supported for DELETE"),
@@ -65,26 +65,28 @@ public enum ValidationErrorCode {
POLICY_VALIDATION_ERR_UNSUPPORTED_ACTION(3001, "Internal error: method signature isValid(Long) is only supported for DELETE"),
POLICY_VALIDATION_ERR_MISSING_FIELD(3002, "Internal error: missing field[{0}]"),
POLICY_VALIDATION_ERR_NULL_POLICY_OBJECT(3003, "Internal error: policy object passed in was null"),
- POLICY_VALIDATION_ERR_INVALID_POLICY_ID(3004, "Invalid policy id provided for update: no policy found for id[{0}]"),
+ POLICY_VALIDATION_ERR_INVALID_POLICY_ID(3004, "No policy found for id[{0}]"),
POLICY_VALIDATION_ERR_POLICY_NAME_MULTIPLE_POLICIES_WITH_SAME_NAME(3005, "Internal error: multiple policies found with the name[{0}]"),
- POLICY_VALIDATION_ERR_POLICY_NAME_CONFLICT(3006, "id/name conflict: another policy already exists with name[{0}] for service[{1}, its id is[{2}]"),
+ POLICY_VALIDATION_ERR_POLICY_NAME_CONFLICT(3006, "Another policy already exists for this name: policy-id=[{0}], service=[{1}]"),
POLICY_VALIDATION_ERR_INVALID_SERVICE_NAME(3007, "no service found with name[{0}]"),
POLICY_VALIDATION_ERR_MISSING_POLICY_ITEMS(3008, "at least one policy item must be specified if audit isn't enabled"),
POLICY_VALIDATION_ERR_MISSING_SERVICE_DEF(3009, "Internal error: Service def[{0}] of policy's service[{1}] does not exist!"),
- POLICY_VALIDATION_ERR_DUPLICATE_POLICY_RESOURCE(3010, "another policy[{0}] with matching resources[{1}] exists for service[{2}]!"),
- POLICY_VALIDATION_ERR_INVALID_RESOURCE_NO_COMPATIBLE_HIERARCHY(3011, "policy resources [{0}] are not compatible with any resource hierarchy for service def[{1}]! Valid hierarchies are: {2}"),
- POLICY_VALIDATION_ERR_INVALID_RESOURCE_MISSING_MANDATORY(3012, "policy is missing required resources. Mandatory resources of potential hierarchies are: {0}"),
+ POLICY_VALIDATION_ERR_DUPLICATE_POLICY_RESOURCE(3010, "Another policy already exists for matching resource: policy-name=[{0}], service=[{1}]"),
+ POLICY_VALIDATION_ERR_INVALID_RESOURCE_NO_COMPATIBLE_HIERARCHY(3011, "Invalid resources specified. {0} policy can specify values for one of the following resource sets: {1}"),
+ POLICY_VALIDATION_ERR_INVALID_RESOURCE_MISSING_MANDATORY(3012, "Invalid resources specified. {0} policy must specify values for one of the following resource sets: {1}"),
POLICY_VALIDATION_ERR_NULL_RESOURCE_DEF(3013, "Internal error: a resource-def on resource def collection of service-def[{0}] was null"),
POLICY_VALIDATION_ERR_MISSING_RESOURCE_DEF_NAME(3014, "Internal error: name of a resource-def on resource def collection of service-def[{0}] was null"),
- POLICY_VALIDATION_ERR_EXCLUDES_NOT_SUPPORTED(3015, "isExcludes specified as [{0}] for resource [{1}] which doesn't support isExcludes"),
- POLICY_VALIDATION_ERR_EXCLUDES_REQUIRES_ADMIN(3016, "isExcludes specified as [{0}] for resource [{1}]. Insufficient permissions to create excludes policy."),
- POLICY_VALIDATION_ERR_RECURSIVE_NOT_SUPPORTED(3017, "isRecursive specified as [{0}] for resource [{1}] which doesn't support isRecursive"),
- POLICY_VALIDATION_ERR_INVALID_RESOURCE_VALUE_REGEX(3018, "Value[{0}] of resource[{1}] does not conform to the validation regex[{2}] defined on the service-def[{3}]"),
+ POLICY_VALIDATION_ERR_EXCLUDES_NOT_SUPPORTED(3015, "Excludes option not supported: resource-name=[{0}]"),
+ POLICY_VALIDATION_ERR_EXCLUDES_REQUIRES_ADMIN(3016, "Insufficient permissions to create excludes policy"),
+ POLICY_VALIDATION_ERR_RECURSIVE_NOT_SUPPORTED(3017, "Recursive option not supported: resource-name=[{0}]."),
+ POLICY_VALIDATION_ERR_INVALID_RESOURCE_VALUE_REGEX(3018, "Invalid resource specified. A value of [{0}] is not valid for resource [{1}]"),
POLICY_VALIDATION_ERR_NULL_POLICY_ITEM(3019, "policy items object was null"),
POLICY_VALIDATION_ERR_MISSING_USER_AND_GROUPS(3020, "both users and user-groups collections on the policy item were null/empty"),
POLICY_VALIDATION_ERR_NULL_POLICY_ITEM_ACCESS(3021, "policy items access object was null"),
- POLICY_VALIDATION_ERR_POLICY_ITEM_ACCESS_TYPE_INVALID(3022, "access type[{0}] not among valid types for service[{1}]"),
- POLICY_VALIDATION_ERR_POLICY_ITEM_ACCESS_TYPE_DENY(3023, "access type is set to deny. Currently deny access types are not supported."),
+ POLICY_VALIDATION_ERR_POLICY_ITEM_ACCESS_TYPE_INVALID(3022, "Invalid access type: access type=[{0}], valid access types=[{1}]"),
+ POLICY_VALIDATION_ERR_POLICY_ITEM_ACCESS_TYPE_DENY(3023, "Currently deny access types are not supported. Access type is set to deny."),
+ POLICY_VALIDATION_ERR_INVALID_RESOURCE_NO_COMPATIBLE_HIERARCHY_SINGLE(3024, "Invalid resources specified. {0} policy can specify values for the following resources: {1}"),
+ POLICY_VALIDATION_ERR_INVALID_RESOURCE_MISSING_MANDATORY_SINGLE(3025, "Invalid resources specified. {0} policy must specify values for the following resources: {1}"),
;
diff --git a/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerPolicyValidator.java b/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerPolicyValidator.java
index da817c69996..66768c2b154 100644
--- a/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerPolicyValidator.java
+++ b/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerPolicyValidator.java
@@ -170,7 +170,7 @@ boolean isValid(RangerPolicy policy, Action action, boolean isAdmin, List> candidateHierarchies = filterHierarchies_hierarchyHasAllPolicyResources(policyResources, hierarchies, defHelper);
if (candidateHierarchies.isEmpty()) {
- ValidationErrorCode error = ValidationErrorCode.POLICY_VALIDATION_ERR_INVALID_RESOURCE_NO_COMPATIBLE_HIERARCHY;
+ if (LOG.isDebugEnabled()) {
+ LOG.debug(String.format("No compatible resource hierarchies found: resource[%s], service-def[%s], valid-resource-hierarchies[%s]",
+ policyResources.toString(), serviceDef.getName(), toStringHierarchies_all(hierarchies, defHelper)));
+ }
+ ValidationErrorCode error;
+ if (hierarchies.size() == 1) { // we can give a simpler message for single hierarchy service-defs which is the majority of cases
+ error = ValidationErrorCode.POLICY_VALIDATION_ERR_INVALID_RESOURCE_NO_COMPATIBLE_HIERARCHY_SINGLE;
+ } else {
+ error = ValidationErrorCode.POLICY_VALIDATION_ERR_INVALID_RESOURCE_NO_COMPATIBLE_HIERARCHY;
+ }
failures.add(new ValidationFailureDetailsBuilder()
.field("policy resources")
.subField("incompatible")
.isSemanticallyIncorrect()
- .becauseOf(error.getMessage(policyResources.toString(), serviceDef.getName(), toStringHierarchies_all(hierarchies, defHelper)))
+ .becauseOf(error.getMessage(serviceDef.getName(), toStringHierarchies_all(hierarchies, defHelper)))
.errorCode(error.getErrorCode())
.build());
valid = false;
@@ -353,12 +362,17 @@ boolean isValidResourceNames(final RangerPolicy policy, final List> validHierarchies = filterHierarchies_mandatoryResourcesSpecifiedInPolicy(policyResources, candidateHierarchies, defHelper);
if (validHierarchies.isEmpty()) {
- ValidationErrorCode error = ValidationErrorCode.POLICY_VALIDATION_ERR_INVALID_RESOURCE_MISSING_MANDATORY;
+ ValidationErrorCode error;
+ if (candidateHierarchies.size() == 1) { // we can provide better message if there is a single candidate hierarchy
+ error = ValidationErrorCode.POLICY_VALIDATION_ERR_INVALID_RESOURCE_MISSING_MANDATORY_SINGLE;
+ } else {
+ error = ValidationErrorCode.POLICY_VALIDATION_ERR_INVALID_RESOURCE_MISSING_MANDATORY;
+ }
failures.add(new ValidationFailureDetailsBuilder()
.field("policy resources")
.subField("missing mandatory")
.isSemanticallyIncorrect()
- .becauseOf(error.getMessage(toStringHierarchies_mandatory(candidateHierarchies, defHelper)))
+ .becauseOf(error.getMessage(serviceDef.getName(), toStringHierarchies_mandatory(candidateHierarchies, defHelper)))
.errorCode(error.getErrorCode())
.build());
valid = false;
@@ -495,7 +509,7 @@ boolean isValidResourceFlags(final Map inputPolicy
.field("isExcludes")
.subField(resourceName)
.isSemanticallyIncorrect()
- .becauseOf(error.getMessage(policyResourceIsExcludes, resourceName))
+ .becauseOf(error.getMessage(resourceName))
.errorCode(error.getErrorCode())
.build());
valid = false;
@@ -506,7 +520,7 @@ boolean isValidResourceFlags(final Map inputPolicy
.field("isExcludes")
.subField("isAdmin")
.isSemanticallyIncorrect()
- .becauseOf(error.getMessage(policyResourceIsExcludes, resourceName))
+ .becauseOf(error.getMessage())
.errorCode(error.getErrorCode())
.build());
valid = false;
@@ -519,7 +533,7 @@ boolean isValidResourceFlags(final Map inputPolicy
.field("isRecursive")
.subField(resourceName)
.isSemanticallyIncorrect()
- .becauseOf(error.getMessage(policyIsRecursive, resourceName))
+ .becauseOf(error.getMessage(resourceName))
.errorCode(error.getErrorCode())
.build());
valid = false;
@@ -551,12 +565,15 @@ boolean isValidResourceValues(Map resourceMap, Lis
if (StringUtils.isBlank(aValue)) {
LOG.debug("resource value was blank");
} else if (!aValue.matches(regEx)) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug(String.format("Resource failed regex check: value[%s], resource-name[%s], regEx[%s], service-def-name[%s]", aValue, name, regEx, serviceDef.getName()));
+ }
ValidationErrorCode error = ValidationErrorCode.POLICY_VALIDATION_ERR_INVALID_RESOURCE_VALUE_REGEX;
failures.add(new ValidationFailureDetailsBuilder()
.field("resource-values")
.subField(name)
.isSemanticallyIncorrect()
- .becauseOf(error.getMessage(aValue, name, regEx, serviceDef.getName()))
+ .becauseOf(error.getMessage(aValue, name))
.errorCode(error.getErrorCode())
.build());
valid = false;
diff --git a/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/ValidationFailureDetails.java b/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/ValidationFailureDetails.java
index a0e85738275..e9ad40a9d2c 100644
--- a/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/ValidationFailureDetails.java
+++ b/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/ValidationFailureDetails.java
@@ -74,7 +74,7 @@ public String getSubFieldName() {
@Override
public String toString() {
LOG.debug("ValidationFailureDetails.toString()");
- return String.format("%s: error code[%d], reason[%s], field[%s], subfield[%s], type[%s]", "Policy validation failure",
+ return String.format(" %s: error code[%d], reason[%s], field[%s], subfield[%s], type[%s]", "Validation failure",
_errorCode, _reason, _fieldName, _subFieldName, getType());
}
From 97453ff07cad0b7e73f645e22fb543b427680973 Mon Sep 17 00:00:00 2001
From: fi_niting
Date: Tue, 15 Sep 2015 17:11:59 +0530
Subject: [PATCH 051/202] RANGER-632 Added validation error msg on Ranger UI in
service/policy create page and also added pause option in bootstrap-notify
plugin.
Signed-off-by: Alok Lal
---
.../bootstrap-notify/js/bootstrap-notify.js | 44 ++++++++++++++++---
.../src/main/webapp/scripts/utils/XAUtils.js | 26 ++++++++++-
.../views/policies/RangerPolicyCreate.js | 12 +++--
.../scripts/views/service/ServiceCreate.js | 23 +++-------
security-admin/src/main/webapp/styles/xa.css | 5 +++
5 files changed, 80 insertions(+), 30 deletions(-)
diff --git a/security-admin/src/main/webapp/libs/bower/bootstrap-notify/js/bootstrap-notify.js b/security-admin/src/main/webapp/libs/bower/bootstrap-notify/js/bootstrap-notify.js
index e58c6c50ab0..ba309e210bc 100644
--- a/security-admin/src/main/webapp/libs/bower/bootstrap-notify/js/bootstrap-notify.js
+++ b/security-admin/src/main/webapp/libs/bower/bootstrap-notify/js/bootstrap-notify.js
@@ -47,13 +47,21 @@
this.$note.text(this.options.message.text);
} else
this.$note.html(this.options.message);
-
+
+ var style = this.options.type == 'error' ? 'color:#a94442' : 'color:#3c763d';
+
if(this.options.closable) {
- var link = $('×');
+ var link = $('×');
$(link).on('click', $.proxy(onClose, this));
this.$note.prepend(link);
}
+ if(this.options.pausable) {
+ var pauseLink = $('');
+ $(pauseLink).on('click', $.proxy(onPause, this));
+ this.$note.prepend(pauseLink);
+
+ }
return this;
};
@@ -64,10 +72,31 @@
return false;
};
+ var onPause = function() {
+ if(this.$note.find('.pause').is(':visible')){
+ clearInterval(this.clearNotifyInterval)
+ this.$note.find('.pause').hide()
+ this.$note.find('.play').show()
+ }else{
+ setFadeOut(this)
+ this.$note.find('.pause').show()
+ this.$note.find('.play').hide()
+ }
+ return false;
+ };
+ var setFadeOut = function(self){
+ var that = self;
+ self.clearNotifyInterval = setTimeout(function() {
+ that.$note.fadeOut('slow', $.proxy(that.onClose, that));
+ }, self.options.fadeOut.delay || 7000);
+ };
+
Notification.prototype.show = function () {
- if(this.options.fadeOut.enabled)
- this.$note.delay(this.options.fadeOut.delay || 3000).fadeOut('slow', $.proxy(onClose, this));
-
+ var that = this;
+ if(this.options.fadeOut.enabled){
+ setFadeOut(this)
+ }
+// this.$note.delay(this.options.fadeOut.delay || 3000).fadeOut('slow', $.proxy(onClose, this));
this.$element.append(this.$note);
this.$note.alert();
};
@@ -88,10 +117,11 @@
transition: 'fade',
fadeOut: {
enabled: true,
- delay: 3000
+ delay: 7000
},
message: null,
onClose: function () {},
- onClosed: function () {}
+ onClosed: function () {},
+ pausable: false
}
})(window.jQuery);
diff --git a/security-admin/src/main/webapp/scripts/utils/XAUtils.js b/security-admin/src/main/webapp/scripts/utils/XAUtils.js
index 6d84d1cf7d9..3f52fb2990a 100644
--- a/security-admin/src/main/webapp/scripts/utils/XAUtils.js
+++ b/security-admin/src/main/webapp/scripts/utils/XAUtils.js
@@ -194,7 +194,8 @@ define(function(require) {
html : html,
text : text
},
- type : 'info'
+ type : 'info',
+ pausable: true
};
}
$('.top-right').notify(options).show();
@@ -220,7 +221,8 @@ define(function(require) {
html : html,
text : text
},
- type : 'error'
+ type : 'error',
+ pausable: true
};
}
$('.top-right').notify(options).show();
@@ -246,6 +248,7 @@ define(function(require) {
html : html
},
type : 'success',
+ pausable: true
};
}
$('.top-right').notify(options).show();
@@ -1096,5 +1099,24 @@ define(function(require) {
})
return {'userRoleList' : userRoleList };
};
+ XAUtils.showErrorMsg = function(respMsg){
+ var respArr = respMsg.split(/\([0-9]*\)/);
+ respArr.shift();
+ _.each(respArr, function(str){
+ var validationMsg = str.split(','), erroCodeMsg = '';
+ //get code from string
+ if(!_.isUndefined(validationMsg[0]) && validationMsg[0].indexOf("error code") != -1){
+ var tmp = validationMsg[0].split('error code');
+ var code = tmp[ tmp.length - 1 ];
+
+ erroCodeMsg = 'Error Code : '+ code.match(/\d/g).join('');
+ }
+ var reason = str.lastIndexOf("reason") != -1 ? (str.substring(str.lastIndexOf("reason")+7, str.indexOf("field[")-2 ))
+ : str;
+ var erroMsg = erroCodeMsg +"
"+XAUtils.capitaliseFirstLetter(reason);
+ return XAUtils.notifyError('Error', erroMsg);
+ });
+ };
+
return XAUtils;
});
diff --git a/security-admin/src/main/webapp/scripts/views/policies/RangerPolicyCreate.js b/security-admin/src/main/webapp/scripts/views/policies/RangerPolicyCreate.js
index 7370ee876eb..b07f9a2fe80 100644
--- a/security-admin/src/main/webapp/scripts/views/policies/RangerPolicyCreate.js
+++ b/security-admin/src/main/webapp/scripts/views/policies/RangerPolicyCreate.js
@@ -207,10 +207,14 @@ define(function(require){
App.appRouter.navigate("#!/service/"+that.rangerService.id+"/policies",{trigger: true});
console.log("success");
},
- error: function (model, response, options) {
- XAUtil.blockUI('unblock');
- XAUtil.notifyError('Error', 'Error creating Policy!');
- console.log("error");
+ error : function(model, response, options) {
+ XAUtil.blockUI('unblock');
+ var msg = that.editPolicy ? 'Error updating policy.': 'Error creating policy.';
+ if (response && response.responseJSON && response.responseJSON.msgDesc) {
+ XAUtil.showErrorMsg(response.responseJSON.msgDesc);
+ } else {
+ XAUtil.notifyError('Error', msg);
+ }
}
});
},
diff --git a/security-admin/src/main/webapp/scripts/views/service/ServiceCreate.js b/security-admin/src/main/webapp/scripts/views/service/ServiceCreate.js
index 01141b642e2..239b61e27a6 100644
--- a/security-admin/src/main/webapp/scripts/views/service/ServiceCreate.js
+++ b/security-admin/src/main/webapp/scripts/views/service/ServiceCreate.js
@@ -164,23 +164,12 @@ define(function(require){
},
error: function (model, response, options) {
XAUtil.blockUI('unblock');
- if ( response && response.responseJSON && response.responseJSON.msgDesc){
- if(response.responseJSON.msgDesc == "serverMsg.fsDefaultNameValidationError"){
- that.form.fields.fsDefaultName.setError(localization.tt(response.responseJSON.msgDesc));
- XAUtil.scrollToField(that.form.fields.fsDefaultName.$el);
- }else if(response.responseJSON.msgDesc == "Repository Name already exists"){
- response.responseJSON.msgDesc = "serverMsg.repositoryNameAlreadyExistsError";
- that.form.fields.name.setError(localization.tt(response.responseJSON.msgDesc));
- XAUtil.scrollToField(that.form.fields.name.$el);
- }else if(response.responseJSON.msgDesc == "XUser already exists"){
- response.responseJSON.msgDesc = "serverMsg.userAlreadyExistsError";
- that.form.fields.userName.setError(localization.tt(response.responseJSON.msgDesc));
- XAUtil.scrollToField(that.form.fields.userName.$el);
- }else
- XAUtil.notifyError('Error', response.responseJSON.msgDesc);
- }else
- XAUtil.notifyError('Error', 'Error creating Service!');
- console.log("error");
+ var msg = that.editService ? 'Error updating Service.': 'Error creating Service.';
+ if (response && response.responseJSON && response.responseJSON.msgDesc) {
+ XAUtil.showErrorMsg(response.responseJSON.msgDesc);
+ } else {
+ XAUtil.notifyError('Error', msg);
+ }
}
});
},
diff --git a/security-admin/src/main/webapp/styles/xa.css b/security-admin/src/main/webapp/styles/xa.css
index ceb1f538532..f0c75307d6a 100644
--- a/security-admin/src/main/webapp/styles/xa.css
+++ b/security-admin/src/main/webapp/styles/xa.css
@@ -1838,4 +1838,9 @@ td.select-row-cell {
#r_topNav .dropdown-menu {
margin:0;
+}
+.pause-play-close{
+ margin-left: -5px;
+ margin-top: -2px;
+ font-size: 11px;
}
\ No newline at end of file
From 1dbc7a1a25c3d32ebdcbf85398738ad63f9391c1 Mon Sep 17 00:00:00 2001
From: Gautam Borad
Date: Tue, 15 Sep 2015 13:50:35 +0530
Subject: [PATCH 052/202] RANGER-630 : Data consistency across API and UI
Signed-off-by: Velmurugan Periasamy
---
.../java/org/apache/ranger/biz/UserMgr.java | 73 +--
.../java/org/apache/ranger/biz/XAuditMgr.java | 73 ++-
.../java/org/apache/ranger/biz/XUserMgr.java | 278 +++++----
.../org/apache/ranger/db/XXGroupUserDao.java | 21 +
.../org/apache/ranger/db/XXModuleDefDao.java | 38 ++
.../org/apache/ranger/rest/AssetREST.java | 15 +-
.../org/apache/ranger/rest/PublicAPIsv2.java | 2 +-
.../org/apache/ranger/rest/ServiceREST.java | 30 +-
.../java/org/apache/ranger/rest/UserREST.java | 13 +-
.../org/apache/ranger/rest/XAuditREST.java | 10 +-
.../java/org/apache/ranger/rest/XKeyREST.java | 10 +-
.../org/apache/ranger/rest/XUserREST.java | 114 +++-
.../security/context/RangerAPIList.java | 201 +++++++
.../security/context/RangerAPIMapping.java | 535 ++++++++++++++++++
.../context/RangerPreAuthSecurityHandler.java | 93 +++
.../ranger/service/XAuditMapService.java | 60 ++
.../ranger/service/XPermMapService.java | 60 +-
.../ranger/service/XResourceService.java | 31 +-
.../resources/META-INF/jpa_named_queries.xml | 19 +
.../conf.dist/security-applicationContext.xml | 2 +
.../apache/ranger/audit/TestAuditQueue.java | 3 +-
.../org/apache/ranger/biz/TestUserMgr.java | 14 +-
.../org/apache/ranger/biz/TestXUserMgr.java | 9 +-
.../apache/ranger/rest/TestServiceREST.java | 2 +-
24 files changed, 1450 insertions(+), 256 deletions(-)
create mode 100644 security-admin/src/main/java/org/apache/ranger/security/context/RangerAPIList.java
create mode 100644 security-admin/src/main/java/org/apache/ranger/security/context/RangerAPIMapping.java
create mode 100644 security-admin/src/main/java/org/apache/ranger/security/context/RangerPreAuthSecurityHandler.java
diff --git a/security-admin/src/main/java/org/apache/ranger/biz/UserMgr.java b/security-admin/src/main/java/org/apache/ranger/biz/UserMgr.java
index 939ddc22dc2..ff0ea01682b 100644
--- a/security-admin/src/main/java/org/apache/ranger/biz/UserMgr.java
+++ b/security-admin/src/main/java/org/apache/ranger/biz/UserMgr.java
@@ -139,22 +139,8 @@ public UserMgr() {
public XXPortalUser createUser(VXPortalUser userProfile, int userStatus,
Collection userRoleList) {
- UserSessionBase session = ContextUtil.getCurrentUserSession();
- if (session != null) {
- if (!session.isUserAdmin()) {
- throw restErrorUtil.create403RESTException("User "
- + "creation denied. LoggedInUser="
- + (session != null ? session.getXXPortalUser().getId()
- : "Not Logged In")
- + " ,isn't permitted to perform the action.");
- }
- }else{
- VXResponse vXResponse = new VXResponse();
- vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED);
- vXResponse.setMsgDesc("Bad Credentials");
- throw restErrorUtil.generateRESTException(vXResponse);
- }
XXPortalUser user = mapVXPortalUserToXXPortalUser(userProfile);
+ checkAdminAccess();
user = createUser(user, userStatus, userRoleList);
return user;
@@ -366,6 +352,7 @@ private boolean updateRoles(Long userId, Collection rolesList) {
* @param vStrings
*/
public void setUserRoles(Long userId, List vStringRolesList) {
+ checkAccess(userId);
List stringRolesList = new ArrayList();
for (VXString vXString : vStringRolesList) {
stringRolesList.add(vXString.getValue());
@@ -384,15 +371,7 @@ public VXResponse changePassword(VXPasswordChange pwdChange) {
String currentUserLoginId = ContextUtil.getCurrentUserLoginId();
XXPortalUser gjUserCurrent = daoManager.getXXPortalUser()
.findByLoginId(currentUserLoginId);
-
- if (gjUserCurrent == null) {
- logger.info("changePassword(). Invalid user login id. userId="
- + currentUserLoginId);
- throw restErrorUtil.createRESTException(
- "serverMsg.userMgrInvalidUser",
- MessageEnums.DATA_NOT_FOUND, null, null, ""
- + currentUserLoginId);
- }
+ checkAccess(gjUserCurrent);
String encryptedOldPwd = encrypt(gjUserCurrent.getLoginId(),
pwdChange.getOldPassword());
@@ -480,7 +459,7 @@ public VXResponse changePassword(VXPasswordChange pwdChange) {
*/
public VXPortalUser changeEmailAddress(XXPortalUser gjUser,
VXPasswordChange changeEmail) {
-
+ checkAccess(gjUser);
if (gjUser.getEmailAddress() != null) {
throw restErrorUtil.createRESTException(
"serverMsg.userMgrEmailChange",
@@ -530,21 +509,7 @@ public VXPortalUser changeEmailAddress(XXPortalUser gjUser,
* @param userId
*/
public VXPortalUser deactivateUser(XXPortalUser gjUser) {
- UserSessionBase session = ContextUtil.getCurrentUserSession();
- if (session != null) {
- if (!session.isUserAdmin()) {
- throw restErrorUtil.create403RESTException("deactivation of user"
- + " denied. LoggedInUser="
- + (session != null ? session.getXXPortalUser().getId()
- : "Not Logged In")
- + " ,isn't permitted to perform the action.");
- }
- }else{
- VXResponse vXResponse = new VXResponse();
- vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED);
- vXResponse.setMsgDesc("Bad Credentials");
- throw restErrorUtil.generateRESTException(vXResponse);
- }
+ checkAdminAccess();
if (gjUser != null
&& gjUser.getStatus() != RangerConstants.ACT_STATUS_DEACTIVATED) {
logger.info("Marking user " + gjUser.getLoginId() + " as deleted");
@@ -1121,6 +1086,7 @@ public String encrypt(String loginId, String password) {
}
public VXPortalUser createUser(VXPortalUser userProfile) {
+ checkAdminAccess();
XXPortalUser xXPortalUser = this.createUser(userProfile,
RangerCommonEnums.STATUS_ENABLED);
return mapXXPortalUserVXPortalUser(xXPortalUser);
@@ -1132,21 +1098,7 @@ public VXPortalUser createDefaultAccountUser(VXPortalUser userProfile) {
userProfile.setUserSource(RangerCommonEnums.USER_EXTERNAL);
}
// access control
- UserSessionBase session = ContextUtil.getCurrentUserSession();
- if (session != null) {
- if (!session.isUserAdmin()) {
- throw restErrorUtil.create403RESTException("User "
- + "creation denied. LoggedInUser="
- + session.getXXPortalUser().getId()
- + " ,isn't permitted to perform the action.");
-
- }
- }else{
- VXResponse vXResponse = new VXResponse();
- vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED);
- vXResponse.setMsgDesc("Bad Credentials");
- throw restErrorUtil.generateRESTException(vXResponse);
- }
+ checkAdminAccess();
logger.info("create:" + userProfile.getEmailAddress());
XXPortalUser xXPortalUser = null;
String loginId = userProfile.getLoginId();
@@ -1275,4 +1227,15 @@ public XXPortalUser updatePasswordInSHA256(String userName,String userPassword)
return xXPortalUser;
}
+
+ public void checkAdminAccess() {
+ UserSessionBase sess = ContextUtil.getCurrentUserSession();
+ if (sess != null) {
+ if (sess != null && sess.isUserAdmin()) {
+ return;
+ }
+ }
+ throw restErrorUtil.create403RESTException("Operation not allowed." + " loggedInUser=" + (sess != null ? sess.getXXPortalUser().getId() : "Not Logged In"));
+ }
+
}
diff --git a/security-admin/src/main/java/org/apache/ranger/biz/XAuditMgr.java b/security-admin/src/main/java/org/apache/ranger/biz/XAuditMgr.java
index d9812f934fa..02d725f6a8e 100644
--- a/security-admin/src/main/java/org/apache/ranger/biz/XAuditMgr.java
+++ b/security-admin/src/main/java/org/apache/ranger/biz/XAuditMgr.java
@@ -19,13 +19,22 @@
package org.apache.ranger.biz;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.ranger.common.ContextUtil;
import org.apache.ranger.common.SearchCriteria;
+import org.apache.ranger.common.UserSessionBase;
import org.apache.ranger.solr.SolrAccessAuditsService;
import org.apache.ranger.view.VXAccessAudit;
import org.apache.ranger.view.VXAccessAuditList;
import org.apache.ranger.view.VXLong;
+import org.apache.ranger.view.VXResponse;
+import org.apache.ranger.view.VXTrxLog;
+import org.apache.ranger.view.VXTrxLogList;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+@Component
public class XAuditMgr extends XAuditMgrBase {
@Autowired
@@ -34,9 +43,68 @@ public class XAuditMgr extends XAuditMgrBase {
@Autowired
RangerBizUtil rangerBizUtil;
+ public VXTrxLog getXTrxLog(Long id) {
+ checkAdminAccess();
+ return super.getXTrxLog(id);
+ }
+
+ public VXTrxLog createXTrxLog(VXTrxLog vXTrxLog) {
+ checkAdminAccess();
+ return super.createXTrxLog(vXTrxLog);
+ }
+
+ public VXTrxLog updateXTrxLog(VXTrxLog vXTrxLog) {
+ checkAdminAccess();
+ return super.updateXTrxLog(vXTrxLog);
+ }
+
+ public void deleteXTrxLog(Long id, boolean force) {
+ checkAdminAccess();
+ super.deleteXTrxLog(id, force);
+ }
+
+ public VXTrxLogList searchXTrxLogs(SearchCriteria searchCriteria) {
+ checkAdminAccess();
+ return super.searchXTrxLogs(searchCriteria);
+ }
+
+ public VXLong getXTrxLogSearchCount(SearchCriteria searchCriteria) {
+ checkAdminAccess();
+ return super.getXTrxLogSearchCount(searchCriteria);
+ }
+
+ public VXAccessAudit createXAccessAudit(VXAccessAudit vXAccessAudit) {
+ checkAdminAccess();
+ return super.createXAccessAudit(vXAccessAudit);
+ }
+
+ public VXAccessAudit updateXAccessAudit(VXAccessAudit vXAccessAudit) {
+ checkAdminAccess();
+ return super.updateXAccessAudit(vXAccessAudit);
+ }
+
+ public void deleteXAccessAudit(Long id, boolean force) {
+ checkAdminAccess();
+ super.deleteXAccessAudit(id, force);
+ }
+
+ public void checkAdminAccess() {
+ UserSessionBase session = ContextUtil.getCurrentUserSession();
+ if (session != null) {
+ if (!session.isUserAdmin()) {
+ throw restErrorUtil.create403RESTException("Operation" + " denied. LoggedInUser=" + (session != null ? session.getXXPortalUser().getId() : "Not Logged In")
+ + " ,isn't permitted to perform the action.");
+ }
+ } else {
+ VXResponse vXResponse = new VXResponse();
+ vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED);
+ vXResponse.setMsgDesc("Bad Credentials");
+ throw restErrorUtil.generateRESTException(vXResponse);
+ }
+ }
+
@Override
public VXAccessAudit getXAccessAudit(Long id) {
- // TODO Auto-generated method stub
return super.getXAccessAudit(id);
}
@@ -52,8 +120,7 @@ public VXAccessAuditList searchXAccessAudits(SearchCriteria searchCriteria) {
@Override
public VXLong getXAccessAuditSearchCount(SearchCriteria searchCriteria) {
if (rangerBizUtil.getAuditDBType().equalsIgnoreCase("solr")) {
- return solrAccessAuditsService
- .getXAccessAuditSearchCount(searchCriteria);
+ return solrAccessAuditsService.getXAccessAuditSearchCount(searchCriteria);
} else {
return super.getXAccessAuditSearchCount(searchCriteria);
}
diff --git a/security-admin/src/main/java/org/apache/ranger/biz/XUserMgr.java b/security-admin/src/main/java/org/apache/ranger/biz/XUserMgr.java
index 700caff74c8..2413afbf8b3 100644
--- a/security-admin/src/main/java/org/apache/ranger/biz/XUserMgr.java
+++ b/security-admin/src/main/java/org/apache/ranger/biz/XUserMgr.java
@@ -20,7 +20,6 @@
package org.apache.ranger.biz;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
@@ -37,6 +36,7 @@
import org.apache.ranger.service.XGroupPermissionService;
import org.apache.ranger.service.XModuleDefService;
import org.apache.ranger.service.XPortalUserService;
+import org.apache.ranger.service.XResourceService;
import org.apache.ranger.service.XUserPermissionService;
import org.apache.ranger.view.VXGroupPermission;
import org.apache.ranger.view.VXModuleDef;
@@ -49,24 +49,31 @@
import org.apache.ranger.common.UserSessionBase;
import org.apache.ranger.db.RangerDaoManager;
import org.apache.ranger.db.XXGroupUserDao;
+import org.apache.ranger.entity.XXAuditMap;
import org.apache.ranger.entity.XXGroup;
+import org.apache.ranger.entity.XXPermMap;
import org.apache.ranger.entity.XXPortalUser;
-import org.apache.ranger.entity.XXPortalUserRole;
import org.apache.ranger.entity.XXTrxLog;
import org.apache.ranger.entity.XXUser;
import org.apache.ranger.service.XGroupService;
import org.apache.ranger.service.XUserService;
+import org.apache.ranger.view.VXAuditMapList;
import org.apache.ranger.view.VXGroup;
+import org.apache.ranger.view.VXGroupGroup;
import org.apache.ranger.view.VXGroupList;
import org.apache.ranger.view.VXGroupUser;
import org.apache.ranger.view.VXGroupUserList;
+import org.apache.ranger.view.VXLong;
+import org.apache.ranger.view.VXPermMapList;
import org.apache.ranger.view.VXPortalUser;
import org.apache.ranger.view.VXUser;
import org.apache.ranger.view.VXUserGroupInfo;
import org.apache.ranger.view.VXUserList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
+
import javax.servlet.http.HttpServletResponse;
+
import org.apache.ranger.view.VXResponse;
@Component
public class XUserMgr extends XUserMgrBase {
@@ -100,25 +107,14 @@ public class XUserMgr extends XUserMgrBase {
@Autowired
XPortalUserService xPortalUserService;
+
+ @Autowired
+ XResourceService xResourceService;
static final Logger logger = Logger.getLogger(XUserMgr.class);
public void deleteXGroup(Long id, boolean force) {
- UserSessionBase session = ContextUtil.getCurrentUserSession();
- if (session != null) {
- if (!session.isUserAdmin()) {
- throw restErrorUtil.create403RESTException("deletion of group"
- + " denied. LoggedInUser="
- + (session != null ? session.getXXPortalUser().getId()
- : "Not Logged In")
- + " ,isn't permitted to perform the action.");
- }
- }else{
- VXResponse vXResponse = new VXResponse();
- vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED);
- vXResponse.setMsgDesc("Bad Credentials");
- throw restErrorUtil.generateRESTException(vXResponse);
- }
+ checkAdminAccess();
if (force) {
SearchCriteria searchCriteria = new SearchCriteria();
searchCriteria.addParam("xGroupId", id);
@@ -139,21 +135,7 @@ public void deleteXGroup(Long id, boolean force) {
}
public void deleteXUser(Long id, boolean force) {
- UserSessionBase session = ContextUtil.getCurrentUserSession();
- if (session != null) {
- if (!session.isUserAdmin()) {
- throw restErrorUtil.create403RESTException("deletion of user"
- + " denied. LoggedInUser="
- + (session != null ? session.getXXPortalUser().getId()
- : "Not Logged In")
- + " ,isn't permitted to perform the action.");
- }
- }else{
- VXResponse vXResponse = new VXResponse();
- vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED);
- vXResponse.setMsgDesc("Bad Credentials");
- throw restErrorUtil.generateRESTException(vXResponse);
- }
+ checkAdminAccess();
if (force) {
SearchCriteria searchCriteria = new SearchCriteria();
searchCriteria.addParam("xUserId", id);
@@ -185,21 +167,7 @@ public VXUser getXUserByUserName(String userName) {
}
public VXUser createXUser(VXUser vXUser) {
- UserSessionBase session = ContextUtil.getCurrentUserSession();
- if (session != null) {
- if (!session.isUserAdmin()) {
- throw restErrorUtil.create403RESTException("creation of user"
- + " denied. LoggedInUser="
- + (session != null ? session.getXXPortalUser().getId()
- : "Not Logged In")
- + " ,isn't permitted to perform the action.");
- }
- }else{
- VXResponse vXResponse = new VXResponse();
- vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED);
- vXResponse.setMsgDesc("Bad Credentials");
- throw restErrorUtil.generateRESTException(vXResponse);
- }
+ checkAdminAccess();
String userName = vXUser.getName();
if (userName == null || userName.isEmpty()) {
throw restErrorUtil.createRESTException("Please provide a valid "
@@ -256,7 +224,6 @@ public VXUser createXUser(VXUser vXUser) {
}
// Assigning Permission
- @SuppressWarnings("unused")
public void assignPermissionToUser(VXPortalUser vXPortalUser,
boolean isCreate) {
HashMap moduleNameId = getModelNames();
@@ -336,7 +303,6 @@ private void insertMappingUserPermisson(Long userId, Long moduleId,
}
- @SuppressWarnings("unused")
public HashMap getModelNames() {
List xxModuleDefs = daoManager.getXXModuleDef()
.findModuleNamesWithIds();
@@ -369,6 +335,10 @@ private VXGroupUser createXGroupUser(Long userId, Long groupId) {
}
public VXUser updateXUser(VXUser vXUser) {
+ if (vXUser == null || vXUser.getName() == null || vXUser.getName().trim().isEmpty()) {
+ throw restErrorUtil.createRESTException("Please provide a valid " + "username.", MessageEnums.INVALID_INPUT_DATA);
+ }
+ checkAccess(vXUser.getName());
VXPortalUser oldUserProfile = userMgr.getUserProfileByLoginId(vXUser
.getName());
VXPortalUser vXPortalUser = new VXPortalUser();
@@ -522,21 +492,7 @@ public VXUser updateXUser(VXUser vXUser) {
public VXUserGroupInfo createXUserGroupFromMap(
VXUserGroupInfo vXUserGroupInfo) {
- UserSessionBase session = ContextUtil.getCurrentUserSession();
- if (session != null) {
- if (!session.isUserAdmin()) {
- throw restErrorUtil.create403RESTException("User group "
- + "creation denied. LoggedInUser="
- + (session != null ? session.getXXPortalUser().getId()
- : "Not Logged In")
- + " ,isn't permitted to perform the action.");
- }
- }else{
- VXResponse vXResponse = new VXResponse();
- vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED);
- vXResponse.setMsgDesc("Bad Credentials");
- throw restErrorUtil.generateRESTException(vXResponse);
- }
+ checkAdminAccess();
VXUserGroupInfo vxUGInfo = new VXUserGroupInfo();
VXUser vXUser = vXUserGroupInfo.getXuserInfo();
@@ -563,41 +519,12 @@ public VXUserGroupInfo createXUserGroupFromMap(
}
public VXUser createXUserWithOutLogin(VXUser vXUser) {
- UserSessionBase session = ContextUtil.getCurrentUserSession();
- if (session != null) {
- if (!session.isUserAdmin()) {
- throw restErrorUtil.create403RESTException("creation of user"
- + " denied. LoggedInUser="
- + (session != null ? session.getXXPortalUser().getId()
- : "Not Logged In")
- + " ,isn't permitted to perform the action.");
- }
- }else{
- VXResponse vXResponse = new VXResponse();
- vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED);
- vXResponse.setMsgDesc("Bad Credentials");
- throw restErrorUtil.generateRESTException(vXResponse);
- }
+ checkAdminAccess();
return xUserService.createXUserWithOutLogin(vXUser);
}
public VXGroup createXGroup(VXGroup vXGroup) {
- UserSessionBase session = ContextUtil.getCurrentUserSession();
- if (session != null) {
- if (!session.isUserAdmin()) {
- throw restErrorUtil.create403RESTException("creation of group"
- + " denied. LoggedInUser="
- + (session != null ? session.getXXPortalUser().getId()
- : "Not Logged In")
- + " ,isn't permitted to perform the action.");
- }
- }else{
- VXResponse vXResponse = new VXResponse();
- vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED);
- vXResponse.setMsgDesc("Bad Credentials");
- throw restErrorUtil.generateRESTException(vXResponse);
- }
- // FIXME Just a hack
+ checkAdminAccess();
if (vXGroup.getDescription() == null) {
vXGroup.setDescription(vXGroup.getName());
}
@@ -610,40 +537,12 @@ public VXGroup createXGroup(VXGroup vXGroup) {
}
public VXGroup createXGroupWithoutLogin(VXGroup vXGroup) {
- UserSessionBase session = ContextUtil.getCurrentUserSession();
- if (session != null) {
- if (!session.isUserAdmin()) {
- throw restErrorUtil.create403RESTException("creation of group"
- + " denied. LoggedInUser="
- + (session != null ? session.getXXPortalUser().getId()
- : "Not Logged In")
- + " ,isn't permitted to perform the action.");
- }
- }else{
- VXResponse vXResponse = new VXResponse();
- vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED);
- vXResponse.setMsgDesc("Bad Credentials");
- throw restErrorUtil.generateRESTException(vXResponse);
- }
+ checkAdminAccess();
return xGroupService.createXGroupWithOutLogin(vXGroup);
}
public VXGroupUser createXGroupUser(VXGroupUser vXGroupUser) {
- UserSessionBase session = ContextUtil.getCurrentUserSession();
- if (session != null) {
- if (!session.isUserAdmin()) {
- throw restErrorUtil.create403RESTException("creation of group"
- + " denied. LoggedInUser="
- + (session != null ? session.getXXPortalUser().getId()
- : "Not Logged In")
- + " ,isn't permitted to perform the action.");
- }
- }else{
- VXResponse vXResponse = new VXResponse();
- vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED);
- vXResponse.setMsgDesc("Bad Credentials");
- throw restErrorUtil.generateRESTException(vXResponse);
- }
+ checkAdminAccess();
vXGroupUser = xGroupUserService
.createXGroupUserWithOutLogin(vXGroupUser);
return vXGroupUser;
@@ -690,21 +589,7 @@ public VXGroup getXGroup(Long id) {
*/
public void deleteXGroupAndXUser(String groupName, String userName) {
- UserSessionBase session = ContextUtil.getCurrentUserSession();
- if (session != null) {
- if (!session.isUserAdmin()) {
- throw restErrorUtil.create403RESTException("User "
- + "deletion denied. LoggedInUser="
- + (session != null ? session.getXXPortalUser().getId()
- : "Not Logged In")
- + " ,isn't permitted to perform the action.");
- }
- }else{
- VXResponse vXResponse = new VXResponse();
- vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED);
- vXResponse.setMsgDesc("Bad Credentials");
- throw restErrorUtil.generateRESTException(vXResponse);
- }
+ checkAdminAccess();
VXGroup vxGroup = xGroupService.getGroupByGroupName(groupName);
VXUser vxUser = xUserService.getXUserByUserName(userName);
SearchCriteria searchCriteria = new SearchCriteria();
@@ -807,6 +692,7 @@ private void setUserDesc(VXUser vXUser) {
@Override
public VXGroup updateXGroup(VXGroup vXGroup) {
+ checkAdminAccess();
XXGroup xGroup = daoManager.getXXGroup().getById(vXGroup.getId());
List trxLogList = xGroupService.getTransactionLog(vXGroup,
xGroup, "update");
@@ -814,8 +700,77 @@ public VXGroup updateXGroup(VXGroup vXGroup) {
vXGroup = (VXGroup) xGroupService.updateResource(vXGroup);
return vXGroup;
}
+ public VXGroupUser updateXGroupUser(VXGroupUser vXGroupUser) {
+ checkAdminAccess();
+ return super.updateXGroupUser(vXGroupUser);
+ }
+
+ public void deleteXGroupUser(Long id, boolean force) {
+ checkAdminAccess();
+ super.deleteXGroupUser(id, force);
+ }
+
+ public VXGroupGroup createXGroupGroup(VXGroupGroup vXGroupGroup){
+ checkAdminAccess();
+ return super.createXGroupGroup(vXGroupGroup);
+ }
+
+ public VXGroupGroup updateXGroupGroup(VXGroupGroup vXGroupGroup) {
+ checkAdminAccess();
+ return super.updateXGroupGroup(vXGroupGroup);
+ }
+
+ public void deleteXGroupGroup(Long id, boolean force) {
+ checkAdminAccess();
+ super.deleteXGroupGroup(id, force);
+ }
+
+ public void deleteXPermMap(Long id, boolean force) {
+ if (force) {
+ XXPermMap xPermMap = daoManager.getXXPermMap().getById(id);
+ if (xPermMap != null) {
+ if (xResourceService.readResource(xPermMap.getResourceId()) == null) {
+ throw restErrorUtil.createRESTException("Invalid Input Data - No resource found with Id: " + xPermMap.getResourceId(), MessageEnums.INVALID_INPUT_DATA);
+ }
+ }
+
+ xPermMapService.deleteResource(id);
+ } else {
+ throw restErrorUtil.createRESTException("serverMsg.modelMgrBaseDeleteModel", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
+ }
+ }
+
+ public VXLong getXPermMapSearchCount(SearchCriteria searchCriteria) {
+ VXPermMapList permMapList = xPermMapService.searchXPermMaps(searchCriteria);
+ VXLong vXLong = new VXLong();
+ vXLong.setValue(permMapList.getListSize());
+ return vXLong;
+ }
+
+ public void deleteXAuditMap(Long id, boolean force) {
+ if (force) {
+ XXAuditMap xAuditMap = daoManager.getXXAuditMap().getById(id);
+ if (xAuditMap != null) {
+ if (xResourceService.readResource(xAuditMap.getResourceId()) == null) {
+ throw restErrorUtil.createRESTException("Invalid Input Data - No resource found with Id: " + xAuditMap.getResourceId(), MessageEnums.INVALID_INPUT_DATA);
+ }
+ }
+
+ xAuditMapService.deleteResource(id);
+ } else {
+ throw restErrorUtil.createRESTException("serverMsg.modelMgrBaseDeleteModel", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
+ }
+ }
+
+ public VXLong getXAuditMapSearchCount(SearchCriteria searchCriteria) {
+ VXAuditMapList auditMapList = xAuditMapService.searchXAuditMaps(searchCriteria);
+ VXLong vXLong = new VXLong();
+ vXLong.setValue(auditMapList.getListSize());
+ return vXLong;
+ }
public void modifyUserVisibility(HashMap visibilityMap) {
+ checkAdminAccess();
Set> entries = visibilityMap.entrySet();
for (Map.Entry entry : entries) {
XXUser xUser = daoManager.getXXUser().getById(entry.getKey());
@@ -826,6 +781,7 @@ public void modifyUserVisibility(HashMap visibilityMap) {
}
public void modifyGroupsVisibility(HashMap groupVisibilityMap) {
+ checkAdminAccess();
Set> entries = groupVisibilityMap.entrySet();
for (Map.Entry entry : entries) {
XXGroup xGroup = daoManager.getXXGroup().getById(entry.getKey());
@@ -878,6 +834,7 @@ public void modifyGroupsVisibility(HashMap groupVisibilityMap) {
// Module permissions
public VXModuleDef createXModuleDefPermission(VXModuleDef vXModuleDef) {
+ checkAdminAccess();
return xModuleDefService.createResource(vXModuleDef);
}
@@ -886,6 +843,7 @@ public VXModuleDef getXModuleDefPermission(Long id) {
}
public VXModuleDef updateXModuleDefPermission(VXModuleDef vXModuleDef) {
+ checkAdminAccess();
List groupPermListNew = vXModuleDef
.getGroupPermList();
List userPermListNew = vXModuleDef.getUserPermList();
@@ -970,12 +928,14 @@ public VXModuleDef updateXModuleDefPermission(VXModuleDef vXModuleDef) {
}
public void deleteXModuleDefPermission(Long id, boolean force) {
+ checkAdminAccess();
xModuleDefService.deleteResource(id);
}
// User permission
public VXUserPermission createXUserPermission(
VXUserPermission vXUserPermission) {
+ checkAdminAccess();
return xUserPermissionService.createResource(vXUserPermission);
}
@@ -985,17 +945,19 @@ public VXUserPermission getXUserPermission(Long id) {
public VXUserPermission updateXUserPermission(
VXUserPermission vXUserPermission) {
-
+ checkAdminAccess();
return xUserPermissionService.updateResource(vXUserPermission);
}
public void deleteXUserPermission(Long id, boolean force) {
+ checkAdminAccess();
xUserPermissionService.deleteResource(id);
}
// Group permission
public VXGroupPermission createXGroupPermission(
VXGroupPermission vXGroupPermission) {
+ checkAdminAccess();
return xGroupPermissionService.createResource(vXGroupPermission);
}
@@ -1005,14 +967,17 @@ public VXGroupPermission getXGroupPermission(Long id) {
public VXGroupPermission updateXGroupPermission(
VXGroupPermission vXGroupPermission) {
+ checkAdminAccess();
return xGroupPermissionService.updateResource(vXGroupPermission);
}
public void deleteXGroupPermission(Long id, boolean force) {
+ checkAdminAccess();
xGroupPermissionService.deleteResource(id);
}
public void modifyUserActiveStatus(HashMap statusMap) {
+ checkAdminAccess();
UserSessionBase session = ContextUtil.getCurrentUserSession();
String currentUser=null;
if(session!=null){
@@ -1040,4 +1005,35 @@ public void modifyUserActiveStatus(HashMap statusMap) {
}
}
}
+
+ public void checkAdminAccess() {
+ UserSessionBase session = ContextUtil.getCurrentUserSession();
+ if (session != null) {
+ if (!session.isUserAdmin()) {
+ throw restErrorUtil.create403RESTException("Operation" + " denied. LoggedInUser=" + (session != null ? session.getXXPortalUser().getId() : "Not Logged In")
+ + " ,isn't permitted to perform the action.");
+ }
+ } else {
+ VXResponse vXResponse = new VXResponse();
+ vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED);
+ vXResponse.setMsgDesc("Bad Credentials");
+ throw restErrorUtil.generateRESTException(vXResponse);
+ }
+ }
+
+ public void checkAccess(String loginID) {
+ UserSessionBase session = ContextUtil.getCurrentUserSession();
+ if (session != null) {
+ if (!session.isUserAdmin() && !session.isKeyAdmin() && !session.getLoginId().equalsIgnoreCase(loginID)) {
+ throw restErrorUtil.create403RESTException("Operation" + " denied. LoggedInUser=" + (session != null ? session.getXXPortalUser().getId() : "Not Logged In")
+ + " ,isn't permitted to perform the action.");
+ }
+ } else {
+ VXResponse vXResponse = new VXResponse();
+ vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED);
+ vXResponse.setMsgDesc("Bad Credentials");
+ throw restErrorUtil.generateRESTException(vXResponse);
+ }
+ }
+
}
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXGroupUserDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXGroupUserDao.java
index 9f5abfb0cd4..104e1884234 100644
--- a/security-admin/src/main/java/org/apache/ranger/db/XXGroupUserDao.java
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXGroupUserDao.java
@@ -60,4 +60,25 @@ public List findByUserId(Long userId) {
}
return null;
}
+
+ /**
+ * @param xUserId
+ * -- Id of X_USER table
+ * @return
+ */
+ @SuppressWarnings("unchecked")
+ public List findGroupIdListByUserId(Long xUserId) {
+ if (xUserId != null) {
+ try {
+ return getEntityManager().createNamedQuery("XXGroupUser.findGroupIdListByUserId").setParameter("xUserId", xUserId).getResultList();
+ } catch (NoResultException e) {
+ logger.debug(e.getMessage());
+ }
+ } else {
+ logger.debug("UserId not provided.");
+ return new ArrayList();
+ }
+ return null;
+ }
+
}
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXModuleDefDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXModuleDefDao.java
index 611eaf869a0..fa2b3d99b75 100644
--- a/security-admin/src/main/java/org/apache/ranger/db/XXModuleDefDao.java
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXModuleDefDao.java
@@ -22,7 +22,9 @@
import javax.persistence.NoResultException;
+import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
+import org.apache.ranger.common.RangerCommonEnums;
import org.apache.ranger.common.db.BaseDao;
import org.apache.ranger.entity.XXModuleDef;
@@ -115,4 +117,40 @@ public List findModuleURLOfPemittedModules(Long userId) {
return null;
}
}
+
+ @SuppressWarnings("unchecked")
+ public List findAccessibleModulesByGroupIdList(List grpIdList) {
+ if (CollectionUtils.isEmpty(grpIdList)) {
+ return new ArrayList();
+ }
+ try {
+ return getEntityManager().createNamedQuery("XXModuleDef.findAccessibleModulesByGroupId").setParameter("grpIdList", grpIdList)
+ .setParameter("isAllowed", RangerCommonEnums.ACCESS_RESULT_ALLOWED).getResultList();
+ } catch (NoResultException e) {
+ return new ArrayList();
+ }
+ }
+
+ /**
+ * @param portalUserId
+ * @param xUserId
+ * @return This function will return all the modules accessible for particular user, considering all the groups as well in which that user belongs
+ */
+ @SuppressWarnings("unchecked")
+ public List findAccessibleModulesByUserId(Long portalUserId, Long xUserId) {
+ if (portalUserId == null || xUserId == null) {
+ return new ArrayList();
+ }
+ try {
+
+ List userPermList = getEntityManager().createNamedQuery("XXModuleDef.findAllAccessibleModulesByUserId").setParameter("portalUserId", portalUserId)
+ .setParameter("xUserId", xUserId).setParameter("isAllowed", RangerCommonEnums.ACCESS_RESULT_ALLOWED).getResultList();
+
+ return userPermList;
+
+ } catch (NoResultException e) {
+ return new ArrayList();
+ }
+ }
+
}
diff --git a/security-admin/src/main/java/org/apache/ranger/rest/AssetREST.java b/security-admin/src/main/java/org/apache/ranger/rest/AssetREST.java
index e5de160186a..19dbfaacbe6 100644
--- a/security-admin/src/main/java/org/apache/ranger/rest/AssetREST.java
+++ b/security-admin/src/main/java/org/apache/ranger/rest/AssetREST.java
@@ -56,6 +56,7 @@
import org.apache.ranger.plugin.util.GrantRevokeRequest;
import org.apache.ranger.plugin.util.SearchFilter;
import org.apache.ranger.plugin.util.ServicePolicies;
+import org.apache.ranger.security.context.RangerAPIList;
import org.apache.ranger.service.XAccessAuditService;
import org.apache.ranger.service.XAgentService;
import org.apache.ranger.service.XAssetService;
@@ -137,6 +138,7 @@ public class AssetREST {
@GET
@Path("/assets/{id}")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_ASSET + "\")")
public VXAsset getXAsset(@PathParam("id") Long id) {
if(logger.isDebugEnabled()) {
logger.debug("==> AssetREST.getXAsset(" + id + ")");
@@ -156,6 +158,7 @@ public VXAsset getXAsset(@PathParam("id") Long id) {
@POST
@Path("/assets")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.CREATE_X_ASSET + "\")")
public VXAsset createXAsset(VXAsset vXAsset) {
if(logger.isDebugEnabled()) {
logger.debug("==> AssetREST.createXAsset(" + vXAsset + ")");
@@ -177,6 +180,7 @@ public VXAsset createXAsset(VXAsset vXAsset) {
@PUT
@Path("/assets/{id}")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.UPDATE_X_ASSET + "\")")
public VXAsset updateXAsset(VXAsset vXAsset) {
if(logger.isDebugEnabled()) {
logger.debug("==> AssetREST.updateXAsset(" + vXAsset + ")");
@@ -197,8 +201,8 @@ public VXAsset updateXAsset(VXAsset vXAsset) {
@DELETE
@Path("/assets/{id}")
- @PreAuthorize("hasRole('ROLE_SYS_ADMIN')")
@RangerAnnotationClassName(class_name = VXAsset.class)
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.DELETE_X_ASSET + "\")")
public void deleteXAsset(@PathParam("id") Long id,
@Context HttpServletRequest request) {
if(logger.isDebugEnabled()) {
@@ -215,6 +219,7 @@ public void deleteXAsset(@PathParam("id") Long id,
@POST
@Path("/assets/testConfig")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.TEST_CONFIG + "\")")
public VXResponse testConfig(VXAsset vXAsset) {
if(logger.isDebugEnabled()) {
logger.debug("==> AssetREST.testConfig(" + vXAsset + ")");
@@ -234,6 +239,7 @@ public VXResponse testConfig(VXAsset vXAsset) {
@GET
@Path("/assets")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_X_ASSETS + "\")")
public VXAssetList searchXAssets(@Context HttpServletRequest request) {
if(logger.isDebugEnabled()) {
logger.debug("==> AssetREST.searchXAssets()");
@@ -269,6 +275,7 @@ public VXAssetList searchXAssets(@Context HttpServletRequest request) {
@GET
@Path("/assets/count")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.COUNT_X_ASSETS + "\")")
public VXLong countXAssets(@Context HttpServletRequest request) {
if(logger.isDebugEnabled()) {
logger.debug("==> AssetREST.countXAssets()");
@@ -547,8 +554,10 @@ public String getResourceJSON(@Context HttpServletRequest request,
@GET
@Path("/exportAudit")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_X_POLICY_EXPORT_AUDITS + "\")")
public VXPolicyExportAuditList searchXPolicyExportAudits(
@Context HttpServletRequest request) {
+
SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
request, xPolicyExportAudits.sortFields);
searchUtil.extractString(request, searchCriteria, "agentId",
@@ -572,7 +581,9 @@ public VXPolicyExportAuditList searchXPolicyExportAudits(
@GET
@Path("/report")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_REPORT_LOGS + "\")")
public VXTrxLogList getReportLogs(@Context HttpServletRequest request){
+
SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
request, xTrxLogService.sortFields);
searchUtil.extractInt(request, searchCriteria, "objectClassType", "Class type for report.");
@@ -592,6 +603,7 @@ public VXTrxLogList getReportLogs(@Context HttpServletRequest request){
@GET
@Path("/report/{transactionId}")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_TRANSACTION_REPORT + "\")")
public VXTrxLogList getTransactionReport(@Context HttpServletRequest request,
@PathParam("transactionId") String transactionId){
return assetMgr.getTransactionReport(transactionId);
@@ -600,6 +612,7 @@ public VXTrxLogList getTransactionReport(@Context HttpServletRequest request,
@GET
@Path("/accessAudit")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_ACCESS_LOGS + "\")")
public VXAccessAuditList getAccessLogs(@Context HttpServletRequest request){
SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
request, xAccessAuditService.sortFields);
diff --git a/security-admin/src/main/java/org/apache/ranger/rest/PublicAPIsv2.java b/security-admin/src/main/java/org/apache/ranger/rest/PublicAPIsv2.java
index 059f787290f..2c30daa149a 100644
--- a/security-admin/src/main/java/org/apache/ranger/rest/PublicAPIsv2.java
+++ b/security-admin/src/main/java/org/apache/ranger/rest/PublicAPIsv2.java
@@ -312,7 +312,7 @@ public RangerPolicy getPolicyByName(@PathParam("servicename") String serviceName
@Produces({ "application/json", "application/xml" })
public List searchPolicies(@PathParam("servicename") String serviceName,
@Context HttpServletRequest request) {
- return serviceREST.getServicePolicies(serviceName, request).getPolicies();
+ return serviceREST.getServicePoliciesByName(serviceName, request).getPolicies();
}
@POST
diff --git a/security-admin/src/main/java/org/apache/ranger/rest/ServiceREST.java b/security-admin/src/main/java/org/apache/ranger/rest/ServiceREST.java
index 3d2e8b08e36..f523d670019 100644
--- a/security-admin/src/main/java/org/apache/ranger/rest/ServiceREST.java
+++ b/security-admin/src/main/java/org/apache/ranger/rest/ServiceREST.java
@@ -49,6 +49,7 @@
import org.apache.ranger.biz.ServiceDBStore;
import org.apache.ranger.biz.ServiceMgr;
import org.apache.ranger.biz.XUserMgr;
+import org.apache.ranger.common.AppConstants;
import org.apache.ranger.common.GUIDUtil;
import org.apache.ranger.common.MessageEnums;
import org.apache.ranger.common.RESTErrorUtil;
@@ -81,6 +82,8 @@
import org.apache.ranger.plugin.util.GrantRevokeRequest;
import org.apache.ranger.plugin.util.SearchFilter;
import org.apache.ranger.plugin.util.ServicePolicies;
+import org.apache.ranger.security.context.RangerAPIList;
+import org.apache.ranger.security.context.RangerPreAuthSecurityHandler;
import org.apache.ranger.service.RangerPolicyService;
import org.apache.ranger.service.RangerServiceDefService;
import org.apache.ranger.service.RangerServiceService;
@@ -151,11 +154,10 @@ public class ServiceREST {
public ServiceREST() {
}
-
@POST
@Path("/definitions")
@Produces({ "application/json", "application/xml" })
- @PreAuthorize("hasRole('ROLE_SYS_ADMIN')")
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.CREATE_SERVICE_DEF + "\")")
public RangerServiceDef createServiceDef(RangerServiceDef serviceDef) {
if(LOG.isDebugEnabled()) {
LOG.debug("==> ServiceREST.createServiceDef(" + serviceDef + ")");
@@ -189,7 +191,7 @@ public RangerServiceDef createServiceDef(RangerServiceDef serviceDef) {
@PUT
@Path("/definitions/{id}")
@Produces({ "application/json", "application/xml" })
- @PreAuthorize("hasRole('ROLE_SYS_ADMIN')")
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.UPDATE_SERVICE_DEF + "\")")
public RangerServiceDef updateServiceDef(RangerServiceDef serviceDef) {
if(LOG.isDebugEnabled()) {
LOG.debug("==> ServiceREST.updateServiceDef(" + serviceDef + ")");
@@ -223,7 +225,7 @@ public RangerServiceDef updateServiceDef(RangerServiceDef serviceDef) {
@DELETE
@Path("/definitions/{id}")
@Produces({ "application/json", "application/xml" })
- @PreAuthorize("hasRole('ROLE_SYS_ADMIN')")
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.DELETE_SERVICE_DEF + "\")")
public void deleteServiceDef(@PathParam("id") Long id, @Context HttpServletRequest request) {
if(LOG.isDebugEnabled()) {
LOG.debug("==> ServiceREST.deleteServiceDef(" + id + ")");
@@ -260,6 +262,7 @@ public void deleteServiceDef(@PathParam("id") Long id, @Context HttpServletReque
@GET
@Path("/definitions/{id}")
@Produces({ "application/json", "application/xml" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_SERVICE_DEF + "\")")
public RangerServiceDef getServiceDef(@PathParam("id") Long id) {
if(LOG.isDebugEnabled()) {
LOG.debug("==> ServiceREST.getServiceDef(" + id + ")");
@@ -298,6 +301,7 @@ public RangerServiceDef getServiceDef(@PathParam("id") Long id) {
@GET
@Path("/definitions/name/{name}")
@Produces({ "application/json", "application/xml" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_SERVICE_DEF_BY_NAME + "\")")
public RangerServiceDef getServiceDefByName(@PathParam("name") String name) {
if(LOG.isDebugEnabled()) {
LOG.debug("==> ServiceREST.getServiceDefByName(" + name + ")");
@@ -338,6 +342,7 @@ public RangerServiceDef getServiceDefByName(@PathParam("name") String name) {
@GET
@Path("/definitions")
@Produces({ "application/json", "application/xml" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_SERVICE_DEFS + "\")")
public RangerServiceDefList getServiceDefs(@Context HttpServletRequest request) {
if (LOG.isDebugEnabled()) {
LOG.debug("==> ServiceREST.getServiceDefs()");
@@ -366,7 +371,7 @@ public RangerServiceDefList getServiceDefs(@Context HttpServletRequest request)
@POST
@Path("/services")
@Produces({ "application/json", "application/xml" })
- @PreAuthorize("hasRole('ROLE_SYS_ADMIN')")
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.CREATE_SERVICE + "\")")
public RangerService createService(RangerService service) {
if(LOG.isDebugEnabled()) {
LOG.debug("==> ServiceREST.createService(" + service + ")");
@@ -405,7 +410,7 @@ public RangerService createService(RangerService service) {
@PUT
@Path("/services/{id}")
@Produces({ "application/json", "application/xml" })
- @PreAuthorize("hasRole('ROLE_SYS_ADMIN')")
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.UPDATE_SERVICE + "\")")
public RangerService updateService(RangerService service) {
if(LOG.isDebugEnabled()) {
LOG.debug("==> ServiceREST.updateService(): " + service);
@@ -444,7 +449,7 @@ public RangerService updateService(RangerService service) {
@DELETE
@Path("/services/{id}")
@Produces({ "application/json", "application/xml" })
- @PreAuthorize("hasRole('ROLE_SYS_ADMIN')")
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.DELETE_SERVICE + "\")")
public void deleteService(@PathParam("id") Long id) {
if(LOG.isDebugEnabled()) {
LOG.debug("==> ServiceREST.deleteService(" + id + ")");
@@ -480,6 +485,7 @@ public void deleteService(@PathParam("id") Long id) {
@GET
@Path("/services/{id}")
@Produces({ "application/json", "application/xml" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_SERVICE + "\")")
public RangerService getService(@PathParam("id") Long id) {
if(LOG.isDebugEnabled()) {
LOG.debug("==> ServiceREST.getService(" + id + ")");
@@ -511,6 +517,7 @@ public RangerService getService(@PathParam("id") Long id) {
@GET
@Path("/services/name/{name}")
@Produces({ "application/json", "application/xml" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_SERVICE_BY_NAME + "\")")
public RangerService getServiceByName(@PathParam("name") String name) {
if(LOG.isDebugEnabled()) {
LOG.debug("==> ServiceREST.getServiceByName(" + name + ")");
@@ -542,6 +549,7 @@ public RangerService getServiceByName(@PathParam("name") String name) {
@GET
@Path("/services")
@Produces({ "application/json", "application/xml" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_SERVICES + "\")")
public RangerServiceList getServices(@Context HttpServletRequest request) {
if (LOG.isDebugEnabled()) {
LOG.debug("==> ServiceREST.getServices()");
@@ -595,6 +603,7 @@ public List getServices(SearchFilter filter) {
@GET
@Path("/services/count")
@Produces({ "application/json", "application/xml" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.COUNT_SERVICES + "\")")
public Long countServices(@Context HttpServletRequest request) {
if(LOG.isDebugEnabled()) {
LOG.debug("==> ServiceREST.countServices():");
@@ -624,6 +633,7 @@ public Long countServices(@Context HttpServletRequest request) {
@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 + ")");
@@ -651,6 +661,7 @@ public VXResponse validateConfig(RangerService service) {
@POST
@Path("/services/lookupResource/{serviceName}")
@Produces({ "application/json", "application/xml" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.LOOKUP_RESOURCE + "\")")
public List lookupResource(@PathParam("serviceName") String serviceName, ResourceLookupContext context) {
if(LOG.isDebugEnabled()) {
LOG.debug("==> ServiceREST.lookupResource(" + serviceName + ")");
@@ -1196,7 +1207,7 @@ public RangerPolicyList getServicePolicies(@PathParam("id") Long serviceId,
@GET
@Path("/policies/service/name/{name}")
@Produces({ "application/json", "application/xml" })
- public RangerPolicyList getServicePolicies(@PathParam("name") String serviceName,
+ public RangerPolicyList getServicePoliciesByName(@PathParam("name") String serviceName,
@Context HttpServletRequest request) {
if (LOG.isDebugEnabled()) {
LOG.debug("==> ServiceREST.getServicePolicies(" + serviceName + ")");
@@ -1464,6 +1475,7 @@ private boolean removeUsersAndGroupsFromPolicy(RangerPolicy policy, Set
@GET
@Path("/policies/eventTime")
@Produces({ "application/json", "application/xml" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_POLICY_FROM_EVENT_TIME + "\")")
public RangerPolicy getPolicyFromEventTime(@Context HttpServletRequest request) {
if (LOG.isDebugEnabled()) {
LOG.debug("==> ServiceREST.getPolicyFromEventTime()");
@@ -1490,6 +1502,7 @@ public RangerPolicy getPolicyFromEventTime(@Context HttpServletRequest request)
@GET
@Path("/policy/{policyId}/versionList")
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_POLICY_VERSION_LIST + "\")")
public VXString getPolicyVersionList(@PathParam("policyId") Long policyId) {
return svcStore.getPolicyVersionList(policyId);
}
@@ -1497,6 +1510,7 @@ public VXString getPolicyVersionList(@PathParam("policyId") Long policyId) {
@GET
@Path("/policy/{policyId}/version/{versionNo}")
@Produces({ "application/json", "application/xml" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_POLICY_FOR_VERSION_NO + "\")")
public RangerPolicy getPolicyForVersionNumber(@PathParam("policyId") Long policyId,
@PathParam("versionNo") int versionNo) {
return svcStore.getPolicyForVersionNumber(policyId, versionNo);
diff --git a/security-admin/src/main/java/org/apache/ranger/rest/UserREST.java b/security-admin/src/main/java/org/apache/ranger/rest/UserREST.java
index a9d00595b49..4c5e890fe4b 100644
--- a/security-admin/src/main/java/org/apache/ranger/rest/UserREST.java
+++ b/security-admin/src/main/java/org/apache/ranger/rest/UserREST.java
@@ -45,6 +45,8 @@
import org.apache.ranger.common.annotation.RangerAnnotationRestAPI;
import org.apache.ranger.db.RangerDaoManager;
import org.apache.ranger.entity.XXPortalUser;
+import org.apache.ranger.security.context.RangerAPIList;
+import org.apache.ranger.security.context.RangerPreAuthSecurityHandler;
import org.apache.ranger.util.RangerRestUtil;
import org.apache.ranger.view.VXPasswordChange;
import org.apache.ranger.view.VXPortalUser;
@@ -99,7 +101,7 @@ public class UserREST {
*/
@GET
@Produces({ "application/xml", "application/json" })
- @PreAuthorize("hasRole('ROLE_SYS_ADMIN')")
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_USERS + "\")")
public VXPortalUserList searchUsers(@Context HttpServletRequest request) {
String[] approvedSortByParams = new String[] { "requestDate",
"approvedDate", "activationDate", "emailAddress", "firstName",
@@ -150,6 +152,7 @@ public VXPortalUserList searchUsers(@Context HttpServletRequest request) {
@GET
@Path("{userId}")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_USER_PROFILE_FOR_USER + "\")")
public VXPortalUser getUserProfileForUser(@PathParam("userId") Long userId) {
try {
VXPortalUser userProfile = userManager.getUserProfile(userId);
@@ -171,7 +174,7 @@ public VXPortalUser getUserProfileForUser(@PathParam("userId") Long userId) {
@POST
@Consumes({ "application/json", "application/xml" })
@Produces({ "application/xml", "application/json" })
- @PreAuthorize("hasRole('ROLE_SYS_ADMIN')")
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.CREATE + "\")")
public VXPortalUser create(VXPortalUser userProfile,
@Context HttpServletRequest servletRequest) {
logger.info("create:" + userProfile.getEmailAddress());
@@ -184,7 +187,7 @@ public VXPortalUser create(VXPortalUser userProfile,
@Path("/default")
@Consumes({ "application/json", "application/xml" })
@Produces({ "application/xml", "application/json" })
- @PreAuthorize("hasRole('ROLE_SYS_ADMIN')")
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.CREATE_DEFAULT_ACCOUNT_USER + "\")")
public VXPortalUser createDefaultAccountUser(VXPortalUser userProfile,
@Context HttpServletRequest servletRequest) {
VXPortalUser vxPortalUser;
@@ -201,6 +204,7 @@ public VXPortalUser createDefaultAccountUser(VXPortalUser userProfile,
@Consumes({ "application/json", "application/xml" })
@Produces({ "application/xml", "application/json" })
@RangerAnnotationRestAPI(updates_classes = "VUserProfile")
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.UPDATE + "\")")
public VXPortalUser update(VXPortalUser userProfile,
@Context HttpServletRequest servletRequest) {
logger.info("update:" + userProfile.getEmailAddress());
@@ -222,6 +226,7 @@ public VXPortalUser update(VXPortalUser userProfile,
@PUT
@Path("/{userId}/roles")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SET_USER_ROLES + "\")")
public VXResponse setUserRoles(@PathParam("userId") Long userId,
VXStringList roleList) {
userManager.checkAccess(userId);
@@ -240,7 +245,7 @@ public VXResponse setUserRoles(@PathParam("userId") Long userId,
@POST
@Path("{userId}/deactivate")
@Produces({ "application/xml", "application/json" })
- @PreAuthorize("hasRole('ROLE_SYS_ADMIN')")
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.DEACTIVATE_USER + "\")")
@RangerAnnotationClassName(class_name = VXPortalUser.class)
public VXPortalUser deactivateUser(@PathParam("userId") Long userId) {
XXPortalUser gjUser = daoManager.getXXPortalUser().getById(userId);
diff --git a/security-admin/src/main/java/org/apache/ranger/rest/XAuditREST.java b/security-admin/src/main/java/org/apache/ranger/rest/XAuditREST.java
index 531f395032c..cbe486b7646 100644
--- a/security-admin/src/main/java/org/apache/ranger/rest/XAuditREST.java
+++ b/security-admin/src/main/java/org/apache/ranger/rest/XAuditREST.java
@@ -35,6 +35,7 @@
import org.apache.ranger.common.SearchUtil;
import org.apache.ranger.common.annotation.RangerAnnotationClassName;
import org.apache.ranger.common.annotation.RangerAnnotationJSMgrName;
+import org.apache.ranger.security.context.RangerAPIList;
import org.apache.ranger.service.XAccessAuditService;
import org.apache.ranger.service.XTrxLogService;
import org.apache.ranger.view.VXAccessAuditList;
@@ -71,6 +72,7 @@ public class XAuditREST {
@GET
@Path("/trx_log/{id}")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_TRX_LOG + "\")")
public VXTrxLog getXTrxLog(
@PathParam("id") Long id) {
return xAuditMgr.getXTrxLog(id);
@@ -79,6 +81,7 @@ public VXTrxLog getXTrxLog(
@POST
@Path("/trx_log")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.CREATE_X_TRX_LOG + "\")")
public VXTrxLog createXTrxLog(VXTrxLog vXTrxLog) {
return xAuditMgr.createXTrxLog(vXTrxLog);
}
@@ -86,13 +89,14 @@ public VXTrxLog createXTrxLog(VXTrxLog vXTrxLog) {
@PUT
@Path("/trx_log")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.UPDATE_X_TRX_LOG + "\")")
public VXTrxLog updateXTrxLog(VXTrxLog vXTrxLog) {
return xAuditMgr.updateXTrxLog(vXTrxLog);
}
@DELETE
@Path("/trx_log/{id}")
- @PreAuthorize("hasRole('ROLE_SYS_ADMIN')")
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.DELETE_X_TRX_LOG + "\")")
@RangerAnnotationClassName(class_name = VXTrxLog.class)
public void deleteXTrxLog(@PathParam("id") Long id,
@Context HttpServletRequest request) {
@@ -109,6 +113,7 @@ public void deleteXTrxLog(@PathParam("id") Long id,
@GET
@Path("/trx_log")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_X_TRX_LOG + "\")")
public VXTrxLogList searchXTrxLogs(@Context HttpServletRequest request) {
SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
request, xTrxLogService.sortFields);
@@ -118,6 +123,7 @@ public VXTrxLogList searchXTrxLogs(@Context HttpServletRequest request) {
@GET
@Path("/trx_log/count")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.COUNT_X_TRX_LOGS + "\")")
public VXLong countXTrxLogs(@Context HttpServletRequest request) {
SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
request, xTrxLogService.sortFields);
@@ -135,6 +141,7 @@ public VXLong countXTrxLogs(@Context HttpServletRequest request) {
@GET
@Path("/access_audit")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_X_ACCESS_AUDITS + "\")")
public VXAccessAuditList searchXAccessAudits(@Context HttpServletRequest request) {
SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
request, xAccessAuditService.sortFields);
@@ -144,6 +151,7 @@ public VXAccessAuditList searchXAccessAudits(@Context HttpServletRequest request
@GET
@Path("/access_audit/count")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.COUNT_X_ACCESS_AUDITS + "\")")
public VXLong countXAccessAudits(@Context HttpServletRequest request) {
SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
request, xAccessAuditService.sortFields);
diff --git a/security-admin/src/main/java/org/apache/ranger/rest/XKeyREST.java b/security-admin/src/main/java/org/apache/ranger/rest/XKeyREST.java
index 1c0f9fc4a19..c374f8eac9a 100755
--- a/security-admin/src/main/java/org/apache/ranger/rest/XKeyREST.java
+++ b/security-admin/src/main/java/org/apache/ranger/rest/XKeyREST.java
@@ -35,12 +35,15 @@
import org.apache.ranger.common.RESTErrorUtil;
import org.apache.ranger.common.SearchUtil;
import org.apache.ranger.common.annotation.RangerAnnotationJSMgrName;
+import org.apache.ranger.security.context.RangerAPIList;
+import org.apache.ranger.security.context.RangerPreAuthSecurityHandler;
import org.apache.ranger.view.VXKmsKey;
import org.apache.ranger.view.VXKmsKeyList;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
+import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@@ -66,7 +69,7 @@ public class XKeyREST {
@Autowired
RESTErrorUtil restErrorUtil;
-
+
/**
* Implements the traditional search functionalities for Keys
*
@@ -76,6 +79,7 @@ public class XKeyREST {
@GET
@Path("/keys")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_KEYS + "\")")
public VXKmsKeyList searchKeys(@Context HttpServletRequest request, @QueryParam("provider") String provider) {
VXKmsKeyList vxKmsKeyList = new VXKmsKeyList();
try{
@@ -94,6 +98,7 @@ public VXKmsKeyList searchKeys(@Context HttpServletRequest request, @QueryParam(
@PUT
@Path("/key")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.ROLLOVER_KEYS + "\")")
public VXKmsKey rolloverKey(@QueryParam("provider") String provider, VXKmsKey vXKey) {
VXKmsKey vxKmsKey = new VXKmsKey();
try{
@@ -120,6 +125,7 @@ public VXKmsKey rolloverKey(@QueryParam("provider") String provider, VXKmsKey vX
@DELETE
@Path("/key/{alias}")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.DELETE_KEY + "\")")
public void deleteKey(@PathParam("alias") String name, @QueryParam("provider") String provider, @Context HttpServletRequest request) {
try{
if (name == null || name.isEmpty()) {
@@ -140,6 +146,7 @@ public void deleteKey(@PathParam("alias") String name, @QueryParam("provider") S
@POST
@Path("/key")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.CREATE_KEY + "\")")
public VXKmsKey createKey(@QueryParam("provider") String provider, VXKmsKey vXKey) {
VXKmsKey vxKmsKey = new VXKmsKey();
try{
@@ -167,6 +174,7 @@ public VXKmsKey createKey(@QueryParam("provider") String provider, VXKmsKey vXKe
@GET
@Path("/key/{alias}")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_KEY + "\")")
public VXKmsKey getKey(@PathParam("alias") String name,@QueryParam("provider") String provider){
VXKmsKey vxKmsKey = new VXKmsKey();
try{
diff --git a/security-admin/src/main/java/org/apache/ranger/rest/XUserREST.java b/security-admin/src/main/java/org/apache/ranger/rest/XUserREST.java
index 93980b49d5e..472dad6bb37 100644
--- a/security-admin/src/main/java/org/apache/ranger/rest/XUserREST.java
+++ b/security-admin/src/main/java/org/apache/ranger/rest/XUserREST.java
@@ -36,6 +36,7 @@
import org.apache.ranger.biz.RangerBizUtil;
import org.apache.ranger.biz.SessionMgr;
import org.apache.ranger.biz.XUserMgr;
+import org.apache.ranger.common.MessageEnums;
import org.apache.ranger.common.RESTErrorUtil;
import org.apache.ranger.common.SearchCriteria;
import org.apache.ranger.common.SearchUtil;
@@ -43,6 +44,9 @@
import org.apache.ranger.common.annotation.RangerAnnotationClassName;
import org.apache.ranger.common.annotation.RangerAnnotationJSMgrName;
import org.apache.ranger.db.RangerDaoManager;
+import org.apache.ranger.security.context.RangerAPIList;
+import org.apache.ranger.security.context.RangerAPIMapping;
+import org.apache.ranger.security.context.RangerPreAuthSecurityHandler;
import org.apache.ranger.service.AuthSessionService;
import org.apache.ranger.service.XAuditMapService;
import org.apache.ranger.service.XGroupGroupService;
@@ -51,6 +55,7 @@
import org.apache.ranger.service.XGroupUserService;
import org.apache.ranger.service.XModuleDefService;
import org.apache.ranger.service.XPermMapService;
+import org.apache.ranger.service.XResourceService;
import org.apache.ranger.service.XUserPermissionService;
import org.apache.ranger.service.XUserService;
import org.apache.ranger.view.VXAuditMap;
@@ -138,11 +143,15 @@ public class XUserREST {
@Autowired
RangerBizUtil bizUtil;
+
+ @Autowired
+ XResourceService xResourceService;
// Handle XGroup
@GET
@Path("/groups/{id}")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_GROUP + "\")")
public VXGroup getXGroup(@PathParam("id") Long id) {
return xUserMgr.getXGroup(id);
}
@@ -150,6 +159,7 @@ public VXGroup getXGroup(@PathParam("id") Long id) {
@GET
@Path("/secure/groups/{id}")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SECURE_GET_X_GROUP + "\")")
public VXGroup secureGetXGroup(@PathParam("id") Long id) {
return xUserMgr.getXGroup(id);
}
@@ -187,6 +197,7 @@ public VXGroup secureUpdateXGroup(VXGroup vXGroup) {
@PUT
@Path("/secure/groups/visibility")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.MODIFY_GROUPS_VISIBILITY + "\")")
public void modifyGroupsVisibility(HashMap groupVisibilityMap){
xUserMgr.modifyGroupsVisibility(groupVisibilityMap);
}
@@ -210,6 +221,7 @@ public void deleteXGroup(@PathParam("id") Long id,
@GET
@Path("/groups")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_X_GROUPS + "\")")
public VXGroupList searchXGroups(@Context HttpServletRequest request) {
SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
request, xGroupService.sortFields);
@@ -224,6 +236,7 @@ public VXGroupList searchXGroups(@Context HttpServletRequest request) {
@GET
@Path("/groups/count")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.COUNT_X_GROUPS + "\")")
public VXLong countXGroups(@Context HttpServletRequest request) {
SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
request, xGroupService.sortFields);
@@ -235,6 +248,7 @@ public VXLong countXGroups(@Context HttpServletRequest request) {
@GET
@Path("/users/{id}")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_USER + "\")")
public VXUser getXUser(@PathParam("id") Long id) {
return xUserMgr.getXUser(id);
}
@@ -242,6 +256,7 @@ public VXUser getXUser(@PathParam("id") Long id) {
@GET
@Path("/secure/users/{id}")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SECURE_GET_X_USER + "\")")
public VXUser secureGetXUser(@PathParam("id") Long id) {
return xUserMgr.getXUser(id);
}
@@ -291,6 +306,7 @@ public VXUser secureUpdateXUser(VXUser vXUser) {
@PUT
@Path("/secure/users/visibility")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.MODIFY_USER_VISIBILITY + "\")")
public void modifyUserVisibility(HashMap visibilityMap){
xUserMgr.modifyUserVisibility(visibilityMap);
}
@@ -314,6 +330,7 @@ public void deleteXUser(@PathParam("id") Long id,
@GET
@Path("/users")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_X_USERS + "\")")
public VXUserList searchXUsers(@Context HttpServletRequest request) {
SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
request, xUserService.sortFields);
@@ -334,6 +351,7 @@ public VXUserList searchXUsers(@Context HttpServletRequest request) {
@GET
@Path("/users/count")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.COUNT_X_USERS + "\")")
public VXLong countXUsers(@Context HttpServletRequest request) {
SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
request, xUserService.sortFields);
@@ -345,6 +363,7 @@ public VXLong countXUsers(@Context HttpServletRequest request) {
@GET
@Path("/groupusers/{id}")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_GROUP_USER + "\")")
public VXGroupUser getXGroupUser(@PathParam("id") Long id) {
return xUserMgr.getXGroupUser(id);
}
@@ -383,6 +402,7 @@ public void deleteXGroupUser(@PathParam("id") Long id,
@GET
@Path("/groupusers")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_X_GROUP_USERS + "\")")
public VXGroupUserList searchXGroupUsers(@Context HttpServletRequest request) {
SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
request, xGroupUserService.sortFields);
@@ -392,6 +412,7 @@ public VXGroupUserList searchXGroupUsers(@Context HttpServletRequest request) {
@GET
@Path("/groupusers/count")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.COUNT_X_GROUP_USERS + "\")")
public VXLong countXGroupUsers(@Context HttpServletRequest request) {
SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
request, xGroupUserService.sortFields);
@@ -403,6 +424,7 @@ public VXLong countXGroupUsers(@Context HttpServletRequest request) {
@GET
@Path("/groupgroups/{id}")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_GROUP_GROUP + "\")")
public VXGroupGroup getXGroupGroup(@PathParam("id") Long id) {
return xUserMgr.getXGroupGroup(id);
}
@@ -440,6 +462,7 @@ public void deleteXGroupGroup(@PathParam("id") Long id,
@GET
@Path("/groupgroups")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_X_GROUP_GROUPS + "\")")
public VXGroupGroupList searchXGroupGroups(
@Context HttpServletRequest request) {
SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
@@ -450,6 +473,7 @@ public VXGroupGroupList searchXGroupGroups(
@GET
@Path("/groupgroups/count")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.COUNT_X_GROUP_GROUPS + "\")")
public VXLong countXGroupGroups(@Context HttpServletRequest request) {
SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
request, xGroupGroupService.sortFields);
@@ -461,28 +485,53 @@ public VXLong countXGroupGroups(@Context HttpServletRequest request) {
@GET
@Path("/permmaps/{id}")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_PERM_MAP + "\")")
public VXPermMap getXPermMap(@PathParam("id") Long id) {
- return xUserMgr.getXPermMap(id);
+ VXPermMap permMap = xUserMgr.getXPermMap(id);
+
+ if (permMap != null) {
+ if (xResourceService.readResource(permMap.getResourceId()) == null) {
+ throw restErrorUtil.createRESTException("Invalid Input Data - No resource found with Id: " + permMap.getResourceId(), MessageEnums.INVALID_INPUT_DATA);
+ }
+ }
+
+ return permMap;
}
@POST
@Path("/permmaps")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.CREATE_X_PERM_MAP + "\")")
public VXPermMap createXPermMap(VXPermMap vXPermMap) {
+
+ if (vXPermMap != null) {
+ if (xResourceService.readResource(vXPermMap.getResourceId()) == null) {
+ throw restErrorUtil.createRESTException("Invalid Input Data - No resource found with Id: " + vXPermMap.getResourceId(), MessageEnums.INVALID_INPUT_DATA);
+ }
+ }
+
return xUserMgr.createXPermMap(vXPermMap);
}
@PUT
@Path("/permmaps")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.UPDATE_X_PERM_MAP + "\")")
public VXPermMap updateXPermMap(VXPermMap vXPermMap) {
+
+ if (vXPermMap != null) {
+ if (xResourceService.readResource(vXPermMap.getResourceId()) == null) {
+ throw restErrorUtil.createRESTException("Invalid Input Data - No resource found with Id: " + vXPermMap.getResourceId());
+ }
+ }
+
return xUserMgr.updateXPermMap(vXPermMap);
}
@DELETE
@Path("/permmaps/{id}")
- @PreAuthorize("hasRole('ROLE_SYS_ADMIN')")
@RangerAnnotationClassName(class_name = VXPermMap.class)
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.DELETE_X_PERM_MAP + "\")")
public void deleteXPermMap(@PathParam("id") Long id,
@Context HttpServletRequest request) {
boolean force = false;
@@ -498,6 +547,7 @@ public void deleteXPermMap(@PathParam("id") Long id,
@GET
@Path("/permmaps")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_X_PERM_MAPS + "\")")
public VXPermMapList searchXPermMaps(@Context HttpServletRequest request) {
SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
request, xPermMapService.sortFields);
@@ -507,6 +557,7 @@ public VXPermMapList searchXPermMaps(@Context HttpServletRequest request) {
@GET
@Path("/permmaps/count")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.COUNT_X_PERM_MAPS + "\")")
public VXLong countXPermMaps(@Context HttpServletRequest request) {
SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
request, xPermMapService.sortFields);
@@ -518,28 +569,53 @@ public VXLong countXPermMaps(@Context HttpServletRequest request) {
@GET
@Path("/auditmaps/{id}")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_AUDIT_MAP + "\")")
public VXAuditMap getXAuditMap(@PathParam("id") Long id) {
- return xUserMgr.getXAuditMap(id);
+ VXAuditMap vXAuditMap = xUserMgr.getXAuditMap(id);
+
+ if (vXAuditMap != null) {
+ if (xResourceService.readResource(vXAuditMap.getResourceId()) == null) {
+ throw restErrorUtil.createRESTException("Invalid Input Data - No resource found with Id: " + vXAuditMap.getResourceId(), MessageEnums.INVALID_INPUT_DATA);
+ }
+ }
+
+ return vXAuditMap;
}
@POST
@Path("/auditmaps")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.CREATE_X_AUDIT_MAP + "\")")
public VXAuditMap createXAuditMap(VXAuditMap vXAuditMap) {
+
+ if (vXAuditMap != null) {
+ if (xResourceService.readResource(vXAuditMap.getResourceId()) == null) {
+ throw restErrorUtil.createRESTException("Invalid Input Data - No resource found with Id: " + vXAuditMap.getResourceId(), MessageEnums.INVALID_INPUT_DATA);
+ }
+ }
+
return xUserMgr.createXAuditMap(vXAuditMap);
}
@PUT
@Path("/auditmaps")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.UPDATE_X_AUDIT_MAP + "\")")
public VXAuditMap updateXAuditMap(VXAuditMap vXAuditMap) {
+
+ if (vXAuditMap != null) {
+ if (xResourceService.readResource(vXAuditMap.getResourceId()) == null) {
+ throw restErrorUtil.createRESTException("Invalid Input Data - No resource found with Id: " + vXAuditMap.getResourceId(), MessageEnums.INVALID_INPUT_DATA);
+ }
+ }
+
return xUserMgr.updateXAuditMap(vXAuditMap);
}
@DELETE
@Path("/auditmaps/{id}")
- @PreAuthorize("hasRole('ROLE_SYS_ADMIN')")
@RangerAnnotationClassName(class_name = VXAuditMap.class)
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.DELETE_X_AUDIT_MAP + "\")")
public void deleteXAuditMap(@PathParam("id") Long id,
@Context HttpServletRequest request) {
boolean force = false;
@@ -555,6 +631,7 @@ public void deleteXAuditMap(@PathParam("id") Long id,
@GET
@Path("/auditmaps")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_X_AUDIT_MAPS + "\")")
public VXAuditMapList searchXAuditMaps(@Context HttpServletRequest request) {
SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
request, xAuditMapService.sortFields);
@@ -564,6 +641,7 @@ public VXAuditMapList searchXAuditMaps(@Context HttpServletRequest request) {
@GET
@Path("/auditmaps/count")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.COUNT_X_AUDIT_MAPS + "\")")
public VXLong countXAuditMaps(@Context HttpServletRequest request) {
SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
request, xAuditMapService.sortFields);
@@ -575,6 +653,7 @@ public VXLong countXAuditMaps(@Context HttpServletRequest request) {
@GET
@Path("/users/userName/{userName}")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_USER_BY_USER_NAME + "\")")
public VXUser getXUserByUserName(@Context HttpServletRequest request,
@PathParam("userName") String userName) {
return xUserMgr.getXUserByUserName(userName);
@@ -583,6 +662,7 @@ public VXUser getXUserByUserName(@Context HttpServletRequest request,
@GET
@Path("/groups/groupName/{groupName}")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_GROUP_BY_GROUP_NAME + "\")")
public VXGroup getXGroupByGroupName(@Context HttpServletRequest request,
@PathParam("groupName") String groupName) {
return xGroupService.getGroupByGroupName(groupName);
@@ -629,6 +709,7 @@ public void deleteXGroupAndXUser(@PathParam("groupName") String groupName,
@GET
@Path("/{userId}/groups")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_USER_GROUPS + "\")")
public VXGroupList getXUserGroups(@Context HttpServletRequest request,
@PathParam("userId") Long id){
return xUserMgr.getXUserGroups(id);
@@ -637,6 +718,7 @@ public VXGroupList getXUserGroups(@Context HttpServletRequest request,
@GET
@Path("/{groupId}/users")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_GROUP_USERS + "\")")
public VXUserList getXGroupUsers(@Context HttpServletRequest request,
@PathParam("groupId") Long id){
return xUserMgr.getXGroupUsers(id);
@@ -645,6 +727,7 @@ public VXUserList getXGroupUsers(@Context HttpServletRequest request,
@GET
@Path("/authSessions")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_AUTH_SESSIONS + "\")")
public VXAuthSessionList getAuthSessions(@Context HttpServletRequest request){
SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
request, authSessionService.AUTH_SESSION_SORT_FLDS);
@@ -666,6 +749,7 @@ public VXAuthSessionList getAuthSessions(@Context HttpServletRequest request){
@GET
@Path("/authSessions/info")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_AUTH_SESSION + "\")")
public VXAuthSession getAuthSession(@Context HttpServletRequest request){
String authSessionId = request.getParameter("extSessionId");
return sessionMgr.getAuthSessionBySessionId(authSessionId);
@@ -675,6 +759,7 @@ public VXAuthSession getAuthSession(@Context HttpServletRequest request){
@POST
@Path("/permission")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.CREATE_X_MODULE_DEF_PERMISSION + "\")")
public VXModuleDef createXModuleDefPermission(VXModuleDef vXModuleDef) {
return xUserMgr.createXModuleDefPermission(vXModuleDef);
}
@@ -682,6 +767,7 @@ public VXModuleDef createXModuleDefPermission(VXModuleDef vXModuleDef) {
@GET
@Path("/permission/{id}")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_MODULE_DEF_PERMISSION + "\")")
public VXModuleDef getXModuleDefPermission(@PathParam("id") Long id) {
return xUserMgr.getXModuleDefPermission(id);
}
@@ -689,13 +775,14 @@ public VXModuleDef getXModuleDefPermission(@PathParam("id") Long id) {
@PUT
@Path("/permission/{id}")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.UPDATE_X_MODULE_DEF_PERMISSION + "\")")
public VXModuleDef updateXModuleDefPermission(VXModuleDef vXModuleDef) {
return xUserMgr.updateXModuleDefPermission(vXModuleDef);
}
@DELETE
@Path("/permission/{id}")
- @PreAuthorize("hasRole('ROLE_SYS_ADMIN')")
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.DELETE_X_MODULE_DEF_PERMISSION + "\")")
public void deleteXModuleDefPermission(@PathParam("id") Long id,
@Context HttpServletRequest request) {
boolean force = true;
@@ -705,6 +792,7 @@ public void deleteXModuleDefPermission(@PathParam("id") Long id,
@GET
@Path("/permission")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_X_MODULE_DEF + "\")")
public VXModuleDefList searchXModuleDef(@Context HttpServletRequest request) {
SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
request, xModuleDefService.sortFields);
@@ -725,6 +813,7 @@ public VXModuleDefList searchXModuleDef(@Context HttpServletRequest request) {
@GET
@Path("/permission/count")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.COUNT_X_MODULE_DEF + "\")")
public VXLong countXModuleDef(@Context HttpServletRequest request) {
SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
request, xModuleDefService.sortFields);
@@ -735,6 +824,7 @@ public VXLong countXModuleDef(@Context HttpServletRequest request) {
@POST
@Path("/permission/user")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.CREATE_X_USER_PERMISSION + "\")")
public VXUserPermission createXUserPermission(
VXUserPermission vXUserPermission) {
return xUserMgr.createXUserPermission(vXUserPermission);
@@ -743,6 +833,7 @@ public VXUserPermission createXUserPermission(
@GET
@Path("/permission/user/{id}")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_USER_PERMISSION + "\")")
public VXUserPermission getXUserPermission(@PathParam("id") Long id) {
return xUserMgr.getXUserPermission(id);
}
@@ -750,6 +841,7 @@ public VXUserPermission getXUserPermission(@PathParam("id") Long id) {
@PUT
@Path("/permission/user/{id}")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.UPDATE_X_USER_PERMISSION + "\")")
public VXUserPermission updateXUserPermission(
VXUserPermission vXUserPermission) {
return xUserMgr.updateXUserPermission(vXUserPermission);
@@ -757,7 +849,7 @@ public VXUserPermission updateXUserPermission(
@DELETE
@Path("/permission/user/{id}")
- @PreAuthorize("hasRole('ROLE_SYS_ADMIN')")
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.DELETE_X_USER_PERMISSION + "\")")
public void deleteXUserPermission(@PathParam("id") Long id,
@Context HttpServletRequest request) {
boolean force = true;
@@ -767,6 +859,7 @@ public void deleteXUserPermission(@PathParam("id") Long id,
@GET
@Path("/permission/user")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_X_USER_PERMISSION + "\")")
public VXUserPermissionList searchXUserPermission(
@Context HttpServletRequest request) {
SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
@@ -782,6 +875,7 @@ public VXUserPermissionList searchXUserPermission(
@GET
@Path("/permission/user/count")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.COUNT_X_USER_PERMISSION + "\")")
public VXLong countXUserPermission(@Context HttpServletRequest request) {
SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
request, xUserPermissionService.sortFields);
@@ -792,6 +886,7 @@ public VXLong countXUserPermission(@Context HttpServletRequest request) {
@POST
@Path("/permission/group")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.CREATE_X_GROUP_PERMISSION + "\")")
public VXGroupPermission createXGroupPermission(
VXGroupPermission vXGroupPermission) {
return xUserMgr.createXGroupPermission(vXGroupPermission);
@@ -800,6 +895,7 @@ public VXGroupPermission createXGroupPermission(
@GET
@Path("/permission/group/{id}")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_GROUP_PERMISSION + "\")")
public VXGroupPermission getXGroupPermission(@PathParam("id") Long id) {
return xUserMgr.getXGroupPermission(id);
}
@@ -807,6 +903,7 @@ public VXGroupPermission getXGroupPermission(@PathParam("id") Long id) {
@PUT
@Path("/permission/group/{id}")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.UPDATE_X_GROUP_PERMISSION + "\")")
public VXGroupPermission updateXGroupPermission(
VXGroupPermission vXGroupPermission) {
return xUserMgr.updateXGroupPermission(vXGroupPermission);
@@ -814,7 +911,7 @@ public VXGroupPermission updateXGroupPermission(
@DELETE
@Path("/permission/group/{id}")
- @PreAuthorize("hasRole('ROLE_SYS_ADMIN')")
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.DELETE_X_GROUP_PERMISSION + "\")")
public void deleteXGroupPermission(@PathParam("id") Long id,
@Context HttpServletRequest request) {
boolean force = true;
@@ -824,6 +921,7 @@ public void deleteXGroupPermission(@PathParam("id") Long id,
@GET
@Path("/permission/group")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_X_GROUP_PERMISSION + "\")")
public VXGroupPermissionList searchXGroupPermission(
@Context HttpServletRequest request) {
SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
@@ -838,6 +936,7 @@ public VXGroupPermissionList searchXGroupPermission(
@GET
@Path("/permission/group/count")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.COUNT_X_GROUP_PERMISSION + "\")")
public VXLong countXGroupPermission(@Context HttpServletRequest request) {
SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
request, xGroupPermissionService.sortFields);
@@ -847,6 +946,7 @@ public VXLong countXGroupPermission(@Context HttpServletRequest request) {
@PUT
@Path("/secure/users/activestatus")
@Produces({ "application/xml", "application/json" })
+ @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.MODIFY_USER_ACTIVE_STATUS + "\")")
public void modifyUserActiveStatus(HashMap statusMap){
xUserMgr.modifyUserActiveStatus(statusMap);
}
diff --git a/security-admin/src/main/java/org/apache/ranger/security/context/RangerAPIList.java b/security-admin/src/main/java/org/apache/ranger/security/context/RangerAPIList.java
new file mode 100644
index 00000000000..f10453c0449
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/security/context/RangerAPIList.java
@@ -0,0 +1,201 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.ranger.security.context;
+
+/**
+ * This class holds list of APIs available in the system.
+ * This Class needs to be updated when writing new API in any of the REST.
+ */
+public class RangerAPIList {
+
+ /**
+ * List of APIs for AssetREST
+ */
+ public static final String GET_X_ASSET = "AssetREST.getXAsset";
+ public static final String CREATE_X_ASSET = "AssetREST.createXAsset";
+ public static final String UPDATE_X_ASSET = "AssetREST.updateXAsset";
+ public static final String DELETE_X_ASSET = "AssetREST.deleteXAsset";
+ public static final String TEST_CONFIG = "AssetREST.testConfig";
+ public static final String SEARCH_X_ASSETS = "AssetREST.searchXAssets";
+ public static final String COUNT_X_ASSETS = "AssetREST.countXAssets";
+ public static final String GET_X_RESOURCE = "AssetREST.getXResource";
+ public static final String CREATE_X_RESOURCE = "AssetREST.createXResource";
+ public static final String UPDATE_X_RESOURCE = "AssetREST.updateXResource";
+ public static final String DELETE_X_RESOURCE = "AssetREST.deleteXResource";
+ public static final String SEARCH_X_RESOURCES = "AssetREST.searchXResources";
+ public static final String COUNT_X_RESOURCES = "AssetREST.countXResources";
+ public static final String GET_X_CRED_STORE = "AssetREST.getXCredentialStore";
+ public static final String CREATE_X_CRED_STORE = "AssetREST.createXCredentialStore";
+ public static final String UPDATE_X_CRED_STORE = "AssetREST.updateXCredentialStore";
+ public static final String DELETE_X_CRED_STORE = "AssetREST.deleteXCredentialStore";
+ public static final String SEARCH_X_CRED_STORE = "AssetREST.searchXCredentialStores";
+ public static final String COUNT_X_CRED_STORE = "AssetREST.countXCredentialStores";
+ public static final String GET_X_RESOURCE_FILE = "AssetREST.getXResourceFile";
+ public static final String GET_RESOURCE_JSON = "AssetREST.getResourceJSON";
+ public static final String SEARCH_X_POLICY_EXPORT_AUDITS = "AssetREST.searchXPolicyExportAudits";
+ public static final String GET_REPORT_LOGS = "AssetREST.getReportLogs";
+ public static final String GET_TRANSACTION_REPORT = "AssetREST.getTransactionReport";
+ public static final String GET_ACCESS_LOGS = "AssetREST.getAccessLogs";
+ public static final String GRANT_PERMISSION = "AssetREST.grantPermission";
+ public static final String REVOKE_PERMISSION = "AssetREST.revokePermission";
+
+ /**
+ * List of APIs for ServiceREST
+ */
+ public static final String CREATE_SERVICE_DEF = "ServiceREST.createServiceDef";
+ public static final String UPDATE_SERVICE_DEF = "ServiceREST.updateServiceDef";
+ public static final String DELETE_SERVICE_DEF = "ServiceREST.deleteServiceDef";
+ public static final String GET_SERVICE_DEF = "ServiceREST.getServiceDef";
+ public static final String GET_SERVICE_DEF_BY_NAME = "ServiceREST.getServiceDefByName";
+ public static final String GET_SERVICE_DEFS = "ServiceREST.getServiceDefs";
+ public static final String CREATE_SERVICE = "ServiceREST.createService";
+ public static final String UPDATE_SERVICE = "ServiceREST.updateService";
+ public static final String DELETE_SERVICE = "ServiceREST.deleteService";
+ public static final String GET_SERVICE = "ServiceREST.getService";
+ public static final String GET_SERVICE_BY_NAME = "ServiceREST.getServiceByName";
+ public static final String GET_SERVICES = "ServiceREST.getServices";
+ public static final String COUNT_SERVICES = "ServiceREST.countServices";
+ public static final String VALIDATE_CONFIG = "ServiceREST.validateConfig";
+ public static final String LOOKUP_RESOURCE = "ServiceREST.lookupResource";
+ public static final String GRANT_ACCESS = "ServiceREST.grantAccess";
+ public static final String REVOKE_ACCESS = "ServiceREST.revokeAccess";
+ public static final String CREATE_POLICY = "ServiceREST.createPolicy";
+ public static final String UPDATE_POLICY = "ServiceREST.updatePolicy";
+ public static final String DELETE_POLICY = "ServiceREST.deletePolicy";
+ public static final String GET_POLICY = "ServiceREST.getPolicy";
+ public static final String GET_POLICIES = "ServiceREST.getPolicies";
+ public static final String COUNT_POLICIES = "ServiceREST.countPolicies";
+ public static final String GET_SERVICE_POLICIES = "ServiceREST.getServicePolicies";
+ public static final String GET_SERVICE_POLICIES_BY_NAME = "ServiceREST.getServicePoliciesByName";
+ public static final String GET_SERVICE_POLICIES_IF_UPDATED = "ServiceREST.getServicePoliciesIfUpdated";
+ public static final String GET_POLICY_FROM_EVENT_TIME = "ServiceREST.getPolicyFromEventTime";
+ public static final String GET_POLICY_VERSION_LIST = "ServiceREST.getPolicyVersionList";
+ public static final String GET_POLICY_FOR_VERSION_NO = "ServiceREST.getPolicyForVersionNumber";
+
+ /**
+ * List of APIs for UserREST
+ */
+ public static final String SEARCH_USERS = "UserREST.searchUsers";
+ public static final String GET_USER_PROFILE_FOR_USER = "UserREST.getUserProfileForUser";
+ public static final String CREATE = "UserREST.create";
+ public static final String CREATE_DEFAULT_ACCOUNT_USER = "UserREST.createDefaultAccountUser";
+ public static final String UPDATE = "UserREST.update";
+ public static final String SET_USER_ROLES = "UserREST.setUserRoles";
+ public static final String DEACTIVATE_USER = "UserREST.deactivateUser";
+ public static final String GET_USER_PROFILE = "UserREST.getUserProfile";
+ public static final String SUGGEST_USER_FIRST_NAME = "UserREST.suggestUserFirstName";
+ public static final String CHANGE_PASSWORD = "UserREST.changePassword";
+ public static final String CHANGE_EMAIL_ADDRESS = "UserREST.changeEmailAddress";
+
+ /**
+ * List of APIs for XAuditREST
+ */
+ public static final String GET_X_TRX_LOG = "XAuditREST.getXTrxLog";
+ public static final String CREATE_X_TRX_LOG = "XAuditREST.createXTrxLog";
+ public static final String UPDATE_X_TRX_LOG = "XAuditREST.updateXTrxLog";
+ public static final String DELETE_X_TRX_LOG = "XAuditREST.deleteXTrxLog";
+ public static final String SEARCH_X_TRX_LOG = "XAuditREST.searchXTrxLogs";
+ public static final String COUNT_X_TRX_LOGS = "XAuditREST.countXTrxLogs";
+ public static final String SEARCH_X_ACCESS_AUDITS = "XAuditREST.searchXAccessAudits";
+ public static final String COUNT_X_ACCESS_AUDITS = "XAuditREST.countXAccessAudits";
+
+ /**
+ * List of APIs for XKeyREST
+ */
+ public static final String SEARCH_KEYS = "XKeyREST.searchKeys";
+ public static final String ROLLOVER_KEYS = "XKeyREST.rolloverKey";
+ public static final String DELETE_KEY = "XKeyREST.deleteKey";
+ public static final String CREATE_KEY = "XKeyREST.createKey";
+ public static final String GET_KEY = "XKeyREST.getKey";
+
+ /**
+ * List of APIs for XUserREST
+ */
+ public static final String GET_X_GROUP = "XUserREST.getXGroup";
+ public static final String SECURE_GET_X_GROUP = "XUserREST.secureGetXGroup";
+ public static final String CREATE_X_GROUP = "XUserREST.createXGroup";
+ public static final String SECURE_CREATE_X_GROUP = "XUserREST.secureCreateXGroup";
+ public static final String UPDATE_X_GROUP = "XUserREST.updateXGroup";
+ public static final String SECURE_UPDATE_X_GROUP = "XUserREST.secureUpdateXGroup";
+ public static final String MODIFY_GROUPS_VISIBILITY = "XUserREST.modifyGroupsVisibility";
+ public static final String DELETE_X_GROUP = "XUserREST.deleteXGroup";
+ public static final String SEARCH_X_GROUPS = "XUserREST.searchXGroups";
+ public static final String COUNT_X_GROUPS = "XUserREST.countXGroups";
+ public static final String GET_X_USER = "XUserREST.getXUser";
+ public static final String SECURE_GET_X_USER = "XUserREST.secureGetXUser";
+ public static final String CREATE_X_USER = "XUserREST.createXUser";
+ public static final String CREATE_X_USER_GROUP_FROM_MAP = "XUserREST.createXUserGroupFromMap";
+ public static final String SECURE_CREATE_X_USER = "XUserREST.secureCreateXUser";
+ public static final String UPDATE_X_USER = "XUserREST.updateXUser";
+ public static final String SECURE_UPDATE_X_USER = "XUserREST.secureUpdateXUser";
+ public static final String MODIFY_USER_VISIBILITY = "XUserREST.modifyUserVisibility";
+ public static final String DELETE_X_USER = "XUserREST.deleteXUser";
+ public static final String SEARCH_X_USERS = "XUserREST.searchXUsers";
+ public static final String COUNT_X_USERS = "XUserREST.countXUsers";
+ public static final String GET_X_GROUP_USER = "XUserREST.getXGroupUser";
+ public static final String CREATE_X_GROUP_USER = "XUserREST.createXGroupUser";
+ public static final String UPDATE_X_GROUP_USER = "XUserREST.updateXGroupUser";
+ public static final String DELETE_X_GROUP_USER = "XUserREST.deleteXGroupUser";
+ public static final String SEARCH_X_GROUP_USERS = "XUserREST.searchXGroupUsers";
+ public static final String COUNT_X_GROUP_USERS = "XUserREST.countXGroupUsers";
+ public static final String GET_X_GROUP_GROUP = "XUserREST.getXGroupGroup";
+ public static final String CREATE_X_GROUP_GROUP = "XUserREST.createXGroupGroup";
+ public static final String UPDATE_X_GROUP_GROUP = "XUserREST.updateXGroupGroup";
+ public static final String DELETE_X_GROUP_GROUP = "XUserREST.deleteXGroupGroup";
+ public static final String SEARCH_X_GROUP_GROUPS = "XUserREST.searchXGroupGroups";
+ public static final String COUNT_X_GROUP_GROUPS = "XUserREST.countXGroupGroups";
+ public static final String GET_X_PERM_MAP = "XUserREST.getXPermMap";
+ public static final String CREATE_X_PERM_MAP = "XUserREST.createXPermMap";
+ public static final String UPDATE_X_PERM_MAP = "XUserREST.updateXPermMap";
+ public static final String DELETE_X_PERM_MAP = "XUserREST.deleteXPermMap";
+ public static final String SEARCH_X_PERM_MAPS = "XUserREST.searchXPermMaps";
+ public static final String COUNT_X_PERM_MAPS = "XUserREST.countXPermMaps";
+ public static final String GET_X_AUDIT_MAP = "XUserREST.getXAuditMap";
+ public static final String CREATE_X_AUDIT_MAP = "XUserREST.createXAuditMap";
+ public static final String UPDATE_X_AUDIT_MAP = "XUserREST.updateXAuditMap";
+ public static final String DELETE_X_AUDIT_MAP = "XUserREST.deleteXAuditMap";
+ public static final String SEARCH_X_AUDIT_MAPS = "XUserREST.searchXAuditMaps";
+ public static final String COUNT_X_AUDIT_MAPS = "XUserREST.countXAuditMaps";
+ public static final String GET_X_USER_BY_USER_NAME = "XUserREST.getXUserByUserName";
+ public static final String GET_X_GROUP_BY_GROUP_NAME = "XUserREST.getXGroupByGroupName";
+ public static final String DELETE_X_USER_BY_USER_NAME = "XUserREST.deleteXUserByUserName";
+ public static final String DELETE_X_GROUP_BY_GROUP_NAME = "XUserREST.deleteXGroupByGroupName";
+ public static final String DELETE_X_GROUP_AND_X_USER = "XUserREST.deleteXGroupAndXUser";
+ public static final String GET_X_USER_GROUPS = "XUserREST.getXUserGroups";
+ public static final String GET_X_GROUP_USERS = "XUserREST.getXGroupUsers";
+ public static final String GET_AUTH_SESSIONS = "XUserREST.getAuthSessions";
+ public static final String GET_AUTH_SESSION = "XUserREST.getAuthSession";
+ public static final String CREATE_X_MODULE_DEF_PERMISSION = "XUserREST.createXModuleDefPermission";
+ public static final String GET_X_MODULE_DEF_PERMISSION = "XUserREST.getXModuleDefPermission";
+ public static final String UPDATE_X_MODULE_DEF_PERMISSION = "XUserREST.updateXModuleDefPermission";
+ public static final String DELETE_X_MODULE_DEF_PERMISSION = "XUserREST.deleteXModuleDefPermission";
+ public static final String SEARCH_X_MODULE_DEF = "XUserREST.searchXModuleDef";
+ public static final String COUNT_X_MODULE_DEF = "XUserREST.countXModuleDef";
+ public static final String CREATE_X_USER_PERMISSION = "XUserREST.createXUserPermission";
+ public static final String GET_X_USER_PERMISSION = "XUserREST.getXUserPermission";
+ public static final String UPDATE_X_USER_PERMISSION = "XUserREST.updateXUserPermission";
+ public static final String DELETE_X_USER_PERMISSION = "XUserREST.deleteXUserPermission";
+ public static final String SEARCH_X_USER_PERMISSION = "XUserREST.searchXUserPermission";
+ public static final String COUNT_X_USER_PERMISSION = "XUserREST.countXUserPermission";
+ public static final String CREATE_X_GROUP_PERMISSION = "XUserREST.createXGroupPermission";
+ public static final String GET_X_GROUP_PERMISSION = "XUserREST.getXGroupPermission";
+ public static final String UPDATE_X_GROUP_PERMISSION = "XUserREST.updateXGroupPermission";
+ public static final String DELETE_X_GROUP_PERMISSION = "XUserREST.deleteXGroupPermission";
+ public static final String SEARCH_X_GROUP_PERMISSION = "XUserREST.searchXGroupPermission";
+ public static final String COUNT_X_GROUP_PERMISSION = "XUserREST.countXGroupPermission";
+ public static final String MODIFY_USER_ACTIVE_STATUS = "XUserREST.modifyUserActiveStatus";
+}
\ No newline at end of file
diff --git a/security-admin/src/main/java/org/apache/ranger/security/context/RangerAPIMapping.java b/security-admin/src/main/java/org/apache/ranger/security/context/RangerAPIMapping.java
new file mode 100644
index 00000000000..adc8e2a1cfb
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/security/context/RangerAPIMapping.java
@@ -0,0 +1,535 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.ranger.security.context;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.commons.collections.CollectionUtils;
+import org.springframework.stereotype.Component;
+
+@Component
+public class RangerAPIMapping {
+
+ /**
+ * @NOTE While adding new tab here, please don't forget to update the function:
+ * org.apache.ranger.security.context.RangerAPIMapping.getAvailableUITabs()
+ */
+ public static final String TAB_RESOURCE_BASED_POLICIES = "Resource Based Policies";
+ public static final String TAB_AUDIT = "Audit";
+ public static final String TAB_USERS_GROUPS = "Users/Groups";
+ public static final String TAB_PERMISSIONS = "Permissions";
+ public static final String TAB_KEY_MANAGER = "Key Manager";
+ public static final String TAB_TAG_BASED_POLICIES = "Tag Based Policies";
+ public static final String TAB_REPORTS = "Reports";
+
+ private static HashMap> rangerAPIMappingWithUI = null;
+ private static Set tabList = new HashSet();
+ private static Map> mapApiToTabs = null;
+
+ public RangerAPIMapping() {
+ init();
+ }
+
+ private void init() {
+ if (rangerAPIMappingWithUI == null) {
+ rangerAPIMappingWithUI = new HashMap>();
+ }
+ if (mapApiToTabs == null) {
+ mapApiToTabs = new HashMap>();
+ }
+
+ mapResourceBasedPoliciesWithAPIs();
+ mapAuditWithAPIs();
+ mapUGWithAPIs();
+ mapPermissionsWithAPIs();
+ mapKeyManagerWithAPIs();
+ mapTagBasedPoliciesWithAPIs();
+ mapReportsWithAPIs();
+
+ if (CollectionUtils.isEmpty(tabList)) {
+ populateAvailableUITabs();
+ }
+
+ }
+
+ private void populateAvailableUITabs() {
+ tabList = new HashSet();
+ tabList.add(TAB_RESOURCE_BASED_POLICIES);
+ tabList.add(TAB_TAG_BASED_POLICIES);
+ tabList.add(TAB_AUDIT);
+ tabList.add(TAB_REPORTS);
+ tabList.add(TAB_KEY_MANAGER);
+ tabList.add(TAB_PERMISSIONS);
+ tabList.add(TAB_USERS_GROUPS);
+ }
+
+ private void mapReportsWithAPIs() {
+ Set apiAssociatedWithReports = new HashSet();
+
+ apiAssociatedWithReports.add(RangerAPIList.COUNT_X_ASSETS);
+ apiAssociatedWithReports.add(RangerAPIList.GET_X_ASSET);
+ apiAssociatedWithReports.add(RangerAPIList.SEARCH_X_ASSETS);
+
+ apiAssociatedWithReports.add(RangerAPIList.COUNT_SERVICES);
+ apiAssociatedWithReports.add(RangerAPIList.GET_POLICY_FOR_VERSION_NO);
+ apiAssociatedWithReports.add(RangerAPIList.GET_POLICY_FROM_EVENT_TIME);
+ apiAssociatedWithReports.add(RangerAPIList.GET_POLICY_VERSION_LIST);
+ apiAssociatedWithReports.add(RangerAPIList.GET_SERVICE);
+ apiAssociatedWithReports.add(RangerAPIList.GET_SERVICE_BY_NAME);
+ apiAssociatedWithReports.add(RangerAPIList.GET_SERVICE_DEF);
+ apiAssociatedWithReports.add(RangerAPIList.GET_SERVICE_DEF_BY_NAME);
+ apiAssociatedWithReports.add(RangerAPIList.GET_SERVICE_DEFS);
+ apiAssociatedWithReports.add(RangerAPIList.GET_SERVICES);
+ apiAssociatedWithReports.add(RangerAPIList.LOOKUP_RESOURCE);
+
+ apiAssociatedWithReports.add(RangerAPIList.GET_USER_PROFILE_FOR_USER);
+ apiAssociatedWithReports.add(RangerAPIList.SEARCH_USERS);
+
+ apiAssociatedWithReports.add(RangerAPIList.COUNT_X_AUDIT_MAPS);
+ apiAssociatedWithReports.add(RangerAPIList.COUNT_X_GROUP_GROUPS);
+ apiAssociatedWithReports.add(RangerAPIList.COUNT_X_GROUPS);
+ apiAssociatedWithReports.add(RangerAPIList.COUNT_X_GROUP_USERS);
+ apiAssociatedWithReports.add(RangerAPIList.COUNT_X_PERM_MAPS);
+ apiAssociatedWithReports.add(RangerAPIList.COUNT_X_USERS);
+ apiAssociatedWithReports.add(RangerAPIList.GET_X_AUDIT_MAP);
+ apiAssociatedWithReports.add(RangerAPIList.GET_X_GROUP);
+ apiAssociatedWithReports.add(RangerAPIList.GET_X_GROUP_BY_GROUP_NAME);
+ apiAssociatedWithReports.add(RangerAPIList.GET_X_GROUP_GROUP);
+ apiAssociatedWithReports.add(RangerAPIList.GET_X_GROUP_USER);
+ apiAssociatedWithReports.add(RangerAPIList.GET_X_GROUP_USERS);
+ apiAssociatedWithReports.add(RangerAPIList.GET_X_PERM_MAP);
+ apiAssociatedWithReports.add(RangerAPIList.GET_X_USER);
+ apiAssociatedWithReports.add(RangerAPIList.GET_X_USER_BY_USER_NAME);
+ apiAssociatedWithReports.add(RangerAPIList.GET_X_USER_GROUPS);
+ apiAssociatedWithReports.add(RangerAPIList.SEARCH_X_AUDIT_MAPS);
+ apiAssociatedWithReports.add(RangerAPIList.SEARCH_X_GROUP_GROUPS);
+ apiAssociatedWithReports.add(RangerAPIList.SEARCH_X_GROUPS);
+ apiAssociatedWithReports.add(RangerAPIList.SEARCH_X_GROUP_USERS);
+ apiAssociatedWithReports.add(RangerAPIList.SEARCH_X_PERM_MAPS);
+ apiAssociatedWithReports.add(RangerAPIList.SEARCH_X_USERS);
+ apiAssociatedWithReports.add(RangerAPIList.SECURE_GET_X_GROUP);
+ apiAssociatedWithReports.add(RangerAPIList.SECURE_GET_X_USER);
+
+ rangerAPIMappingWithUI.put(TAB_REPORTS, apiAssociatedWithReports);
+
+ for (String api : apiAssociatedWithReports) {
+ if (mapApiToTabs.get(api) == null) {
+ mapApiToTabs.put(api, new HashSet());
+ }
+ mapApiToTabs.get(api).add(TAB_REPORTS);
+ }
+ }
+
+ private void mapTagBasedPoliciesWithAPIs() {
+ Set apiAssociatedWithTagBasedPolicy = new HashSet();
+
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.COUNT_X_ASSETS);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.CREATE_X_ASSET);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.DELETE_X_ASSET);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_X_ASSET);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.SEARCH_X_ASSETS);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.TEST_CONFIG);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.UPDATE_X_ASSET);
+
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.COUNT_SERVICES);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.CREATE_SERVICE);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.CREATE_SERVICE_DEF);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.DELETE_SERVICE);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.DELETE_SERVICE_DEF);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_POLICY_FOR_VERSION_NO);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_POLICY_FROM_EVENT_TIME);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_POLICY_VERSION_LIST);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_SERVICE);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_SERVICE_BY_NAME);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_SERVICE_DEF);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_SERVICE_DEF_BY_NAME);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_SERVICE_DEFS);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_SERVICES);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.LOOKUP_RESOURCE);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.UPDATE_SERVICE);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.UPDATE_SERVICE_DEF);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.VALIDATE_CONFIG);
+
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_USER_PROFILE_FOR_USER);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.SEARCH_USERS);
+
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.COUNT_X_AUDIT_MAPS);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.COUNT_X_GROUP_GROUPS);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.COUNT_X_GROUPS);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.COUNT_X_GROUP_USERS);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.COUNT_X_PERM_MAPS);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.COUNT_X_USERS);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.CREATE_X_AUDIT_MAP);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.CREATE_X_PERM_MAP);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.DELETE_X_AUDIT_MAP);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.DELETE_X_PERM_MAP);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_X_AUDIT_MAP);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_X_GROUP);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_X_GROUP_BY_GROUP_NAME);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_X_GROUP_GROUP);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_X_GROUP_USER);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_X_GROUP_USERS);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_X_PERM_MAP);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_X_USER);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_X_USER_BY_USER_NAME);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_X_USER_GROUPS);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.MODIFY_GROUPS_VISIBILITY);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.MODIFY_USER_ACTIVE_STATUS);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.MODIFY_USER_VISIBILITY);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.SEARCH_X_AUDIT_MAPS);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.SEARCH_X_GROUP_GROUPS);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.SEARCH_X_GROUPS);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.SEARCH_X_GROUP_USERS);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.SEARCH_X_PERM_MAPS);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.SEARCH_X_USERS);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.SECURE_GET_X_GROUP);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.SECURE_GET_X_USER);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.UPDATE_X_AUDIT_MAP);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.UPDATE_X_PERM_MAP);
+
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.CREATE);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.CREATE_DEFAULT_ACCOUNT_USER);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.UPDATE);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.SET_USER_ROLES);
+ apiAssociatedWithTagBasedPolicy.add(RangerAPIList.DEACTIVATE_USER);
+
+ rangerAPIMappingWithUI.put(TAB_TAG_BASED_POLICIES, apiAssociatedWithTagBasedPolicy);
+
+ for (String api : apiAssociatedWithTagBasedPolicy) {
+ if (mapApiToTabs.get(api) == null) {
+ mapApiToTabs.put(api, new HashSet());
+ }
+ mapApiToTabs.get(api).add(TAB_TAG_BASED_POLICIES);
+ }
+ }
+
+ private void mapKeyManagerWithAPIs() {
+
+ Set apiAssociatedWithKeyManager = new HashSet();
+
+ apiAssociatedWithKeyManager.add(RangerAPIList.COUNT_X_ASSETS);
+ apiAssociatedWithKeyManager.add(RangerAPIList.CREATE_X_ASSET);
+ apiAssociatedWithKeyManager.add(RangerAPIList.DELETE_X_ASSET);
+ apiAssociatedWithKeyManager.add(RangerAPIList.GET_X_ASSET);
+ apiAssociatedWithKeyManager.add(RangerAPIList.SEARCH_X_ASSETS);
+ apiAssociatedWithKeyManager.add(RangerAPIList.TEST_CONFIG);
+ apiAssociatedWithKeyManager.add(RangerAPIList.UPDATE_X_ASSET);
+
+ apiAssociatedWithKeyManager.add(RangerAPIList.COUNT_SERVICES);
+ apiAssociatedWithKeyManager.add(RangerAPIList.CREATE_SERVICE);
+ apiAssociatedWithKeyManager.add(RangerAPIList.CREATE_SERVICE_DEF);
+ apiAssociatedWithKeyManager.add(RangerAPIList.DELETE_SERVICE);
+ apiAssociatedWithKeyManager.add(RangerAPIList.DELETE_SERVICE_DEF);
+ apiAssociatedWithKeyManager.add(RangerAPIList.GET_POLICY_FOR_VERSION_NO);
+ apiAssociatedWithKeyManager.add(RangerAPIList.GET_POLICY_FROM_EVENT_TIME);
+ apiAssociatedWithKeyManager.add(RangerAPIList.GET_POLICY_VERSION_LIST);
+ apiAssociatedWithKeyManager.add(RangerAPIList.GET_SERVICE);
+ apiAssociatedWithKeyManager.add(RangerAPIList.GET_SERVICE_BY_NAME);
+ apiAssociatedWithKeyManager.add(RangerAPIList.GET_SERVICE_DEF);
+ apiAssociatedWithKeyManager.add(RangerAPIList.GET_SERVICE_DEF_BY_NAME);
+ apiAssociatedWithKeyManager.add(RangerAPIList.GET_SERVICE_DEFS);
+ apiAssociatedWithKeyManager.add(RangerAPIList.GET_SERVICES);
+ apiAssociatedWithKeyManager.add(RangerAPIList.LOOKUP_RESOURCE);
+ apiAssociatedWithKeyManager.add(RangerAPIList.UPDATE_SERVICE);
+ apiAssociatedWithKeyManager.add(RangerAPIList.UPDATE_SERVICE_DEF);
+ apiAssociatedWithKeyManager.add(RangerAPIList.VALIDATE_CONFIG);
+
+ apiAssociatedWithKeyManager.add(RangerAPIList.CREATE_KEY);
+ apiAssociatedWithKeyManager.add(RangerAPIList.DELETE_KEY);
+ apiAssociatedWithKeyManager.add(RangerAPIList.GET_KEY);
+ apiAssociatedWithKeyManager.add(RangerAPIList.ROLLOVER_KEYS);
+ apiAssociatedWithKeyManager.add(RangerAPIList.SEARCH_KEYS);
+
+ rangerAPIMappingWithUI.put(TAB_KEY_MANAGER, apiAssociatedWithKeyManager);
+
+ for (String api : apiAssociatedWithKeyManager) {
+ if (mapApiToTabs.get(api) == null) {
+ mapApiToTabs.put(api, new HashSet());
+ }
+ mapApiToTabs.get(api).add(TAB_KEY_MANAGER);
+ }
+ }
+
+ private void mapPermissionsWithAPIs() {
+
+ Set apiAssociatedWithPermissions = new HashSet();
+
+ apiAssociatedWithPermissions.add(RangerAPIList.COUNT_X_GROUP_PERMISSION);
+ apiAssociatedWithPermissions.add(RangerAPIList.COUNT_X_MODULE_DEF);
+ apiAssociatedWithPermissions.add(RangerAPIList.COUNT_X_USER_PERMISSION);
+ apiAssociatedWithPermissions.add(RangerAPIList.CREATE_X_GROUP_PERMISSION);
+ apiAssociatedWithPermissions.add(RangerAPIList.CREATE_X_MODULE_DEF_PERMISSION);
+ apiAssociatedWithPermissions.add(RangerAPIList.CREATE_X_USER_PERMISSION);
+ apiAssociatedWithPermissions.add(RangerAPIList.DELETE_X_GROUP_PERMISSION);
+ apiAssociatedWithPermissions.add(RangerAPIList.DELETE_X_MODULE_DEF_PERMISSION);
+ apiAssociatedWithPermissions.add(RangerAPIList.DELETE_X_USER_PERMISSION);
+ apiAssociatedWithPermissions.add(RangerAPIList.GET_X_GROUP_PERMISSION);
+ apiAssociatedWithPermissions.add(RangerAPIList.GET_X_MODULE_DEF_PERMISSION);
+ apiAssociatedWithPermissions.add(RangerAPIList.GET_X_USER_PERMISSION);
+ apiAssociatedWithPermissions.add(RangerAPIList.SEARCH_X_GROUP_PERMISSION);
+ apiAssociatedWithPermissions.add(RangerAPIList.SEARCH_X_MODULE_DEF);
+ apiAssociatedWithPermissions.add(RangerAPIList.SEARCH_X_USER_PERMISSION);
+ apiAssociatedWithPermissions.add(RangerAPIList.UPDATE_X_GROUP_PERMISSION);
+ apiAssociatedWithPermissions.add(RangerAPIList.UPDATE_X_MODULE_DEF_PERMISSION);
+ apiAssociatedWithPermissions.add(RangerAPIList.UPDATE_X_USER_PERMISSION);
+
+ rangerAPIMappingWithUI.put(TAB_PERMISSIONS, apiAssociatedWithPermissions);
+
+ for (String api : apiAssociatedWithPermissions) {
+ if (mapApiToTabs.get(api) == null) {
+ mapApiToTabs.put(api, new HashSet());
+ }
+ mapApiToTabs.get(api).add(TAB_PERMISSIONS);
+ }
+ }
+
+ private void mapUGWithAPIs() {
+ Set apiAssociatedWithUserAndGroups = new HashSet();
+
+ apiAssociatedWithUserAndGroups.add(RangerAPIList.GET_USER_PROFILE_FOR_USER);
+ apiAssociatedWithUserAndGroups.add(RangerAPIList.SEARCH_USERS);
+
+ apiAssociatedWithUserAndGroups.add(RangerAPIList.COUNT_X_AUDIT_MAPS);
+ apiAssociatedWithUserAndGroups.add(RangerAPIList.COUNT_X_GROUP_GROUPS);
+ apiAssociatedWithUserAndGroups.add(RangerAPIList.COUNT_X_GROUPS);
+ apiAssociatedWithUserAndGroups.add(RangerAPIList.COUNT_X_GROUP_USERS);
+ apiAssociatedWithUserAndGroups.add(RangerAPIList.COUNT_X_PERM_MAPS);
+ apiAssociatedWithUserAndGroups.add(RangerAPIList.COUNT_X_USERS);
+ apiAssociatedWithUserAndGroups.add(RangerAPIList.CREATE_X_AUDIT_MAP);
+ apiAssociatedWithUserAndGroups.add(RangerAPIList.CREATE_X_PERM_MAP);
+ apiAssociatedWithUserAndGroups.add(RangerAPIList.DELETE_X_AUDIT_MAP);
+ apiAssociatedWithUserAndGroups.add(RangerAPIList.DELETE_X_PERM_MAP);
+ apiAssociatedWithUserAndGroups.add(RangerAPIList.GET_X_AUDIT_MAP);
+ apiAssociatedWithUserAndGroups.add(RangerAPIList.GET_X_GROUP);
+ apiAssociatedWithUserAndGroups.add(RangerAPIList.GET_X_GROUP_BY_GROUP_NAME);
+ apiAssociatedWithUserAndGroups.add(RangerAPIList.GET_X_GROUP_GROUP);
+ apiAssociatedWithUserAndGroups.add(RangerAPIList.GET_X_GROUP_USER);
+ apiAssociatedWithUserAndGroups.add(RangerAPIList.GET_X_GROUP_USERS);
+ apiAssociatedWithUserAndGroups.add(RangerAPIList.GET_X_PERM_MAP);
+ apiAssociatedWithUserAndGroups.add(RangerAPIList.GET_X_USER);
+ apiAssociatedWithUserAndGroups.add(RangerAPIList.GET_X_USER_BY_USER_NAME);
+ apiAssociatedWithUserAndGroups.add(RangerAPIList.GET_X_USER_GROUPS);
+ apiAssociatedWithUserAndGroups.add(RangerAPIList.MODIFY_GROUPS_VISIBILITY);
+ apiAssociatedWithUserAndGroups.add(RangerAPIList.MODIFY_USER_ACTIVE_STATUS);
+ apiAssociatedWithUserAndGroups.add(RangerAPIList.MODIFY_USER_VISIBILITY);
+ apiAssociatedWithUserAndGroups.add(RangerAPIList.SEARCH_X_AUDIT_MAPS);
+ apiAssociatedWithUserAndGroups.add(RangerAPIList.SEARCH_X_GROUP_GROUPS);
+ apiAssociatedWithUserAndGroups.add(RangerAPIList.SEARCH_X_GROUPS);
+ apiAssociatedWithUserAndGroups.add(RangerAPIList.SEARCH_X_GROUP_USERS);
+ apiAssociatedWithUserAndGroups.add(RangerAPIList.SEARCH_X_PERM_MAPS);
+ apiAssociatedWithUserAndGroups.add(RangerAPIList.SEARCH_X_USERS);
+ apiAssociatedWithUserAndGroups.add(RangerAPIList.SECURE_GET_X_GROUP);
+ apiAssociatedWithUserAndGroups.add(RangerAPIList.SECURE_GET_X_USER);
+ apiAssociatedWithUserAndGroups.add(RangerAPIList.UPDATE_X_AUDIT_MAP);
+ apiAssociatedWithUserAndGroups.add(RangerAPIList.UPDATE_X_PERM_MAP);
+
+ apiAssociatedWithUserAndGroups.add(RangerAPIList.CREATE);
+ apiAssociatedWithUserAndGroups.add(RangerAPIList.CREATE_DEFAULT_ACCOUNT_USER);
+ apiAssociatedWithUserAndGroups.add(RangerAPIList.UPDATE);
+ apiAssociatedWithUserAndGroups.add(RangerAPIList.SET_USER_ROLES);
+ apiAssociatedWithUserAndGroups.add(RangerAPIList.DEACTIVATE_USER);
+
+ rangerAPIMappingWithUI.put(TAB_USERS_GROUPS, apiAssociatedWithUserAndGroups);
+
+ for (String api : apiAssociatedWithUserAndGroups) {
+ if (mapApiToTabs.get(api) == null) {
+ mapApiToTabs.put(api, new HashSet());
+ }
+ mapApiToTabs.get(api).add(TAB_USERS_GROUPS);
+ }
+ }
+
+ private void mapAuditWithAPIs() {
+
+ Set apiAssociatedWithAudit = new HashSet();
+
+ apiAssociatedWithAudit.add(RangerAPIList.COUNT_X_ASSETS);
+ apiAssociatedWithAudit.add(RangerAPIList.GET_X_ASSET);
+ apiAssociatedWithAudit.add(RangerAPIList.SEARCH_X_ASSETS);
+
+ apiAssociatedWithAudit.add(RangerAPIList.COUNT_SERVICES);
+ apiAssociatedWithAudit.add(RangerAPIList.GET_POLICY_FOR_VERSION_NO);
+ apiAssociatedWithAudit.add(RangerAPIList.GET_POLICY_FROM_EVENT_TIME);
+ apiAssociatedWithAudit.add(RangerAPIList.GET_POLICY_VERSION_LIST);
+ apiAssociatedWithAudit.add(RangerAPIList.GET_SERVICE);
+ apiAssociatedWithAudit.add(RangerAPIList.GET_SERVICE_BY_NAME);
+ apiAssociatedWithAudit.add(RangerAPIList.GET_SERVICE_DEF);
+ apiAssociatedWithAudit.add(RangerAPIList.GET_SERVICE_DEF_BY_NAME);
+ apiAssociatedWithAudit.add(RangerAPIList.GET_SERVICE_DEFS);
+ apiAssociatedWithAudit.add(RangerAPIList.GET_SERVICES);
+ apiAssociatedWithAudit.add(RangerAPIList.LOOKUP_RESOURCE);
+
+ apiAssociatedWithAudit.add(RangerAPIList.GET_USER_PROFILE_FOR_USER);
+ apiAssociatedWithAudit.add(RangerAPIList.SEARCH_USERS);
+
+ apiAssociatedWithAudit.add(RangerAPIList.COUNT_X_AUDIT_MAPS);
+ apiAssociatedWithAudit.add(RangerAPIList.COUNT_X_GROUP_GROUPS);
+ apiAssociatedWithAudit.add(RangerAPIList.COUNT_X_GROUPS);
+ apiAssociatedWithAudit.add(RangerAPIList.COUNT_X_GROUP_USERS);
+ apiAssociatedWithAudit.add(RangerAPIList.COUNT_X_PERM_MAPS);
+ apiAssociatedWithAudit.add(RangerAPIList.COUNT_X_USERS);
+ apiAssociatedWithAudit.add(RangerAPIList.GET_X_AUDIT_MAP);
+ apiAssociatedWithAudit.add(RangerAPIList.GET_X_GROUP);
+ apiAssociatedWithAudit.add(RangerAPIList.GET_X_GROUP_BY_GROUP_NAME);
+ apiAssociatedWithAudit.add(RangerAPIList.GET_X_GROUP_GROUP);
+ apiAssociatedWithAudit.add(RangerAPIList.GET_X_GROUP_USER);
+ apiAssociatedWithAudit.add(RangerAPIList.GET_X_GROUP_USERS);
+ apiAssociatedWithAudit.add(RangerAPIList.GET_X_PERM_MAP);
+ apiAssociatedWithAudit.add(RangerAPIList.GET_X_USER);
+ apiAssociatedWithAudit.add(RangerAPIList.GET_X_USER_BY_USER_NAME);
+ apiAssociatedWithAudit.add(RangerAPIList.GET_X_USER_GROUPS);
+ apiAssociatedWithAudit.add(RangerAPIList.SEARCH_X_AUDIT_MAPS);
+ apiAssociatedWithAudit.add(RangerAPIList.SEARCH_X_GROUP_GROUPS);
+ apiAssociatedWithAudit.add(RangerAPIList.SEARCH_X_GROUPS);
+ apiAssociatedWithAudit.add(RangerAPIList.SEARCH_X_GROUP_USERS);
+ apiAssociatedWithAudit.add(RangerAPIList.SEARCH_X_PERM_MAPS);
+ apiAssociatedWithAudit.add(RangerAPIList.SEARCH_X_USERS);
+ apiAssociatedWithAudit.add(RangerAPIList.SECURE_GET_X_GROUP);
+ apiAssociatedWithAudit.add(RangerAPIList.SECURE_GET_X_USER);
+
+ apiAssociatedWithAudit.add(RangerAPIList.GET_X_TRX_LOG);
+ apiAssociatedWithAudit.add(RangerAPIList.CREATE_X_TRX_LOG);
+ apiAssociatedWithAudit.add(RangerAPIList.UPDATE_X_TRX_LOG);
+ apiAssociatedWithAudit.add(RangerAPIList.DELETE_X_TRX_LOG);
+ apiAssociatedWithAudit.add(RangerAPIList.SEARCH_X_TRX_LOG);
+ apiAssociatedWithAudit.add(RangerAPIList.COUNT_X_TRX_LOGS);
+ apiAssociatedWithAudit.add(RangerAPIList.SEARCH_X_ACCESS_AUDITS);
+ apiAssociatedWithAudit.add(RangerAPIList.COUNT_X_ACCESS_AUDITS);
+ apiAssociatedWithAudit.add(RangerAPIList.SEARCH_X_POLICY_EXPORT_AUDITS);
+ apiAssociatedWithAudit.add(RangerAPIList.GET_REPORT_LOGS);
+ apiAssociatedWithAudit.add(RangerAPIList.GET_TRANSACTION_REPORT);
+ apiAssociatedWithAudit.add(RangerAPIList.GET_ACCESS_LOGS);
+ apiAssociatedWithAudit.add(RangerAPIList.GET_AUTH_SESSION);
+ apiAssociatedWithAudit.add(RangerAPIList.GET_AUTH_SESSIONS);
+
+ rangerAPIMappingWithUI.put(TAB_AUDIT, apiAssociatedWithAudit);
+
+ for (String api : apiAssociatedWithAudit) {
+ if (mapApiToTabs.get(api) == null) {
+ mapApiToTabs.put(api, new HashSet());
+ }
+ mapApiToTabs.get(api).add(TAB_AUDIT);
+ }
+ }
+
+ private void mapResourceBasedPoliciesWithAPIs() {
+ Set apiAssociatedWithRBPolicies = new HashSet();
+
+ apiAssociatedWithRBPolicies.add(RangerAPIList.COUNT_X_ASSETS);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.CREATE_X_ASSET);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.DELETE_X_ASSET);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.GET_X_ASSET);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.SEARCH_X_ASSETS);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.TEST_CONFIG);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.UPDATE_X_ASSET);
+
+ apiAssociatedWithRBPolicies.add(RangerAPIList.COUNT_SERVICES);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.CREATE_SERVICE);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.CREATE_SERVICE_DEF);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.DELETE_SERVICE);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.DELETE_SERVICE_DEF);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.GET_POLICY_FOR_VERSION_NO);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.GET_POLICY_FROM_EVENT_TIME);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.GET_POLICY_VERSION_LIST);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.GET_SERVICE);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.GET_SERVICE_BY_NAME);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.GET_SERVICE_DEF);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.GET_SERVICE_DEF_BY_NAME);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.GET_SERVICE_DEFS);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.GET_SERVICES);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.LOOKUP_RESOURCE);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.UPDATE_SERVICE);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.UPDATE_SERVICE_DEF);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.VALIDATE_CONFIG);
+
+ apiAssociatedWithRBPolicies.add(RangerAPIList.GET_USER_PROFILE_FOR_USER);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.SEARCH_USERS);
+
+ apiAssociatedWithRBPolicies.add(RangerAPIList.COUNT_X_AUDIT_MAPS);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.COUNT_X_GROUP_GROUPS);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.COUNT_X_GROUPS);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.COUNT_X_GROUP_USERS);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.COUNT_X_PERM_MAPS);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.COUNT_X_USERS);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.CREATE_X_AUDIT_MAP);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.CREATE_X_PERM_MAP);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.DELETE_X_AUDIT_MAP);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.DELETE_X_PERM_MAP);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.GET_X_AUDIT_MAP);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.GET_X_GROUP);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.GET_X_GROUP_BY_GROUP_NAME);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.GET_X_GROUP_GROUP);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.GET_X_GROUP_USER);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.GET_X_GROUP_USERS);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.GET_X_PERM_MAP);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.GET_X_USER);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.GET_X_USER_BY_USER_NAME);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.GET_X_USER_GROUPS);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.MODIFY_GROUPS_VISIBILITY);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.MODIFY_USER_ACTIVE_STATUS);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.MODIFY_USER_VISIBILITY);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.SEARCH_X_AUDIT_MAPS);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.SEARCH_X_GROUP_GROUPS);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.SEARCH_X_GROUPS);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.SEARCH_X_GROUP_USERS);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.SEARCH_X_PERM_MAPS);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.SEARCH_X_USERS);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.SECURE_GET_X_GROUP);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.SECURE_GET_X_USER);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.UPDATE_X_AUDIT_MAP);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.UPDATE_X_PERM_MAP);
+
+ apiAssociatedWithRBPolicies.add(RangerAPIList.CREATE);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.CREATE_DEFAULT_ACCOUNT_USER);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.UPDATE);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.SET_USER_ROLES);
+ apiAssociatedWithRBPolicies.add(RangerAPIList.DEACTIVATE_USER);
+
+ rangerAPIMappingWithUI.put(TAB_RESOURCE_BASED_POLICIES, apiAssociatedWithRBPolicies);
+
+ for (String api : apiAssociatedWithRBPolicies) {
+ if (mapApiToTabs.get(api) == null) {
+ mapApiToTabs.put(api, new HashSet());
+ }
+ mapApiToTabs.get(api).add(TAB_RESOURCE_BASED_POLICIES);
+ }
+ }
+
+ // * Utility methods starts from here, to retrieve API-UItab mapping information *
+
+ public Set getAvailableUITabs() {
+ if (CollectionUtils.isEmpty(tabList)) {
+ populateAvailableUITabs();
+ }
+ return tabList;
+ }
+
+ /**
+ * @param apiName
+ * @return
+ *
+ * @Note: apiName being passed to this function should strictly follow this format: {ClassName}.{apiMethodName} and also API should be listed into
+ * RangerAPIList and should be mapped properly with UI tabs in the current class.
+ */
+ public Set getAssociatedTabsWithAPI(String apiName) {
+ Set associatedTabs = mapApiToTabs.get(apiName);
+ return associatedTabs;
+ }
+}
diff --git a/security-admin/src/main/java/org/apache/ranger/security/context/RangerPreAuthSecurityHandler.java b/security-admin/src/main/java/org/apache/ranger/security/context/RangerPreAuthSecurityHandler.java
new file mode 100644
index 00000000000..6d132e6c751
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/security/context/RangerPreAuthSecurityHandler.java
@@ -0,0 +1,93 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.ranger.security.context;
+
+import java.util.List;
+import java.util.Set;
+
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.log4j.Logger;
+import org.apache.ranger.common.ContextUtil;
+import org.apache.ranger.common.MessageEnums;
+import org.apache.ranger.common.RESTErrorUtil;
+import org.apache.ranger.common.UserSessionBase;
+import org.apache.ranger.db.RangerDaoManager;
+import org.apache.ranger.entity.XXUser;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+@Component("rangerPreAuthSecurityHandler")
+public class RangerPreAuthSecurityHandler {
+ Logger logger = Logger.getLogger(RangerPreAuthSecurityHandler.class);
+
+ @Autowired
+ RangerDaoManager daoManager;
+
+ @Autowired
+ RESTErrorUtil restErrorUtil;
+
+ @Autowired
+ RangerAPIMapping rangerAPIMapping;
+
+ public boolean isAPIAccessible(String methodName) throws Exception {
+
+ if (methodName == null) {
+ return false;
+ }
+
+ UserSessionBase userSession = ContextUtil.getCurrentUserSession();
+ if (userSession == null) {
+ logger.warn("WARNING: UserSession found null. Some non-authorized user might be trying to access the API.");
+ return false;
+ }
+
+ if (userSession.isUserAdmin()) {
+ if (logger.isDebugEnabled()) {
+ logger.debug("WARNING: Logged in user is System Admin, System Admin is allowed to access all the tabs except Key Manager."
+ + "Reason for returning true is, In few cases system admin needs to have access on Key Manager tabs as well.");
+ }
+ return true;
+ }
+
+ Set associatedTabs = rangerAPIMapping.getAssociatedTabsWithAPI(methodName);
+ if (CollectionUtils.isEmpty(associatedTabs)) {
+ return true;
+ }
+ return isAPIAccessible(associatedTabs);
+ }
+
+ public boolean isAPIAccessible(Set associatedTabs) throws Exception {
+
+ XXUser xUser = daoManager.getXXUser().findByUserName(ContextUtil.getCurrentUserLoginId());
+ if (xUser == null) {
+ restErrorUtil.createRESTException("x_user cannot be null.", MessageEnums.ERROR_SYSTEM);
+ }
+
+ List accessibleModules = daoManager.getXXModuleDef().findAccessibleModulesByUserId(ContextUtil.getCurrentUserId(), xUser.getId());
+ if (CollectionUtils.containsAny(accessibleModules, associatedTabs)) {
+ return true;
+ }
+
+ throw restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "User is not allowed to access the API", true);
+ }
+
+}
diff --git a/security-admin/src/main/java/org/apache/ranger/service/XAuditMapService.java b/security-admin/src/main/java/org/apache/ranger/service/XAuditMapService.java
index 1f48c8636cd..349ddbd6c90 100644
--- a/security-admin/src/main/java/org/apache/ranger/service/XAuditMapService.java
+++ b/security-admin/src/main/java/org/apache/ranger/service/XAuditMapService.java
@@ -24,16 +24,23 @@
import java.util.HashMap;
import java.util.List;
+import org.apache.ranger.biz.RangerBizUtil;
import org.apache.ranger.common.AppConstants;
+import org.apache.ranger.common.ContextUtil;
+import org.apache.ranger.common.SearchCriteria;
import org.apache.ranger.common.SearchField;
+import org.apache.ranger.common.UserSessionBase;
import org.apache.ranger.common.view.VTrxLogAttr;
import org.apache.ranger.db.RangerDaoManager;
import org.apache.ranger.entity.XXAuditMap;
import org.apache.ranger.entity.XXPortalUser;
+import org.apache.ranger.entity.XXResource;
import org.apache.ranger.entity.XXTrxLog;
import org.apache.ranger.entity.XXUser;
import org.apache.ranger.util.RangerEnumUtil;
import org.apache.ranger.view.VXAuditMap;
+import org.apache.ranger.view.VXAuditMapList;
+import org.apache.ranger.view.VXResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
@@ -48,6 +55,12 @@ public class XAuditMapService extends
@Autowired
RangerDaoManager rangerDaoManager;
+
+ @Autowired
+ RangerBizUtil rangerBizUtil;
+
+ @Autowired
+ XResourceService xResourceService;
static HashMap trxLogAttrs = new HashMap();
static {
@@ -186,4 +199,51 @@ protected VXAuditMap mapEntityToViewBean(VXAuditMap vObj, XXAuditMap mObj) {
}
return vObj;
}
+
+ @Override
+ public VXAuditMapList searchXAuditMaps(SearchCriteria searchCriteria) {
+
+ VXAuditMapList returnList;
+ UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession();
+ // If user is system admin
+ if (currentUserSession.isUserAdmin()) {
+ returnList = super.searchXAuditMaps(searchCriteria);
+ } else {
+ returnList = new VXAuditMapList();
+ int startIndex = searchCriteria.getStartIndex();
+ int pageSize = searchCriteria.getMaxRows();
+ searchCriteria.setStartIndex(0);
+ searchCriteria.setMaxRows(Integer.MAX_VALUE);
+ List resultList = (List) searchResources(searchCriteria, searchFields, sortFields, returnList);
+
+ List adminAuditResourceList = new ArrayList();
+ for (XXAuditMap xXAuditMap : resultList) {
+ XXResource xRes = daoManager.getXXResource().getById(xXAuditMap.getResourceId());
+ VXResponse vXResponse = rangerBizUtil.hasPermission(xResourceService.populateViewBean(xRes), AppConstants.XA_PERM_TYPE_ADMIN);
+ if (vXResponse.getStatusCode() == VXResponse.STATUS_SUCCESS) {
+ adminAuditResourceList.add(xXAuditMap);
+ }
+ }
+
+ if (adminAuditResourceList.size() > 0) {
+ populatePageList(adminAuditResourceList, startIndex, pageSize, returnList);
+ }
+ }
+
+ return returnList;
+ }
+
+ private void populatePageList(List auditMapList, int startIndex, int pageSize, VXAuditMapList vxAuditMapList) {
+ List onePageList = new ArrayList();
+ for (int i = startIndex; i < pageSize + startIndex && i < auditMapList.size(); i++) {
+ VXAuditMap vXAuditMap = populateViewBean(auditMapList.get(i));
+ onePageList.add(vXAuditMap);
+ }
+ vxAuditMapList.setVXAuditMaps(onePageList);
+ vxAuditMapList.setStartIndex(startIndex);
+ vxAuditMapList.setPageSize(pageSize);
+ vxAuditMapList.setResultSize(onePageList.size());
+ vxAuditMapList.setTotalCount(auditMapList.size());
+ }
+
}
diff --git a/security-admin/src/main/java/org/apache/ranger/service/XPermMapService.java b/security-admin/src/main/java/org/apache/ranger/service/XPermMapService.java
index 7e5eb10612d..6d961070b9d 100644
--- a/security-admin/src/main/java/org/apache/ranger/service/XPermMapService.java
+++ b/security-admin/src/main/java/org/apache/ranger/service/XPermMapService.java
@@ -24,20 +24,25 @@
import java.util.HashMap;
import java.util.List;
+import org.apache.ranger.biz.RangerBizUtil;
import org.apache.ranger.common.AppConstants;
+import org.apache.ranger.common.ContextUtil;
import org.apache.ranger.common.SearchCriteria;
import org.apache.ranger.common.SearchField;
+import org.apache.ranger.common.UserSessionBase;
import org.apache.ranger.common.view.VTrxLogAttr;
import org.apache.ranger.db.RangerDaoManager;
import org.apache.ranger.entity.XXGroup;
import org.apache.ranger.entity.XXPermMap;
import org.apache.ranger.entity.XXPortalUser;
+import org.apache.ranger.entity.XXResource;
import org.apache.ranger.entity.XXTrxLog;
import org.apache.ranger.entity.XXUser;
import org.apache.ranger.util.RangerEnumUtil;
import org.apache.ranger.view.VXGroup;
import org.apache.ranger.view.VXPermMap;
import org.apache.ranger.view.VXPermMapList;
+import org.apache.ranger.view.VXResponse;
import org.apache.ranger.view.VXUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
@@ -59,6 +64,12 @@ public class XPermMapService extends XPermMapServiceBase {
@Autowired
RangerDaoManager rangerDaoManager;
+ @Autowired
+ RangerBizUtil rangerBizUtil;
+
+ @Autowired
+ XResourceService xResourceService;
+
static HashMap trxLogAttrs = new HashMap();
static {
// trxLogAttrs.put("groupId", new VTrxLogAttr("groupId", "Group Permission", false));
@@ -112,19 +123,48 @@ public VXPermMap populateViewBean(XXPermMap xXPermMap){
@Override
public VXPermMapList searchXPermMaps(SearchCriteria searchCriteria) {
- VXPermMapList vXPermMapList = super.searchXPermMaps(searchCriteria);
- if(vXPermMapList != null && vXPermMapList.getResultSize() != 0){
- for(VXPermMap vXPermMap : vXPermMapList.getVXPermMaps()){
- if(vXPermMap.getPermFor() == AppConstants.XA_PERM_FOR_GROUP) {
- String groupName = getGroupName(vXPermMap.getGroupId());
- vXPermMap.setGroupName(groupName);
- } else if(vXPermMap.getPermFor() == AppConstants.XA_PERM_FOR_USER) {
- String username = getUserName(vXPermMap.getUserId());
- vXPermMap.setUserName(username);
+
+
+ VXPermMapList returnList;
+ UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession();
+ // If user is system admin
+ if (currentUserSession.isUserAdmin()) {
+ returnList = super.searchXPermMaps(searchCriteria);
+ } else {
+ returnList = new VXPermMapList();
+ int startIndex = searchCriteria.getStartIndex();
+ int pageSize = searchCriteria.getMaxRows();
+ searchCriteria.setStartIndex(0);
+ searchCriteria.setMaxRows(Integer.MAX_VALUE);
+ List resultList = (List) searchResources(searchCriteria, searchFields, sortFields, returnList);
+
+ List adminPermResourceList = new ArrayList();
+ for (XXPermMap xXPermMap : resultList) {
+ XXResource xRes = daoManager.getXXResource().getById(xXPermMap.getResourceId());
+ VXResponse vXResponse = rangerBizUtil.hasPermission(xResourceService.populateViewBean(xRes), AppConstants.XA_PERM_TYPE_ADMIN);
+ if (vXResponse.getStatusCode() == VXResponse.STATUS_SUCCESS) {
+ adminPermResourceList.add(xXPermMap);
}
}
+
+ if (adminPermResourceList.size() > 0) {
+ populatePageList(adminPermResourceList, startIndex, pageSize, returnList);
+ }
+ }
+ return returnList;
+ }
+
+ private void populatePageList(List permMapList, int startIndex, int pageSize, VXPermMapList vxPermMapList) {
+ List onePageList = new ArrayList();
+ for (int i = startIndex; i < pageSize + startIndex && i < permMapList.size(); i++) {
+ VXPermMap vXPermMap = populateViewBean(permMapList.get(i));
+ onePageList.add(vXPermMap);
}
- return vXPermMapList;
+ vxPermMapList.setVXPermMaps(onePageList);
+ vxPermMapList.setStartIndex(startIndex);
+ vxPermMapList.setPageSize(pageSize);
+ vxPermMapList.setResultSize(onePageList.size());
+ vxPermMapList.setTotalCount(permMapList.size());
}
public String getGroupName(Long groupId){
diff --git a/security-admin/src/main/java/org/apache/ranger/service/XResourceService.java b/security-admin/src/main/java/org/apache/ranger/service/XResourceService.java
index fa6679a1214..28e92820ea1 100644
--- a/security-admin/src/main/java/org/apache/ranger/service/XResourceService.java
+++ b/security-admin/src/main/java/org/apache/ranger/service/XResourceService.java
@@ -43,6 +43,7 @@
import org.apache.ranger.common.view.VTrxLogAttr;
import org.apache.ranger.db.RangerDaoManager;
import org.apache.ranger.entity.XXAsset;
+import org.apache.ranger.entity.XXAuditMap;
import org.apache.ranger.entity.XXGroup;
import org.apache.ranger.entity.XXPermMap;
import org.apache.ranger.entity.XXPortalUser;
@@ -345,25 +346,25 @@ private void populateAssetProperties(VXResource vXResource) {
}
private void populateAuditList(VXResource vXResource) {
- SearchCriteria searchCriteria = new SearchCriteria();
- searchCriteria.addParam("resourceId", vXResource.getId());
- VXAuditMapList vXAuditMapList = xAuditMapService
- .searchXAuditMaps(searchCriteria);
- if (vXAuditMapList != null && vXAuditMapList.getResultSize() != 0) {
- List auditMapList = vXAuditMapList.getList();
- vXResource.setAuditList(auditMapList);
+
+ List xAuditMapList = daoManager.getXXAuditMap().findByResourceId(vXResource.getId());
+ List vXAuditMapList = new ArrayList();
+
+ for (XXAuditMap xAuditMap : xAuditMapList) {
+ vXAuditMapList.add(xAuditMapService.populateViewBean(xAuditMap));
}
+ vXResource.setAuditList(vXAuditMapList);
}
private void populatePermList(VXResource vXResource) {
- SearchCriteria searchCriteria = new SearchCriteria();
- searchCriteria.addParam("resourceId", vXResource.getId());
- VXPermMapList vXPermMapList = xPermMapService
- .searchXPermMaps(searchCriteria);
- if (vXPermMapList != null && vXPermMapList.getResultSize() != 0) {
- List