HBase分析之Ranger权限验证

HBase源码分析之权限验证中讲过了自带的simple认证方式,Apache有个项目,也提供了权限验证,就是Ranger。Ranger的安装方式比较复杂,具体看:https://cwiki.apache.org/confluence/display/RANGER/Apache+Ranger+0.5.0+Installation

个人感觉Ranger还是略显粗糙,和我预期的Apache顶级项目有差距。

Ranger的权限管理是通过RangerAuthorizationCoprocessor来实现的,实现了MasterObserver、RegionServerObserver、RegionObserver、BulkLoadObserver,各种回调。

和HBase的grant、revoke同步

配置中配置了grant、revoke的时候,是否相应的刷新ranger的标记位UpdateRangerPoliciesOnGrantRevoke

UpdateRangerPoliciesOnGrantRevoke = RangerConfiguration.getInstance().getBoolean(RangerHadoopConstants.HBASE_UPDATE_RANGER_POLICIES_ON_GRANT_REVOKE_PROP, RangerHadoopConstants.HBASE_UPDATE_RANGER_POLICIES_ON_GRANT_REVOKE_DEFAULT_VALUE);

RangerAuthorizationCoprocessor实现了CoprocessorService接口,将自己注册进去,监听grant、revoke。

@Override
public Service getService() {
    return AccessControlProtos.AccessControlService.newReflectiveService(this);
}

实现了这2个方法,在这2个方法中判断UpdateRangerPoliciesOnGrantRevoke如果为true,就更新下自己的配置。

/**
 * <code>rpc Grant(.GrantRequest) returns (.GrantResponse);</code>
 */
public abstract void grant(
    com.google.protobuf.RpcController controller,
    org.apache.hadoop.hbase.protobuf.generated.AccessControlProtos.GrantRequest request,
    com.google.protobuf.RpcCallback<org.apache.hadoop.hbase.protobuf.generated.AccessControlProtos.GrantResponse> done);

/**
 * <code>rpc Revoke(.RevokeRequest) returns (.RevokeResponse);</code>
 */
public abstract void revoke(
    com.google.protobuf.RpcController controller,
    org.apache.hadoop.hbase.protobuf.generated.AccessControlProtos.RevokeRequest request,
    com.google.protobuf.RpcCallback<org.apache.hadoop.hbase.protobuf.generated.AccessControlProtos.RevokeResponse> done);

Policy生效规则

各种操作之前调用evaluateAccess,代码简直裹脚布,总结起来就是判断了Namespace、table、column、qualifier的设置,将所有设置集中到AuthorizationSession中,然后调用AuthorizationSession的authorize,判断权限。

