Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3371426
  • 博文数量: 258
  • 博客积分: 9440
  • 博客等级: 少将
  • 技术积分: 6998
  • 用 户 组: 普通用户
  • 注册时间: 2009-05-03 10:28
个人简介

-- linux爱好者,业余时间热衷于分析linux内核源码 -- 目前主要研究云计算和虚拟化相关的技术,主要包括libvirt/qemu,openstack,opennebula架构和源码分析。 -- 第五届云计算大会演讲嘉宾 微博:@Marshal-Liu

文章分类

全部博文(258)

文章存档

2016年(1)

2015年(4)

2014年(16)

2013年(22)

2012年(41)

2011年(59)

2010年(40)

2009年(75)

分类: 云计算

2014-03-12 15:06:10

 1. openstack 鉴权简单介绍  
    众所周知,openstack通过keystone用来完成authenticate(认证),真正的鉴权(authorize)是在各个模块分别做的,具体实现为每个模块都有一个policy文件,叫policy.json,里面定义了鉴权用的rules。
    以nova为例,policy文件的位置在:/etc/nova/policy.json,下面先来看几条rules,了解其基本含义:
  1. "compute:create": "",                                             
  2. "compute:create:attach_network": "",
  3. "compute:create:attach_volume": "",
  4. "compute:create:forced_host": "is_admin:True",
  5. "compute:get_all": "",
  6. "compute:get_all_tenants": "",
  7. "compute:start": "rule:admin_or_owner",
  8. "compute:stop": "rule:admin_or_owner",
  9. "compute:unlock_override": "rule:admin_api",
语法规则为:rule:[result]
    rule:指这条规则是干啥的,通常对应一个action,以类似scope:action的形式给出,scope表示作用范围,action表示执行哪种操作
    result: 表示这条rule的判定结果或者如何进行判定,比如"compute:create:forced_host": "is_admin:True",如果执行此操作的用户具有admin角色(role),则这条结果的判定结果就是True。
另外,rule是可以嵌套的,比如"compute:stop": "rule:admin_or_owner",表示compute:stop这条规则的结果为admin_or_owner这条规则的结果,而admin_or_owner规则如下:
  1. "admin_or_owner": "is_admin:True or project_id:%(project_id)s",
如果调用这个操作的用户的角色是admin,就返回True,或者返回用户所属的project的id.

2. policy鉴权代码分析
针对每一个操作,都会经过一个叫@wrap_check_policy的decorator,以nova的resize操作为例,在执行真正的resize代码之前,先要经过一个叫@wrap_check_policy的装饰器来完成policy的check过程,具体参见后面的代码check_policy函数:
  1.     @wrap_check_policy
  2.     @check_instance_lock
  3.     @check_instance_cell
  4.     @check_instance_state(vm_state=[vm_states.ACTIVE, vm_states.STOPPED],
  5.                           task_state=[None])
  6.     def resize(self, context, instance, flavor_id=None,
  7.                **extra_instance_updates):
check_policy(context, action, target, scope='compute')函数有四个参数:
(1) context: 执行resize操作的上下文,其内容包括project_id, user_id, role,auth_token等信息,具体如下:
  1. {'project_name': u'demo', 'user_id': u'a51e07e52af24111973dd7e11ece97f3', 'roles': [u'admin'], 'timestamp': '2014-03-10T08:45:56.552624', 'auth_token': '851012cfd5ad220e02cc3bc61b31c5f5', 'remote_address': '10.2.45.133', 'quota_class': None, 'is_admin': True, 'tenant': u'999c9fb0d7684ce1913cac4cc6122e51', 'service_catalog': [{u'endpoints': [{u'adminURL': u'', u'region': u'RegionOne', u'id': u'0987e932f0a0408ca7a5a31200c8ac51', u'internalURL': u'', u'publicURL': u''}], u'endpoints_links': [], u'type': u'volume', u'name': u'cinder'}], 'request_id': 'req-292b93ac-0a2b-488e-8a51-ea734286b07c', 'instance_lock_checked': False, 'project_id': u'999c9fb0d7684ce1913cac4cc6122e51', 'user_name': u'admin', 'read_deleted': 'no', 'user': u'a51e07e52af24111973dd7e11ece97f3'}
