Extension of the Xen-API for managing the ACM policy (and others)
PATCH 3/3 Extension of the Xen-API for managing the ACM policy (and others)
This patch implements extensions for managing security policies in xend. The XSPolicy and ACMPolicy classes provide the interface for the Xen-API and implement the functionality described in the documentation.
Some of the xend-internal code implements changing the previously used format into the format used by the Xen-API. This is mostly related to the labels and their format of <policy identifier>:<policy name>:<label>.
The acmpolicy class implements a compiler for translating an XML policy into their binary format and provides functionality for comparing a current policy against a new one when changing a policy.
The xspolicyadmin class administers the policy of the system.
--- xen-unstable.hg/tools/python/xen/xend/XendAPI.py | 287 ++- xen-unstable.hg/tools/python/xen/xend/XendConfig.py | 27 xen-unstable.hg/tools/python/xen/xend/XendDomainInfo.py | 182 + xen-unstable.hg/tools/python/xen/xend/XendError.py | 1 xen-unstable.hg/tools/python/xen/xend/XendVDI.py | 11 xen-unstable.hg/tools/python/xen/xend/server/blkif.py | 15 xen-unstable.hg/tools/python/xen/util/acmpolicy.py | 1130 ++++++++++++ xen-unstable.hg/tools/python/xen/util/bootloader.py | 377 ++++ xen-unstable.hg/tools/python/xen/util/security.py | 757 +++++++- xen-unstable.hg/tools/python/xen/util/xsconstants.py | 99 + xen-unstable.hg/tools/python/xen/util/xspolicy.py | 57 xen-unstable.hg/tools/python/xen/util/xspolicyadmin.py | 311 +++ xen-unstable.hg/tools/security/policies/security_policy.xsd | 29 13 files changed, 3155 insertions(+), 128 deletions(-)
xen-unstable.hg/tools/python/xen/xend/XendAPI.py +283 -6
@@ -47,6 +47,11 @@ from xen.util.xmlrpclib2 import stringif from xen.util.blkif import blkdev_name_to_number +from xen.util import xsconstants, xspolicy, security, dictio +from xen.util.acmpolicy import ACMPolicy +from xen.util.xspolicyadmin import XSPolicyAdminInstance +import base64 + AUTH_NONE = 'none' AUTH_PAM = 'pam'
@@ -427,6 +432,35 @@ def valid_object(class_name): XendAPIStore.get(r, class_name) is not None, 'PIF', func, *args, **kwargs) +def valid_xspolicy(func): + """Decorator to verify if xspolicy_ref is valid before calling + method. + + @param func: function with params: (self, session, xspolicy_ref) + @rtype: callable object + """ + def check_xspolicy_ref(self, session, xspolicy_ref, *args, **kwargs): + xennode = XendNode.instance() + xsadmin = XSPolicyAdminInstance() + if type(xspolicy_ref) == type(str()) and \ + xsadmin.has_ref(xspolicy_ref): + try: + xsadmin.lock_policy(xspolicy_ref) + except: + return {'Status' : 'Failure', + 'ErrorDescription': "Could not lock policy."} + res = func(self, session, xspolicy_ref, *args, **kwargs) + xsadmin.unlock_policy(xspolicy_ref) + return res + else: + return {'Status': 'Failure', + 'ErrorDescription': XEND_ERROR_XSPOLICY_INVALID} + + if hasattr(func, 'api'): + check_xspolicy_ref.api = func.api + + return check_xspolicy_ref + # ----------------------------- # Bridge to Legacy XM API calls # -----------------------------
@@ -467,6 +501,8 @@ classes = { 'console' : valid_console, 'SR' : valid_sr, 'task' : valid_task, + 'XSPolicy' : valid_xspolicy, + 'ACMPolicy' : valid_xspolicy, 'debug' : valid_debug, 'network' : valid_object("network"), 'PIF' : valid_object("PIF"),
@@ -1161,7 +1197,8 @@ class XendAPI(object): 'HVM_boot_params', 'platform', 'PCI_bus', - 'other_config'] + 'other_config', + 'security_label'] VM_methods = [('clone', 'VM'), ('start', None),
@@ -1221,7 +1258,8 @@ class XendAPI(object): 'HVM_boot_params', 'platform', 'PCI_bus', - 'other_config'] + 'other_config', + 'security_label'] def VM_get(self, name, session, vm_ref): return xen_api_success(
@@ -1580,10 +1618,30 @@ class XendAPI(object): def VM_get_by_name_label(self, session, label): xendom = XendDomain.instance() dom = xendom.domain_lookup_nr(label) + log.info("Looked up %s, got %s." % (label,dom)) if dom: return xen_api_success([dom.get_uuid()]) return xen_api_success([]) - + + def VM_get_security_label(self, session, vm_ref): + dom = XendDomain.instance().get_vm_by_uuid(vm_ref) + if not dom: + return xen_api_error(['VM_HANDLE_INVALID', vm_ref]) + label = dom.get_security_label() + return xen_api_success(label) + + def VM_set_security_label(self, session, vm_ref, sec_label, old_label): + dom = XendDomain.instance().get_vm_by_uuid(vm_ref) + if not dom: + return xen_api_error(['VM_HANDLE_INVALID', vm_ref]) + (rc, errors, oldlabel, new_ssidref) = \ + dom.set_security_label(sec_label, old_label) + if rc < 0: + return xen_api_error(['XSERROR', xsconstants.xserr2string(-rc)]) + if rc == 0: + rc = new_ssidref + return xen_api_success(rc) + def VM_create(self, session, vm_struct): xendom = XendDomain.instance() domuuid = XendTask.log_progress(0, 100,
@@ -1636,8 +1694,10 @@ class XendAPI(object): 'other_config': xeninfo.info.get('other_config', {}), 'domid': domid is None and -1 or domid, 'is_control_domain': xeninfo.info['is_control_domain'], - 'metrics': xeninfo.get_metrics() + 'metrics': xeninfo.get_metrics(), + 'security_label': xeninfo.get_security_label(), } + log.info("PLATFORM = %s" % xeninfo.get_platform()) return xen_api_success(record) def VM_clean_reboot(self, session, vm_ref):
@@ -2067,7 +2127,8 @@ class XendAPI(object): 'virtual_size', 'sharable', 'read_only', - 'other_config'] + 'other_config', + 'security_label'] VDI_attr_inst = VDI_attr_ro + VDI_attr_rw VDI_methods = [('destroy', None)]
@@ -2175,13 +2236,24 @@ class XendAPI(object): xennode = XendNode.instance() return xen_api_success(xennode.get_vdi_by_name_label(name)) + def VDI_set_security_label(self, session, vdi_ref, sec_lab, old_lab): + vdi = XendNode.instance().get_vdi_by_uuid(vdi_ref) + rc = vdi.set_security_label(sec_lab, old_lab) + if rc < 0: + return xen_api_error(['XSERROR', xsconstants.xserr2string(-rc)]) + return xen_api_success(rc) + + def VDI_get_security_label(self, session, vdi_ref): + vdi = XendNode.instance().get_vdi_by_uuid(vdi_ref) + return xen_api_success(vdi.get_security_label()) # Xen API: Class VTPM # ---------------------------------------------------------------- VTPM_attr_rw = [ ] VTPM_attr_ro = ['VM', - 'backend'] + 'backend', + 'runtime_properties' ] VTPM_attr_inst = VTPM_attr_rw
@@ -2259,6 +2331,18 @@ class XendAPI(object): vtpms = reduce(lambda x, y: x + y, vtpms) return xen_api_success(vtpms) + def VTPM_get_runtime_properties(self, _, vtpm_ref): + xendom = XendDomain.instance() + dominfo = xendom.get_vm_with_dev_uuid('vtpm', vtpm_ref) + device = dominfo.get_dev_config_by_uuid('vtpm', vtpm_ref) + + try: + device_sxps = dominfo.getDeviceSxprs('vtpm') + device_dict = dict(device_sxps[0][1]) + return xen_api_success(device_dict) + except: + return xen_api_success({}) + # Xen API: Class console # ----------------------------------------------------------------
@@ -2466,6 +2550,199 @@ class XendAPI(object): def debug_get_record(self, session, debug_ref): return xen_api_success({'uuid': debug_ref}) + # Xen API: Class XSPolicy + # ---------------------------------------------------------------- + + XSPolicy_attr_inst = [ ] + + XSPolicy_funcs = [ ('get_xstype', 'int'), + ('set_xspolicy', 'int'), + ('get_xspolicy', 'struct'), + ('rm_xsbootpolicy', 'int'), + ('get_resource_label', 'string'), + ('set_resource_label', 'int'), + ('get_labeled_resources', 'map') ] + + XSPolicy_methods = [ ('activate_xspolicy', 'int') ] + + #Helper function - not exported + def xspolicy_from_ref(self, xs_ref): + poladmin = XSPolicyAdminInstance() + return poladmin.policy_from_ref(xs_ref) + + def XSPolicy_get_all(self, session): + refs = poladmin.get_policies_refs() + return xen_api_success(refs) + + def XSPolicy_get_record(self, session, xs_ref): + xspol = self.xspolicy_from_ref(xs_ref) + + xspol_record = { + 'uuid' : xs_ref, + 'flags' : XSPolicyAdminInstance().get_policy_flags(xspol), + 'repr' : xspol.toxml(), + 'type' : xspol.get_type(), + } + return xen_api_success(xspol_record) + + def XSPolicy_get_xstype(self, session): + return xen_api_success(XSPolicyAdminInstance().isXSEnabled()) + + def XSPolicy_set_xspolicy(self, session, xstype, xml, flags, overwrite): + ref = "" + try: + xstype = int(xstype) + except: + return xen_api_error(['INTERNAL_ERROR', "xstype must be an int"]) + try: + flags = int(flags) + except: + return xen_api_error(['INTERNAL_ERROR', "flags must be an int"]) + + polstate = { 'xs_ref' : "", 'repr' : "", 'type' : 0, + 'flags' : 0 , 'version': 0 , 'errors' : "", 'xserr' : 0 } + if xstype == xsconstants.XS_POLICY_ACM: + poladmin = XSPolicyAdminInstance() + try: + (xspol, rc, errors) = poladmin.add_acmpolicy_to_system( + xml, flags, + overwrite) + if rc != 0: + polstate.update( { 'xserr' : rc, + 'errors': base64.b64encode(errors) } ) + else: + ref = xspol.get_ref() + polstate = { + 'xs_ref' : ref, + 'flags' : poladmin.get_policy_flags(xspol), + 'type' : xstype, + 'repr' : "", + 'version': xspol.get_version(), + 'errors' : base64.b64encode(errors), + 'xserr' : rc, + } + except Exception, e: + return xen_api_error(['XSERROR', str(e)]) + else: + return xen_api_error(['INTERNAL_ERROR', 'Policy type unsupported']) + return xen_api_success(polstate) + + def XSPolicy_activate_xspolicy(self, session, xs_ref, flags): + try: + flags = int(flags) + except: + return xen_api_error(['INTERNAL_ERROR', "flags must be int"]) + rc = -xsconstants.XSERR_GENERAL_FAILURE + poladmin = XSPolicyAdminInstance() + xspol = self.xspolicy_from_ref(xs_ref) + if xspol: + try: + rc = poladmin.activate_xspolicy(xspol, flags) + except Exception, e: + log.info("Activate_policy: %s" % str(e)) + return xen_api_success(rc) + + def XSPolicy_get_xspolicy(self, session): + polstate = { 'xs_ref' : "", + 'repr' : "", + 'type' : 0, + 'flags' : 0, + 'version': "", + 'errors' : "", + 'xserr' : 0 } + poladmin = XSPolicyAdminInstance() + refs = poladmin.get_policies_refs() + # Will return one or no policy + if refs and len(refs) > 0: + xspol = None + try: + xspol = self.xspolicy_from_ref(refs[0]) + xspol.grab_lock() + + polstate = { + 'xs_ref' : refs[0], + 'repr' : xspol.toxml(), + 'type' : xspol.get_type(), + 'flags' : poladmin.get_policy_flags(xspol), + 'version': xspol.get_version(), + 'errors' : "", + 'xserr' : 0, + } + finally: + if xspol: + xspol.unlock() + return xen_api_success(polstate) + + def XSPolicy_rm_xsbootpolicy(self, session): + return xen_api_success(XSPolicyAdminInstance().rm_bootpolicy()) + + def XSPolicy_get_labeled_resources(self, session): + return xen_api_success(security.get_labeled_resources_xapi()) + + def XSPolicy_set_resource_label(self, session, resource, sec_lab, old_lab): + rc = security.set_resource_label_xapi(resource, sec_lab, old_lab) + return xen_api_success(rc) + + def XSPolicy_get_resource_label(self, session, resource): + res = security.get_resource_label_xapi(resource) + return xen_api_success(res) + + # Xen API: Class ACMPolicy + # ---------------------------------------------------------------- + + ACMPolicy_attr_ro = [ 'xml', + 'map', + 'binary', + 'header' ] + + ACMPolicy_attr_inst = [ ] + + ACMPolicy_funcs = [ ('get_domain_vmlabel', 'int') ] + + ACMPolicy_methods = [ ('vm_migrate_security_label', 'int') ] + + def ACMPolicy_get_record(self, session, xs_ref): + xspol = self.xspolicy_from_ref(xs_ref) + + polstate = { + 'uuid' : xs_ref, + 'flags' : XSPolicyAdminInstance().get_policy_flags(xspol), + 'repr' : xspol.toxml(), + 'type' : xspol.get_type(), + } + return xen_api_success(polstate) + + def ACMPolicy_get_header(self, session, xs_ref): + header = { + 'policyname' : "", 'policyurl' : "", 'reference' : "", + 'date' : "", 'namespaceurl' : "", 'version' : "", + } + xspol = self.xspolicy_from_ref(xs_ref) + if xspol: + header = xspol.get_header_fields_map() + return xen_api_success(header) + + def ACMPolicy_get_xml(self, session, xs_ref): + policyxml = "" + xspol = self.xspolicy_from_ref(xs_ref) + if xspol: + policyxml = xspol.toxml() + return xen_api_success(policyxml) + + def ACMPolicy_get_map(self, session, xs_ref): + policymap = "" + xspol = self.xspolicy_from_ref(xs_ref) + if xspol: + policymap = xspol.get_map() + return xen_api_success(policymap) + + def ACMPolicy_get_binary(self, session, xs_ref): + polb64 = "" + xspol = self.xspolicy_from_ref(xs_ref) + if xspol: + polbin = xspol.get_bin() + polb64 = base64.b64encode(polbin) + return xen_api_success(polb64) class XendAPIAsyncProxy: """ A redirector for Async.Class.function calls to XendAPI
xen-unstable.hg/tools/python/xen/xend/XendConfig.py +23 -4
@@ -157,6 +157,7 @@ XENAPI_CFG_TYPES = { 'platform': dict, 'tools_version': dict, 'other_config': dict, + 'security_label': str, } # List of legacy configuration keys that have no equivalent in the
@@ -419,9 +420,9 @@ class XendConfig(dict): self._memory_sanity_check() self['cpu_time'] = dominfo['cpu_time']/1e9 - # TODO: i don't know what the security stuff expects here if dominfo.get('ssidref'): self['security'] = [['ssidref', dominfo['ssidref']]] + self['shutdown_reason'] = dominfo['shutdown_reason'] # parse state into Xen API states
@@ -612,8 +613,27 @@ class XendConfig(dict): except ValueError, e: raise XendConfigError('cpus = %s: %s' % (cfg['cpus'], e)) - if 'security' in cfg and isinstance(cfg['security'], str): - cfg['security'] = sxp.from_string(cfg['security']) + if 'security' in cfg and not cfg.get('security_label'): + secinfo = cfg['security'] + if isinstance(secinfo, list): + # This list is formatted like this: + # [['access_control', ['policy', 'xm-test'],['label', 'red']], + # ['ssidref', 196611]] + policy = "" + label = "" + from xen.util import xsconstants + policytype = xsconstants.ACM_POLICY_ID + for idx in range(0, len(secinfo)): + if secinfo[idx][0] == "access_control": + for aidx in range(1, len(secinfo[idx])): + if secinfo[idx][aidx][0] == "policy": + policy = secinfo[idx][aidx][1] + if secinfo[idx][aidx][0] == "label": + label = secinfo[idx][aidx][1] + if label != "" and policy != "": + cfg['security_label'] = "%s:%s:%s" % \ + (policytype, policy, label) + del cfg['security'] old_state = sxp.child_value(sxp_cfg, 'state') if old_state:
@@ -756,7 +776,6 @@ class XendConfig(dict): self[sxp_arg] = val _set_cfg_if_exists('shadow_memory') - _set_cfg_if_exists('security') _set_cfg_if_exists('features') _set_cfg_if_exists('on_xend_stop') _set_cfg_if_exists('on_xend_start')
xen-unstable.hg/tools/python/xen/xend/XendDomainInfo.py +167 -15
213 lines not on this page · raw message
xen-unstable.hg/tools/python/xen/xend/server/blkif.py +11 -4
@@ -73,10 +73,17 @@ class BlkifController(DevController): back['uuid'] = uuid if security.on(): - (label, ssidref, policy) = security.get_res_security_details(uname) - back.update({'acm_label' : label, - 'acm_ssidref': str(ssidref), - 'acm_policy' : policy}) + (label, ssidref, policy) = \ + security.get_res_security_details(uname) + domain_label = self.vm.get_security_label() + if domain_label: + rc = security.res_security_check_xapi(label, ssidref, policy, + domain_label) + if rc == 0: + raise VmError("VM's access to block device '%s' denied." % + uname) + else: + raise VmError("VM must have a security label.") devid = blkif.blkdev_name_to_number(dev) if devid is None:
xen-unstable.hg/tools/python/xen/xend/XendError.py +1 -0
@@ -188,4 +188,5 @@ XEND_ERROR_VIF_INVALID = ('EVI XEND_ERROR_VTPM_INVALID = ('EVTPMINVALID', 'VTPM Invalid') XEND_ERROR_VDI_INVALID = ('EVDIINVALID', 'VDI Invalid') XEND_ERROR_SR_INVALID = ('ESRINVALID', 'SR Invalid') +XEND_ERROR_XSPOLICY_INVALID = ('EXSPOLICYINVALID', 'XS Invalid') XEND_ERROR_TODO = ('ETODO', 'Lazy Programmer Error')
xen-unstable.hg/tools/python/xen/util/xsconstants.py new file +99 -0
99 lines not on this page · raw message
xen-unstable.hg/tools/python/xen/xend/XendVDI.py +11 -0
@@ -23,6 +23,7 @@ import os from xen.util.xmlrpclib2 import stringify from xmlrpclib import dumps, loads +from xen.util import security KB = 1024 MB = 1024 * 1024
@@ -160,6 +161,16 @@ class XendVDI(AutoSaveObject): def get_location(self): raise NotImplementedError() + + def set_security_label(self, sec_lab, old_lab): + image = self.get_location() + from xen.xend.XendLogging import log + return security.set_resource_label_xapi(image, sec_lab, old_lab) + + def get_security_label(self): + image = self.get_location() + from xen.xend.XendLogging import log + return security.get_resource_label_xapi(image) class XendQCoWVDI(XendVDI):
xen-unstable.hg/tools/python/xen/util/security.py +123 -62
253 lines not on this page · raw message
def refresh_ssidref(config):
@@ -381,8 +442,9 @@ def refresh_ssidref(config):
err("Illegal field in access_control")
#verify policy is correct
if active_policy != policyname:
- err("Policy \'" + policyname + "\' in label does not match active policy \'"
- + active_policy +"\'!")
+ err("Policy \'" + str(policyname) +
+ "\' in label does not match active policy \'"
+ + str(active_policy) +"\'!")
new_ssidref = label2ssidref(labelname, policyname, 'dom') if not new_ssidref:
@@ -470,6 +532,25 @@ def get_decision(arg1, arg2):
err("Cannot determine decision (Invalid parameter).")
+def hv_chg_policy(bin_pol, del_array, chg_array):
+ """
+ Change the binary policy in the hypervisor + The 'del_array' and 'chg_array' give hints about deleted ssidrefs + and changed ssidrefs which can be due to deleted VM labels + or reordered VM labels + """ + rc = -xsconstants.XSERR_GENERAL_FAILURE + errors = "" + if not on():
+ err("No policy active.")
+ try:
+ rc, errors = acm.chgpolicy(bin_pol, del_array, chg_array)
+ except Exception, e:
+ pass
+ if (len(errors) > 0):
+ rc = -xsconstants.XSERR_HV_OP_FAILED
+ return rc, errors
+
def make_policy(policy_name):
policy_file = string.join(string.split(policy_name, "."), "/")
@@ -480,8 +561,6 @@ def make_policy(policy_name):
if ret:
err("Creating policy failed:\n" + output)
-
-
def load_policy(policy_name):
global active_policy
policy_file = policy_dir_prefix + "/" + string.join(string.split(policy_name, "."), "/")@@ -538,8 +617,8 @@ def list_labels(policy_name, condition):
def get_res_label(resource):
- """Returns resource label information (label, policy) if it exists.
- Otherwise returns null label and policy.
+ """Returns resource label information (policytype, label, policy) if
+ it exists. Otherwise returns null label and policy.
"""
def default_res_label():
ssidref = NULL_SSIDREF
@@ -547,23 +626,19 @@ def get_res_label(resource):
label = ssidref2label(ssidref)
else:
label = None
- return (label, 'NULL')
-
- (label, policy) = default_res_label()
+ return (xsconstants.ACM_POLICY_ID, 'NULL', label)
- # load the resource label file
- res_label_cache = {}
- try:- res_label_cache = dictio.dict_read("resources", res_label_filename)
- except:
- log.info("Resource label file not found.")
- return default_res_label()
- # find the resource information
- if res_label_cache.has_key(resource):
- (policy, label) = res_label_cache[resource]
+ tmp = get_resource_label(resource)
+ if len(tmp) == 2:
+ policytype = xsconstants.ACM_POLICY_ID
+ policy, label = tmp
+ elif len(tmp) == 3:
+ policytype, policy, label = tmp
+ else:
+ policytype, policy, label = default_res_label()
- return (label, policy)
+ return (policytype, label, policy)
def get_res_security_details(resource):
@@ -582,7 +657,7 @@ def get_res_security_details(resource):
(label, ssidref, policy) = default_security_details()
# find the entry associated with this resource
- (label, policy) = get_res_label(resource)
+ (policytype, label, policy) = get_res_label(resource)
if policy == 'NULL':
log.info("Resource label for "+resource+" not in file, using DEFAULT.") return default_security_details()
@@ -597,7 +672,7 @@ def get_res_security_details(resource):
return (label, ssidref, policy)
-def unify_resname(resource):
+def unify_resname(resource, mustexist=True):
"""Makes all resource locations absolute. In case of physical resources, '/dev/' is added to local file names"""
@@ -606,28 +681,53 @@ def unify_resname(resource):
# sanity check on resource name
try:
- (type, resfile) = resource.split(":", 1)
+ (typ, resfile) = resource.split(":", 1)
except:
err("Resource spec '%s' contains no ':' delimiter" % resource)- if type == "tap":
+ if typ == "tap":
try:
(subtype, resfile) = resfile.split(":")
except:
err("Resource spec '%s' contains no tap subtype" % resource)
- if type in ["phy", "tap"]: + import os + if typ in ["phy", "tap"]:
if not resfile.startswith("/"):
resfile = "/dev/" + resfile
+ if mustexist:
+ stats = os.lstat(resfile)
+ if stat.S_ISLNK(stats[stat.ST_MODE]):
+ resolved = os.readlink(resfile)
+ if resolved[0] != "/":
+ resfile = os.path.join(os.path.dirname(resfile), resolved)
+ resfile = os.path.abspath(resfile)
+ else:
+ resfile = resolved
+ stats = os.lstat(resfile)
+ if not (stat.S_ISBLK(stats[stat.ST_MODE])):
+ err("Invalid resource")
+
+ if typ in [ "file", "tap" ]:
+ if mustexist:
+ stats = os.lstat(resfile)
+ if stat.S_ISLNK(stats[stat.ST_MODE]):
+ resfile = os.readlink(resfile)
+ stats = os.lstat(resfile)
+ if not stat.S_ISREG(stats[stat.ST_MODE]):
+ err("Invalid resource")
#file: resources must specified with absolute path
- if (not resfile.startswith("/")) or (not os.path.exists(resfile)):
- err("Invalid resource.")
+ #vlan resources don't start with '/'
+ if typ != "vlan":
+ if (not resfile.startswith("/")) or \
+ (mustexist and not os.path.exists(resfile)):
+ err("Invalid resource.")
# from here on absolute file names with resources
- if type == "tap":
- type = type + ":" + subtype
- resource = type + ":" + resfile
+ if typ == "tap":
+ typ = typ + ":" + subtype
+ resource = typ + ":" + resfile
return resource@@ -662,9 +762,480 @@ def res_security_check(resource, domain_
else:
# Note, we can't canonicalise the resource here, because people using # xm without ACM are free to use relative paths.
- (label, policy) = get_res_label(resource)
+ (policytype, label, policy) = get_res_label(resource)
if policy != 'NULL':
raise ACMError("Security is off, but '"+resource+"' is labeled") rtnval = 0
return rtnval
+
+def res_security_check_xapi(rlabel, rssidref, rpolicy, xapi_dom_label):
+ """Checks if the given resource can be used by the given domain
+ label. Returns 1 if the resource can be used, otherwise 0.
+ """ + rtnval = 1 + # if security is on, ask the hypervisor for a decision + if on():
+ typ, dpolicy, domain_label = xapi_dom_label.split(":")
+ if not dpolicy or not domain_label:
+ raise VmError("VM security label in wrong format.")
+ if active_policy != rpolicy:
+ raise VmError("Resource's policy '%s' != active policy '%s'" %
+ (rpolicy, active_policy))
+ domac = ['access_control']
+ domac.append(['policy', active_policy])
+ domac.append(['label', domain_label])
+ domac.append(['type', 'dom'])
+ decision = get_decision(domac, ['ssidref', str(rssidref)])
+
+ log.info("Access Control Decision : %s" % decision)
+ # provide descriptive error messages
+ if decision == 'DENIED':+ if rlabel == ssidref2label(NULL_SSIDREF):
+ #raise ACMError("Resource is not labeled")
+ rtnval = 0
+ else:
+ #raise ACMError("Permission denied for resource because label '"+rlabel+"' is not allowed")
+ rtnval = 0
+
+ # security is off, make sure resource isn't labeled
+ else:
+ # Note, we can't canonicalise the resource here, because people using + # xm without ACM are free to use relative paths. + if rpolicy != 'NULL':
+ #raise ACMError("Security is off, but resource is labeled")
+ rtnval = 0
+
+ return rtnval
+
+
+def set_resource_label_xapi(resource, reslabel_xapi, oldlabel_xapi):
+ """Assign a resource label to a resource
+ @param resource: The name of a resource, i.e., "phy:/dev/hda", or
+ "tap:qcow:/path/to/file.qcow"
+
+ @param reslabel_xapi: A resource label foramtted as in all other parts of
+ the Xen-API, i.e., ACM:xm-test:blue"
+ @rtype: int + @return Success (0) or failure value (< 0) + """ + olabel = "" + if reslabel_xapi == "":
+ return rm_resource_label(resource)
+ typ, policyref, label = reslabel_xapi.split(":")
+ if typ != xsconstants.ACM_POLICY_ID:
+ return -xsconstants.XSERR_WRONG_POLICY_TYPE
+ if not policyref or not label:
+ return -xsconstants.XSERR_BAD_LABEL_FORMAT
+ if oldlabel_xapi not in [ "*", "" ]:
+ tmp = oldlabel_xapi.split(":")
+ if len(tmp) != 3:
+ return -xsconstants.XSERR_BAD_LABEL_FORMAT
+ otyp, opolicyref, olabel = tmp + # Only ACM is supported + if otyp != xsconstants.ACM_POLICY_ID:
+ return -xsconstants.XSERR_WRONG_POLICY_TYPE
+ return set_resource_label(resource, typ, policyref, label, olabel)
+
+def is_resource_in_use(resource):
+ """ Investigate all running domains whether they use this device """
+ from xen.xend import XendDomain
+ dominfos = XendDomain.instance().list('all')
+ lst = []
+ for dominfo in dominfos:+ if is_resource_in_use_by_dom(dominfo, resource):
+ lst.append(dominfo)
+ return lst
+
+def is_resource_in_use_by_dom(dominfo, resource):
+ if not dominfo.domid:
+ return False
+ if dominfo._stateGet() not in [ DOM_STATE_RUNNING ]:
+ return False
+ devs = dominfo.info['devices'] + uuids = devs.keys() + for uuid in uuids:
+ dev = devs[uuid]
+ if len(dev) >= 2 and dev[1].has_key('uname'):
+ # dev[0] is type, i.e. 'vbd'
+ if dev[1]['uname'] == resource:
+ log.info("RESOURCE IN USE: Domain %d uses %s." %
+ (dominfo.domid, resource))
+ return True
+ return False
+
+
+def get_domain_resources(dominfo):
+ """
+ Collect all resources of a domain in a map where each entry of the map
+ is a list.
+ Entries are strored in the following formats:
+ tap:qcow:/path/xyz.qcow or
+ ...
+ """
+ resources = { 'vbd' : [], 'tap' : []}
+ devs = dominfo.info['devices']
+ uuids = devs.keys()
+ for uuid in uuids:
+ dev = devs[uuid]
+ typ = dev[0]
+ if typ in [ 'vbd', 'tap' ]:+ resources[typ].append(dev[1]['uname'])
+
+ return resources
+
+
+def resources_compatible_with_vmlabel(xspol, dominfo, vmlabel):
+ """
+ Check whether the resources' labels are compatible with the + given VM label. This is a function to be used when for example + a running domain is to get the new label 'vmlabel'
+ """
+ if not xspol:
+ return False
+
+ try:
+ __resfile_lock.acquire()
+ try:
+ access_control = dictio.dict_read("resources",
+ res_label_filename)
+ except:
+ return False
+ return __resources_compatible_with_vmlabel(xspol, dominfo, vmlabel,
+ access_control)
+ finally:
+ __resfile_lock.release()
+ return False
+
+
+def __resources_compatible_with_vmlabel(xspol, dominfo, vmlabel,
+ access_control):
+ """
+ Check whether the resources' labels are compatible with the + given VM label. The access_control parameter provides a + dictionary of the resource name to resource label mappings + under which the evaluation should be done. + """ + resources = get_domain_resources(dominfo) + reslabels = [] # all resource labels + polname = xspol.get_name() + for key in resources.keys():
+ for res in resources[key]:
+ try:
+ tmp = access_control[res]
+ if len(tmp) != 3:
+ return False
+
+ if polname != tmp[1]:
+ return False
+ label = tmp[2]
+ if not label in reslabels:
+ reslabels.append(label)
+ except:
+ return False
+ # Check that all resource labes have a common STE type with the + # vmlabel + rc = xspol.policy_check_vmlabel_against_reslabels(vmlabel, reslabels) + return rc;
+
+def set_resource_label(resource, policytype, policyref, reslabel, \
+ oreslabel = None):
+ """Assign a label to a resource
+ If the old label (oreslabel) is given, then the resource must have + that old label. + A resource label may be changed if + - the resource is not in use + - the resource is in use and the domain that is using it + has a VMlabel where one of its STE types is contained in + the STE type of the new resource + @param resource : The name of a resource, i.e., "phy:/dev/hda" + @param policyref : The name of the policy + @param reslabel : the resource label within the policy + @param oreslabel : optional current resource label + + @rtype: int + @return Success (0) or failure value (< 0) + """ + try:
+ resource = unify_resname(resource, mustexist=False)
+ except Exception:
+ return -xsconstants.XSERR_BAD_RESOURCE_FORMAT
+
+ # IF no policy is loaded, anything may be labeled + from xen.util.xspolicyadmin import XSPolicyAdminInstance + poladmin = XSPolicyAdminInstance() + xspol = poladmin.get_policy_by_name(policyref)
+
+ if xspol:
+ domains = is_resource_in_use(resource)
+ if len(domains) > 0:
+ # Resource is in use. Make sure device remains accessible
+ for dominfo in domains:
+ vmlabel_xapi = dominfo.get_security_label()
+ tmp = vmlabel_xapi.split(":")
+ if len(tmp) != 3:+ return -xsconstants.XSERR_GENERAL_FAILURE
+ vmlabel = tmp[2]
+ if not xspol.policy_check_vmlabel_against_reslabels(vmlabel,
+ [ reslabel ]):
+ return -xsconstants.XSERR_RESOURCE_ACCESS
+
+ try:
+ __resfile_lock.acquire()
+ access_control = {}
+ try:+ access_control = dictio.dict_read("resources", res_label_filename)
+ except:
+ pass
+ if oreslabel and oreslabel != "*":
+ if not access_control.has_key(resource):
+ return -xsconstants.XSERR_BAD_LABEL
+ tmp = access_control[resource]
+ if len(tmp) != 3:
+ return -xsconstants.XSERR_BAD_LABEL
+ if tmp[2] != oreslabel:
+ return -xsconstants.XSERR_BAD_LABEL
+ if reslabel != "":
+ new_entry = { resource : tuple([policytype, policyref, reslabel])}
+ access_control.update(new_entry)
+ else:
+ if access_control.has_key(resource):
+ del access_control[resource]
+ dictio.dict_write(access_control, "resources", res_label_filename)
+ finally:
+ __resfile_lock.release()
+ return xsconstants.XSERR_SUCCESS
+
+def rm_resource_label(resource):
+ """Remove a resource label from a physical resource
+ @param resource: The name of a resource, i.e., "phy:/dev/hda"
+
+ @rtype: int + @return Success (0) or failure value (< 0) + """ + return set_resource_label(resource, "", "", "", "*")
+
+def get_resource_label_xapi(resource):
+ """Get the assigned resource label of a physical resource
+ in the format used by then Xen-API, i.e., "ACM:xm-test:blue"
+
+ @rtype: string
+ @return the string representing policy type, policy name and label of
+ the resource
+ """ + res = get_resource_label(resource) + return format_resource_label(res)
+
+def format_resource_label(res):
+ if res:
+ if len(res) == 2:
+ return xsconstants.ACM_POLICY_ID + ":" + res[0] + ":" + res[1]
+ if len(res) == 3:
+ return ":".join(res)
+ return ""
+
+def get_resource_label(resource):
+ """Get the assigned resource label of a given resource
+ @param resource: The name of a resource, i.e., "phy:/dev/hda"
+
+ @rtype: list + @return tuple of (policy name, resource label), i.e., (xm-test, blue) + """ + try:
+ resource = unify_resname(resource, mustexist=False)
+ except Exception:
+ return []
+
+ reslabel_map = get_labeled_resources()
+
+ if reslabel_map.has_key(resource):
+ return list(reslabel_map[resource])
+ else:
+ #Try to resolve each label entry
+ for key, value in reslabel_map.items():
+ try:
+ if resource == unify_resname(key):
+ return list(value)
+ except:
+ pass
+
+ return []
+
+
+def get_labeled_resources_xapi():
+ """ Get a map of all labeled resource with the labels formatted in the
+ xen-api resource label format.
+ """ + reslabel_map = get_labeled_resources() + for key, labeldata in reslabel_map.items():
+ reslabel_map[key] = format_resource_label(labeldata)
+ return reslabel_map
+
+
+def get_labeled_resources():
+ """Get a map of all labeled resources + @rtype: list + @return list of labeled resources + """ + try:
+ __resfile_lock.acquire()
+ try:
+ access_control = dictio.dict_read("resources", res_label_filename)
+ except:
+ return {}
+ finally:
+ __resfile_lock.release()
+ return access_control
+
+
+def relabel_domains(relabel_list):
+ """
+ Relabel the given domains to have a new ssidref.
+ @param relabel_list: a list containing tuples of domid, ssidref
+ example: [ [0, 0x00020002] ]
+ """ + rel_rules = "" + for r in relabel_list:
+ log.info("Relabeling domain with domid %d to new ssidref 0x%08x",
+ r[0], r[1])
+ rel_rules += struct.pack("ii", r[0], r[1])
+ try:
+ rc, errors = acm.relabel_domains(rel_rules)
+ except Exception, e:
+ log.info("Error after relabel_domains: %s" % str(e))
+ rc = -xsconstants.XSERR_GENERAL_FAILURE
+ errors = ""+ if (len(errors) > 0):
+ rc = -xsconstants.XSERR_HV_OP_FAILED
+ return rc, errors
+
+
+def change_acm_policy(bin_pol, del_array, chg_array,
+ vmlabel_map, reslabel_map, cur_acmpol, new_acmpol):
+ """
+ Change the ACM policy of the system by relabeling + domains and resources first and doing some access checks. + Then update the policy in the hypervisor. If this is all successful, + relabel the domains permanently and commit the relabed resources.
+
+ Need to do / check the following:
+ - relabel all resources where there is a 'from' field in
+ the policy. [ NOT DOING THIS: and mark those as unlabeled where the label
+ does not appear in the new policy anymore (deletion) ]
+ - relabel all VMs where there is a 'from' field in the
+ policy and mark those as unlabeled where the label + does not appear in the new policy anymore; no running + or paused VM may be unlabeled through this + - check that under the new labeling conditions the VMs + still have access to their resources as before. Unlabeled + resources are inaccessible. If this check fails, the + update failed.
+ - Attempt changes in the hypervisor; if this step fails,
+ roll back the relabeling of resources and VMs
+ - Make the relabeling of resources and VMs permanent
+ """
+ rc = xsconstants.XSERR_SUCCESS
+
+ domain_label_map = {}
+ new_policyname = new_acmpol.get_name()
+ new_policytype = new_acmpol.get_type_name()
+ cur_policyname = cur_acmpol.get_name()
+ cur_policytype = cur_acmpol.get_type_name()
+ polnew_reslabels = new_acmpol.policy_get_resourcelabel_names()+
+ try:
+ __resfile_lock.acquire()
+ mapfile_lock()
+
+ # Get all domains' dominfo.
+ from xen.xend import XendDomain
+ dominfos = XendDomain.instance().list('all')+
+ log.info("----------------------------------------------")
+ # relabel resources
+
+ access_control = {}
+ try:
+ access_control = dictio.dict_read("resources", res_label_filename)
+ finally:
+ pass
+ for key, labeldata in access_control.items():
+ if len(labeldata) == 2:
+ policy, label = labeldata
+ policytype = xsconstants.ACM_POLICY_ID
+ elif len(labeldata) == 3:
+ policytype, policy, label = labeldata
+ else:
+ return -xsconstants.XSERR_BAD_LABEL_FORMAT, ""
+
+ if policytype != cur_policytype or \
+ policy != cur_policyname:
+ continue
+
+ # label been renamed or deleted?
+ if reslabel_map.has_key(label) and cur_policyname == policy:
+ label = reslabel_map[label]
+ elif label not in polnew_reslabels:
+ policytype = "INV_" + policytype
+ # Update entry
+ access_control[key] = \
+ tuple([ policytype, new_policyname, label ])
+
+ # All resources have new labels in the access_control map
+ # There may still be labels in there that are invalid now.
+
+ # Do this in memory without writing to disk:
+ # - Relabel all domains independent of whether they are running
+ # or not
+ # - later write back to config files
+ polnew_vmlabels = new_acmpol.policy_get_virtualmachinelabel_names()
+
+ for dominfo in dominfos:
+ sec_lab = dominfo.get_security_label()
+ policytype, policy, vmlabel = sec_lab.split(":")
+ name = dominfo.getName()+
+ if policytype != cur_policytype or \
+ policy != cur_policyname:
+ continue
+
+ new_vmlabel = vmlabel
+ if vmlabel_map.has_key(vmlabel):
+ new_vmlabel = vmlabel_map[vmlabel]
+ if new_vmlabel not in polnew_vmlabels:
+ policytype = "INV_" + policytype
+ new_seclab = "%s:%s:%s" % \
+ (policytype, new_policyname, new_vmlabel)
+
+ domain_label_map[dominfo] = [ sec_lab, new_seclab ]
+
+ if dominfo._stateGet() in (DOM_STATE_PAUSED, DOM_STATE_RUNNING):
+ compatible = __resources_compatible_with_vmlabel(new_acmpol,
+ dominfo, + new_vmlabel, + access_control)
+ log.info("Domain %s can access its resource? : %s" %
+ (name, str(compatible)))
+ if not compatible:
+ return (-xsconstants.XSERR_RESOURCE_ACCESS, "")
+
+ rc, errors = hv_chg_policy(bin_pol, del_array, chg_array)
+ if rc == 0:
+ # Write the relabeled resources back into the file + dictio.dict_write(access_control, "resources", res_label_filename) + # Properly update all VMs to their new labels + for dominfo, labels in domain_label_map.items():
+ sec_lab, new_seclab = labels
+ if sec_lab != new_seclab:
+ log.info("Updating domain %s to new label '%s'." % \
+ (new_seclab, sec_lab))
+ # This better be working!
+ dominfo.set_security_label(new_seclab,
+ sec_lab,
+ new_acmpol)
+ finally:
+ log.info("----------------------------------------------")
+ mapfile_unlock()
+ __resfile_lock.release()+
+ return rc, errors
xen-unstable.hg/tools/python/xen/util/xspolicyadmin.py new file +311 -0
311 lines not on this page · raw message
xen-unstable.hg/tools/python/xen/util/bootloader.py new file +377 -0
377 lines not on this page · raw message
xen-unstable.hg/tools/python/xen/util/xspolicy.py new file +57 -0
57 lines not on this page · raw message
xen-unstable.hg/tools/python/xen/util/acmpolicy.py new file +1126 -0
1,126 lines not on this page · raw message
xen-unstable.hg/tools/security/policies/security_policy.xsd +23 -6
@@ -22,7 +22,7 @@ <xsd:element name="Reference" type="xsd:string" minOccurs="0" maxOccurs="1" /> <xsd:element name="Date" minOccurs="0" maxOccurs="1" type="xsd:string"></xsd:element> <xsd:element name="NameSpaceUrl" minOccurs="0" maxOccurs="1" type="xsd:string"></xsd:element> - <xsd:element name="Version" minOccurs="0" maxOccurs="1" type="VersionFormat"/> + <xsd:element name="Version" minOccurs="1" maxOccurs="1" type="VersionFormat"/> <xsd:element ref="FromPolicy" minOccurs="0" maxOccurs="1"/> </xsd:sequence> </xsd:complexType>
@@ -91,23 +91,23 @@ <xsd:sequence> <xsd:element maxOccurs="unbounded" minOccurs="1" ref="Type" /> </xsd:sequence> - <xsd:attribute name="name" type="xsd:string" use="optional"></xsd:attribute> + <xsd:attribute name="name" type="xsd:string" use="required"></xsd:attribute> </xsd:complexType> </xsd:element> <xsd:element name="VirtualMachineLabel"> <xsd:complexType> <xsd:sequence> - <xsd:element ref="Name"></xsd:element> + <xsd:element name="Name" type="NameWithFrom"></xsd:element> <xsd:element ref="SimpleTypeEnforcementTypes" minOccurs="0" maxOccurs="unbounded" /> - <xsd:element ref="ChineseWallTypes" minOccurs="0" maxOccurs="unbounded" /> + <xsd:element name="ChineseWallTypes" type="SingleChineseWallType" /> </xsd:sequence> </xsd:complexType> </xsd:element> <xsd:element name="ResourceLabel"> <xsd:complexType> <xsd:sequence> - <xsd:element ref="Name"></xsd:element> - <xsd:element ref="SimpleTypeEnforcementTypes" minOccurs="0" maxOccurs="unbounded" /> + <xsd:element name="Name" type="NameWithFrom"></xsd:element> + <xsd:element name="SimpleTypeEnforcementTypes" type="SingleSimpleTypeEnforcementType" /> </xsd:sequence> </xsd:complexType> </xsd:element>
@@ -131,4 +131,21 @@ <xsd:pattern value="[0-9]{1,8}.[0-9]{1,8}"></xsd:pattern> </xsd:restriction> </xsd:simpleType> + <xsd:complexType name="NameWithFrom"> + <xsd:simpleContent> + <xsd:extension base="xsd:string"> + <xsd:attribute name="from" type="xsd:string" use="optional"></xsd:attribute> + </xsd:extension> + </xsd:simpleContent> + </xsd:complexType> + <xsd:complexType name="SingleSimpleTypeEnforcementType"> + <xsd:sequence> + <xsd:element maxOccurs="1" minOccurs="1" ref="Type" /> + </xsd:sequence> + </xsd:complexType> + <xsd:complexType name="SingleChineseWallType"> + <xsd:sequence> + <xsd:element maxOccurs="1" minOccurs="1" ref="Type" /> + </xsd:sequence> + </xsd:complexType> </xsd:schema>
_______________________________________________
Xen-devel mailing list
[email protected]
http://lists.xensource.com/xen-devel