ColumnFamilyAccessResult evaluateAccess(String operation, Action action, 
                                    final RegionCoprocessorEnvironment env,
                                    final Map<byte[], ? extends Collection<?>> familyMap) 
  throws AccessDeniedException {
    String access = _authUtils.getAccess(action);
    User user = getActiveUser();
    String userName = _userUtils.getUserAsString(user);

    byte[] tableBytes = getTableName(env);
    if (tableBytes == null || tableBytes.length == 0) {
        throw new AccessDeniedException("Insufficient permissions for operation '" + operation + "',action: " + action);
    }
    String table = Bytes.toString(tableBytes);
    String clusterName = hbasePlugin.getClusterName();

    final String messageTemplate = "evaluateAccess: exiting: user[%s], Operation[%s], access[%s], families[%s], verdict[%s]";
    ColumnFamilyAccessResult result;
    if (canSkipAccessCheck(operation, access, table) || canSkipAccessCheck(operation, access, env)) {
        result = new ColumnFamilyAccessResult(true, true, null, null, null, null, null, null);
        return result;
    }

    // let's create a session that would be reused.  Set things on it that won't change.
    HbaseAuditHandler auditHandler = _factory.getAuditHandler();
    AuthorizationSession session = new AuthorizationSession(hbasePlugin)
            .operation(operation)
            .remoteAddress(getRemoteAddress())
            .auditHandler(auditHandler)
            .user(user)
            .access(access)
            .table(table)
            .clusterName(clusterName);
    Map<String, Set<String>> families = getColumnFamilies(familyMap);
    if (families == null || families.isEmpty()) {
        session.buildRequest()
            .authorize();
        boolean authorized = session.isAuthorized();
        String reason = "";
        if (!authorized) {
            reason = String.format("Insufficient permissions for user ‘%s',action: %s, tableName:%s, no column families found.", user.getName(), operation, table);
        }
        AuthzAuditEvent event = auditHandler.getAndDiscardMostRecentEvent(); // this could be null, of course, depending on audit settings of table.
        // if authorized then pass captured events as access allowed set else as access denied set.
        result = new ColumnFamilyAccessResult(authorized, authorized,
                    authorized ? Collections.singletonList(event) : null,
                    null, authorized ? null : event, reason, null, clusterName);
        return result;
    }

    boolean everythingIsAccessible = true;
    boolean somethingIsAccessible = false;
    /*
     * we would have to accumulate audits of all successful accesses and any one denial (which in our case ends up being the last denial)
     * We need to keep audit events for family level access check seperate because we don't want them logged in some cases.
     */
    List<AuthzAuditEvent> authorizedEvents = new ArrayList<AuthzAuditEvent>();
    List<AuthzAuditEvent> familyLevelAccessEvents = new ArrayList<AuthzAuditEvent>();
    AuthzAuditEvent deniedEvent = null;
    String denialReason = null;
    // we need to cache the auths results so that we can create a filter, if needed
    Map<String, Set<String>> columnsAccessAllowed = new HashMap<String, Set<String>>();
    Set<String> familesAccessAllowed = new HashSet<String>();
    Set<String> familesAccessDenied = new HashSet<String>();
    Set<String> familesAccessIndeterminate = new HashSet<String>();

    for (Map.Entry<String, Set<String>> anEntry : families.entrySet()) {
        String family = anEntry.getKey();
        session.columnFamily(family);
        Set<String> columns = anEntry.getValue();
        if (columns == null || columns.isEmpty()) {
            session.column(null) // zap stale column from prior iteration of this loop, if any
                .buildRequest()
                .authorize();
            AuthzAuditEvent auditEvent = auditHandler.getAndDiscardMostRecentEvent(); // capture it only for success
            if (session.isAuthorized()) {
                // we need to do 3 things: housekeeping, decide about audit events, building the results cache for filter
                somethingIsAccessible = true;
                familesAccessAllowed.add(family);
                if (auditEvent != null) {
                    familyLevelAccessEvents.add(auditEvent);
                }
            } else {
                everythingIsAccessible = false;
                if (auditEvent != null && deniedEvent == null) { // we need to capture just one denial event
                    deniedEvent = auditEvent;
                }

                session.resourceMatchingScope(RangerAccessRequest.ResourceMatchingScope.SELF_OR_DESCENDANTS)
                        .buildRequest()
                        .authorize();
                auditEvent = auditHandler.getAndDiscardMostRecentEvent(); // capture it only for failure
                if (session.isAuthorized()) {
                    // we need to do 3 things: housekeeping, decide about audit events, building the results cache for filter
                    somethingIsAccessible = true;
                    familesAccessIndeterminate.add(family);
                } else {
                    familesAccessDenied.add(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
                        deniedEvent = auditEvent;
                    }
                }
                // Restore the headMatch setting
                session.resourceMatchingScope(RangerAccessRequest.ResourceMatchingScope.SELF);
            }
        } else {
            Set<String> accessibleColumns = new HashSet<String>(); // will be used in to populate our results cache for the filter
            for (String column : columns) {
                session.column(column)
                    .buildRequest()
                    .authorize();
                AuthzAuditEvent auditEvent = auditHandler.getAndDiscardMostRecentEvent();
                if (session.isAuthorized()) {
                    // we need to do 3 things: housekeeping, capturing audit events, building the results cache for filter
                    somethingIsAccessible = true;
                    accessibleColumns.add(column);
                    if (auditEvent != null) {
                        authorizedEvents.add(auditEvent);
                    }
                } else {
                    everythingIsAccessible = false;
                    denialReason = String.format("Insufficient permissions for user ‘%s',action: %s, tableName:%s, family:%s, column: %s", user.getName(), operation, table, family, column);
                    if (auditEvent != null && deniedEvent == null) { // we need to capture just one denial event
                        deniedEvent = auditEvent;
                    }
                }
                if (!accessibleColumns.isEmpty()) {
                    columnsAccessAllowed.put(family, accessibleColumns);
                }
            }
        }
    }
    // Cache of auth results are encapsulated the in the filter. Not every caller of the function uses it - only preGet and preOpt will.
    RangerAuthorizationFilter filter = new RangerAuthorizationFilter(session, familesAccessAllowed, familesAccessDenied, familesAccessIndeterminate, columnsAccessAllowed);
    result = new ColumnFamilyAccessResult(everythingIsAccessible, somethingIsAccessible, authorizedEvents, familyLevelAccessEvents, deniedEvent, denialReason, filter, clusterName);
    return result;
}

authorize里会调用到RangerPolicyEngineImpl#isAccessAllowed(RangerAccessRequest request, RangerAccessResultProcessor resultProcessor)方法

@Override
public RangerAccessResult isAccessAllowed(RangerAccessRequest request, RangerAccessResultProcessor resultProcessor) {
   RangerAccessResult ret = isAccessAllowedNoAudit(request);

   updatePolicyUsageCounts(request, ret);

   if (resultProcessor != null) {
      resultProcessor.processResult(ret);
   }

   return ret;
}

RangerPolicyEngineImpl#isAccessAllowed中会从RangerPolicyRepository中查找该资源的所有Policy,遍历执行RangerDefaultPolicyEvaluator#evaluatePolicyItems,来进行评估是否有权限访问。遍历过程中如果发现了匹配的规则,决定了deny还是allow,遍历就会break。每一次的遍历先从denyEvaluators里查找匹配的deny权限,如果没有找到,就从allowEvaluators里查找匹配的allow权限。