(2) action:表示当前执行的操作是啥,这里就是resize
(3) target:操作针对的object是啥,这里就是instance id
(4) scope:当前操作的作用域是啥,主要为了与policy文件中定义的作用域匹配,这里为compute,即nova执行的操作

  1. def check_policy(context, action, target, scope='compute'):
  2.         _action = '%s:%s' % (scope, action)  ##这里拼接成policy.json的rule,即_action=compute:resize
  3.         nova.policy.enforce(context, _action, target)
  4. ------------------------------------------------------------------------------------------------------------------------
  5.     def enforce(context, action, target, do_raise=True):
  6.         """Verifies that the action is valid on the target in this context.

  7.            :param context: nova context
  8.            :param action: string representing the action to be checked
  9.                this should be colon separated for clarity.
  10.                i.e. ``compute:create_instance``,
  11.                ``compute:attach_volume``,
  12.                ``volume:attach_volume``
  13.            :param target: dictionary representing the object of the action
  14.                for object creation this should be a dictionary representing the
  15.                location of the object e.g. ``{'project_id': context.project_id}``
  16.            :param do_raise: if True (the default), raises PolicyNotAuthorized;
  17.                if False, returns False

  18.            :raises nova.exception.PolicyNotAuthorized: if verification fails
  19.                and do_raise is True.

  20.            :return: returns a non-False value (not necessarily "True") if
  21.                authorized, and the exact value False if not authorized and
  22.                do_raise is False.
  23.         """
  24.         init()   ##policy.json被cache到cache_info数据结构中,init()函数就是去检查policy.json是否已经被加载或修改过,如果cache_info结构为空,说明policy.json还没有加载过,则执行加载;如果policy.json被修改过,也会重新进行加载

  25.         credentials = context.to_dict()  ##将context转化成dictonary,就是上面context给出的内容,以便后面代码使用

  26.         # Add the exception arguments if asked to do a raise
  27.         extra = {}
  28.         if do_raise:
  29.             extra.update(exc=exception.PolicyNotAuthorized, action=action##增加no auth hook函数,即如果rule的结果为False,则执行no auth hook函数做一些处理

  30.         return policy.check(action, target, credentials, **extra)  ##进行policy的check
  31. --------------------------------------------------------------------------------------------------------------------
  32. def init():
  33.     global _POLICY_PATH
  34.     global _POLICY_CACHE
  35.     if not _POLICY_PATH:
  36.         _POLICY_PATH = CONF.policy_file
  37.         if not os.path.exists(_POLICY_PATH):
  38.             _POLICY_PATH = CONF.find_file(_POLICY_PATH)
  39.         if not _POLICY_PATH:
  40.             raise exception.ConfigNotFound(path=CONF.policy_file)
  41.     utils.read_cached_file(_POLICY_PATH, _POLICY_CACHE,
  42.                            reload_func=_set_rules) ##加载policy.json文件
  43. ----------------------------------------------------------------------------------------------------------------------

  44. def read_cached_file(filename, cache_info, reload_func=None):
  45.     """Read from a file if it has been modified.

  46.     :param cache_info: dictionary to hold opaque cache.
  47.     :param reload_func: optional function to be called with data when
  48.                         file is reloaded due to a modification.

  49.     :returns: data from file

  50.     """
  51.     mtime = os.path.getmtime(filename)  ###获取policy.json文件的modify time,如果与cache_info中的mtime不同,则说明文件被修改过,则执行重新加载
  52.     if not cache_info or mtime != cache_info.get('mtime'):
  53.         LOG.debug(_("Reloading cached file %s") % filename)
  54.         with open(filename) as fap:
  55.             cache_info['data'] = fap.read()
  56.         cache_info['mtime'] = mtime
  57.         if reload_func:
  58.             reload_func(cache_info['data'])
  59.     return cache_info['data']            ###返回加载后的policy.json文件的内容
  60. ---------------------------------------------------------------------------------------------------------------------------
  61. def check(rule, target, creds, exc=None, *args, **kwargs):
  62.     """
  63.     Checks authorization of a rule against the target and credentials.

  64.     :param rule: The rule to evaluate.
  65.     :param target: As much information about the object being operated
  66.                    on as possible, as a dictionary.
  67.     :param creds: As much information about the user performing the
  68.                   action as possible, as a dictionary.
  69.     :param exc: Class of the exception to raise if the check fails.
  70.                 Any remaining arguments passed to check() (both
  71.                 positional and keyword arguments) will be passed to
  72.                 the exception class. If exc is not provided, returns
  73.                 False.

  74.     :return: Returns False if the policy does not allow the action and
  75.              exc is not provided; otherwise, returns a value that
  76.              evaluates to True. Note: for rules using the "case"
  77.              expression, this True value will be the specified string
  78.              from the expression.
  79.     """

  80.     # Allow the rule to be a Check tree
  81.     if isinstance(rule, BaseCheck):
  82.         result = rule(target, creds)
  83.     elif not _rules:
  84.         # No rules to reference means we're going to fail closed
  85.         result = False
  86.     else:
  87.         try:
  88.             # Evaluate the rule
  89.             result = _rules[rule](target, creds)  ##没一条rule执行一个函数,这个对应关系记录在全局变量_rules
  90.         except KeyError:
  91.             # If the rule doesn't exist, fail closed
  92.             result = False

  93.     # If it is False, raise the exception if requested
  94.     if exc and result is False:
  95.         raise exc(*args, **kwargs)

  96.     return result
3. 总结
    之前一直以为修改了policy.json文件,需要重启service才能重新加载policy.json生效,通过分析代码,证明policy.json是动态更新的。另外,通过分析代码,也搞清楚了如何添加自定义的rule,以便实现更细粒度的rule,稍后会给出一个自己实现的例子。

微博: @Marshal-Liu
Email: ustcdylan@gmail.com


阅读(10230) | 评论(3) | 转发(1) |
给主人留下些什么吧!~~

lxh2why2017-12-19 14:28:17

你好   请问如何去添加自定义的rule?   是直接在配置文件policy.json就可以了吗?还是还需要改其他说明地方?

wangzy2082016-05-16 19:11:19

什么叫“添加自定义的rule”,是修改policy文件吗?

berserker19812015-04-15 14:46:48

楼主的博文大大加快了我自己分析代码的进度啊,不然真担心弄不完啊~~~