protected void evaluatePolicyItems(RangerAccessRequest request, RangerAccessResult result, boolean isResourceMatch) {
    // 先看有没有匹配的deny记录
    RangerPolicyItemEvaluator matchedPolicyItem = getMatchingPolicyItem(request, denyEvaluators, denyExceptionEvaluators);

    // 再看有没有匹配的allow记录
    if (matchedPolicyItem == null && !result.getIsAllowed()) {
        matchedPolicyItem = getMatchingPolicyItem(request, allowEvaluators, allowExceptionEvaluators);
    }

    if (matchedPolicyItem != null) {
        RangerPolicy policy = getPolicy();
        if (matchedPolicyItem.getPolicyItemType() == RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_DENY) {
            if (isResourceMatch) {
                result.setIsAllowed(false);
                result.setPolicyId(policy.getId());
                result.setReason(matchedPolicyItem.getComments());
            }
        } else {
            if (!result.getIsAllowed()) {
                result.setIsAllowed(true);
                result.setPolicyId(policy.getId());
                result.setReason(matchedPolicyItem.getComments());
            }
        }
    }
}

配置更新

在RangerAuthorizationCoprocessor的start中创建了RangerHBasePlugin

@Override
public void start(CoprocessorEnvironment env) throws IOException {
   ...
   // create and initialize the plugin class
   RangerHBasePlugin plugin = hbasePlugin;

   if(plugin == null) {
      synchronized(RangerAuthorizationCoprocessor.class) {
         plugin = hbasePlugin;

         if(plugin == null) {
            plugin = new RangerHBasePlugin(appType);
            plugin.init();

            UpdateRangerPoliciesOnGrantRevoke = RangerConfiguration.getInstance().getBoolean(RangerHadoopConstants.HBASE_UPDATE_RANGER_POLICIES_ON_GRANT_REVOKE_PROP, RangerHadoopConstants.HBASE_UPDATE_RANGER_POLICIES_ON_GRANT_REVOKE_DEFAULT_VALUE);

            hbasePlugin = plugin;
         }
      }
   }
  ...
}

RangerHBasePlugin的init方法中创建了PolicyRefresher用于同步权限配置,默认刷新时间为30*1000ms,即30s一次主动拉取配置。

public void init() {
    ...
    long   pollingIntervalMs = RangerConfiguration.getInstance().getLong(propertyPrefix + ".policy.pollIntervalMs", 30 * 1000);
    ...
    refresher = new PolicyRefresher(this, serviceType, appId, serviceName, admin, pollingIntervalMs, cacheDir);
    refresher.setDaemon(true);
    refresher.startRefresher();
    ...
}

PolicyRefresher本质是一个Thread,在start之后,会执行run()方法,这里进入了一个loop,执行完一次配置拉取猴,线程sleep 30s。

public void run() {
   while(true) {
      loadPolicy();
      try {
         Thread.sleep(pollingIntervalMs);
      } catch(InterruptedException excp) {
         break;
      }
   }
}
private void loadPolicy() {
    try {
        // 拉取一次配置
        ServicePolicies svcPolicies = loadPolicyfromPolicyAdmin();

        if (svcPolicies == null) {
            // 启动时拉取失败会从缓存中再读取一次
            if (!policiesSetInPlugin) {
                svcPolicies = loadFromCache();
            }
        } else {
            // 写到缓存中
            saveToCache(svcPolicies);
        }

        // 生效配置
        if (svcPolicies != null) {
            plugIn.setPolicies(svcPolicies);
            policiesSetInPlugin = true;
            setLastActivationTimeInMillis(System.currentTimeMillis());
            lastKnownVersion = svcPolicies.getPolicyVersion();
        } else {
            if (!policiesSetInPlugin && !serviceDefSetInPlugin) {
                plugIn.setPolicies(null);
                serviceDefSetInPlugin = true;
            }
        }
    } catch (Exception excp) {
    }
}

配置读取到之后,会写入RangerBasePlugin,并重新new一个RangerPolicyRepository实例,配置作为构造函数的参数,放入了RangerPolicyRepository。

-END-

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 205,132评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,802评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,566评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,858评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,867评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,695评论 1 282
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,064评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,705评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,915评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,677评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,796评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,432评论 4 322
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,041评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,992评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,223评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,185评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,535评论 2 343

推荐阅读更多精彩内容

  • 知道了用户的机制,见HBase源码分析之用户,就可以对用户进行权限控制了,HBase提供了AccessContro...
    HZWong阅读 4,127评论 0 3
  • 一:shell执行: grant授权: 查看commands目录下grant.rb文件: 进入security.r...
    sunTengSt阅读 2,302评论 0 2
  • 一、Ranger概述 1.Ranger简介 Apache Ranger提供一个集中式安全管理框架, 并解决授权和审...
    便利蜂数据平台阅读 31,595评论 2 21
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,598评论 18 139
  • 番茄工作法就是把整个番茄比做每天。 分开好多瓣去吃。 每吃一瓣,就休息一下。 擦擦嘴。
    李冷冷灬阅读 233评论 0 0