ia64/xen-unstable

changeset 15625:f1aed243f3f0

[xend / libxen] Add support for labeling of virtual network interfaces.

This patch adds labeling of virtual network interfaces to xend and
makes this manageable through the Xen-API. It's a feature that is
only usable if ACM is enabled in Xen and xend is used through the
xen-api. A labeled virtual network interface will be plugged into a
bridge where other domains with the same-labeled network interface are
connected to, so that only same-colored domains can communicate with
each other. The bridge should be connected to the outside world using
VLAN for isolation, extending the isolation beyond the local machine.
If a virtual machine is labeled with a VM label that only has one
Simple Type Enforcement Type then it is not necessary to label the
virtual network interface, but the color of the network interface is
determined from the VM's label. If, however, a virtual machine is
labeled with a VM label that has multiple Simple Type Enforcement
Types, then the explicit labeling of each virtual network interface is
required. To specify the label of a network interface, the vif line in
the VM's configuration file has been extended with parameters similar
use for specifying the label of the VM:

vif = ['policy=<policy name>,label=<resource label>']

This labels the VIF of the virtual machine for usage under the policy
'policy name' and labels it with the label 'resource label'.

Signed-off-by: Stefan Berger <stefanb@us.ibm.com>
author kfraser@localhost.localdomain
date Thu Jul 19 16:59:48 2007 +0100 (2007-07-19)
parents c41dd7e841b1
children fdc602720f11
files tools/libxen/include/xen/api/xen_vif.h tools/libxen/src/xen_vif.c tools/python/xen/util/security.py tools/python/xen/xend/XendAPI.py tools/python/xen/xend/XendConfig.py tools/python/xen/xend/XendDomain.py tools/python/xen/xend/XendDomainInfo.py tools/python/xen/xend/XendXSPolicyAdmin.py tools/python/xen/xend/server/netif.py tools/python/xen/xm/addlabel.py tools/python/xen/xm/create.dtd tools/python/xen/xm/create.py tools/python/xen/xm/getlabel.py tools/python/xen/xm/rmlabel.py tools/python/xen/xm/xenapi_create.py
line diff
     1.1 --- a/tools/libxen/include/xen/api/xen_vif.h	Thu Jul 19 13:39:10 2007 +0100
     1.2 +++ b/tools/libxen/include/xen/api/xen_vif.h	Thu Jul 19 16:59:48 2007 +0100
     1.3 @@ -362,4 +362,18 @@ extern bool
     1.4  xen_vif_get_all(xen_session *session, struct xen_vif_set **result);
     1.5  
     1.6  
     1.7 +/**
     1.8 + * Set the security label of a VIF.
     1.9 + */
    1.10 +extern bool
    1.11 +xen_vif_set_security_label(xen_session *session, int64_t *result, xen_vif vif,
    1.12 +                           char *label, char *oldlabel);
    1.13 +
    1.14 +
    1.15 +/**
    1.16 + * Get the security label of a VIF.
    1.17 + */
    1.18 +extern bool
    1.19 +xen_vif_get_security_label(xen_session *session, char **result, xen_vif vif);
    1.20 +
    1.21  #endif
     2.1 --- a/tools/libxen/src/xen_vif.c	Thu Jul 19 13:39:10 2007 +0100
     2.2 +++ b/tools/libxen/src/xen_vif.c	Thu Jul 19 16:59:48 2007 +0100
     2.3 @@ -575,3 +575,42 @@ xen_vif_get_uuid(xen_session *session, c
     2.4      XEN_CALL_("VIF.get_uuid");
     2.5      return session->ok;
     2.6  }
     2.7 +
     2.8 +
     2.9 +bool
    2.10 +xen_vif_set_security_label(xen_session *session, int64_t *result, xen_vif vif,
    2.11 +                           char *label, char *oldlabel)
    2.12 +{
    2.13 +    abstract_value param_values[] =
    2.14 +        {
    2.15 +            { .type = &abstract_type_string,
    2.16 +              .u.string_val = vif },
    2.17 +            { .type = &abstract_type_string,
    2.18 +              .u.string_val = label },
    2.19 +            { .type = &abstract_type_string,
    2.20 +              .u.string_val = oldlabel },
    2.21 +        };
    2.22 +
    2.23 +    abstract_type result_type = abstract_type_int;
    2.24 +
    2.25 +    *result = 0;
    2.26 +    XEN_CALL_("VIF.set_security_label");
    2.27 +    return session->ok;
    2.28 +}
    2.29 +
    2.30 +
    2.31 +bool
    2.32 +xen_vif_get_security_label(xen_session *session, char **result, xen_vif vif)
    2.33 +{
    2.34 +    abstract_value param_values[] =
    2.35 +        {
    2.36 +            { .type = &abstract_type_string,
    2.37 +              .u.string_val = vif },
    2.38 +        };
    2.39 +
    2.40 +    abstract_type result_type = abstract_type_string;
    2.41 +
    2.42 +    *result = NULL;
    2.43 +    XEN_CALL_("VIF.get_security_label");
    2.44 +    return session->ok;
    2.45 +}
     3.1 --- a/tools/python/xen/util/security.py	Thu Jul 19 13:39:10 2007 +0100
     3.2 +++ b/tools/python/xen/util/security.py	Thu Jul 19 16:59:48 2007 +0100
     3.3 @@ -831,7 +831,7 @@ def get_domain_resources(dominfo):
     3.4          Entries are strored in the following formats:
     3.5            tap:qcow:/path/xyz.qcow
     3.6      """
     3.7 -    resources = { 'vbd' : [], 'tap' : []}
     3.8 +    resources = { 'vbd' : [], 'tap' : [], 'vif' : []}
     3.9      devs = dominfo.info['devices']
    3.10      uuids = devs.keys()
    3.11      for uuid in uuids:
    3.12 @@ -839,6 +839,15 @@ def get_domain_resources(dominfo):
    3.13          typ = dev[0]
    3.14          if typ in [ 'vbd', 'tap' ]:
    3.15              resources[typ].append(dev[1]['uname'])
    3.16 +        if typ in [ 'vif' ]:
    3.17 +            sec_lab = dev[1].get('security_label')
    3.18 +            if sec_lab:
    3.19 +                resources[typ].append(sec_lab)
    3.20 +            else:
    3.21 +                resources[typ].append("%s:%s:%s" %
    3.22 +                                      (xsconstants.ACM_POLICY_ID,
    3.23 +                                       active_policy,
    3.24 +                                       "unlabeled"))
    3.25  
    3.26      return resources
    3.27  
    3.28 @@ -874,23 +883,36 @@ def __resources_compatible_with_vmlabel(
    3.29          dictionary of the resource name to resource label mappings
    3.30          under which the evaluation should be done.
    3.31      """
    3.32 +    def collect_labels(reslabels, s_label, polname):
    3.33 +        if len(s_label) != 3 or polname != s_label[1]:
    3.34 +            return False
    3.35 +        label = s_label[2]
    3.36 +        if not label in reslabels:
    3.37 +            reslabels.append(label)
    3.38 +        return True
    3.39 +
    3.40      resources = get_domain_resources(dominfo)
    3.41      reslabels = []  # all resource labels
    3.42 -    polname = xspol.get_name()
    3.43 -    for key in resources.keys():
    3.44 -        for res in resources[key]:
    3.45 -            try:
    3.46 -                tmp = access_control[res]
    3.47 -                if len(tmp) != 3:
    3.48 -                    return False
    3.49  
    3.50 -                if polname != tmp[1]:
    3.51 +    polname = xspol.get_name()
    3.52 +    for key, value in resources.items():
    3.53 +        if key in [ 'vbd', 'tap' ]:
    3.54 +            for res in resources[key]:
    3.55 +                try:
    3.56 +                    label = access_control[res]
    3.57 +                    if not collect_labels(reslabels, label, polname):
    3.58 +                        return False
    3.59 +                except:
    3.60                      return False
    3.61 -                label = tmp[2]
    3.62 -                if not label in reslabels:
    3.63 -                    reslabels.append(label)
    3.64 -            except:
    3.65 -                return False
    3.66 +        elif key in [ 'vif' ]:
    3.67 +            for xapi_label in value:
    3.68 +                label = xapi_label.split(":")
    3.69 +                if not collect_labels(reslabels, label, polname):
    3.70 +                    return False
    3.71 +        else:
    3.72 +            log.error("Unhandled device type: %s" % key)
    3.73 +            return False
    3.74 +
    3.75      # Check that all resource labes have a common STE type with the
    3.76      # vmlabel
    3.77      rc = xspol.policy_check_vmlabel_against_reslabels(vmlabel, reslabels)
     4.1 --- a/tools/python/xen/xend/XendAPI.py	Thu Jul 19 13:39:10 2007 +0100
     4.2 +++ b/tools/python/xen/xend/XendAPI.py	Thu Jul 19 16:59:48 2007 +0100
     4.3 @@ -2084,6 +2084,25 @@ class XendAPI(object):
     4.4      def VIF_get_security_label(self, session, vif_ref):
     4.5          return self._VIF_get(vif_ref, 'security_label')
     4.6  
     4.7 +    def _VIF_set(self, ref, prop, val, old_val):
     4.8 +        return XendDomain.instance().set_dev_property_by_uuid(
     4.9 +                       'vif', ref, prop, val, old_val)
    4.10 +
    4.11 +    def VIF_set_security_label(self, session, vif_ref, sec_lab, old_lab):
    4.12 +        xendom = XendDomain.instance()
    4.13 +        dom = xendom.get_vm_with_dev_uuid('vif', vif_ref)
    4.14 +        if not dom:
    4.15 +            return xen_api_error(['HANDLE_INVALID', 'VIF', vif_ref])
    4.16 +
    4.17 +        if dom._stateGet() == XEN_API_VM_POWER_STATE_RUNNING:
    4.18 +            raise SecurityError(-xsconstants.XSERR_RESOURCE_IN_USE)
    4.19 +
    4.20 +        rc = self._VIF_set(vif_ref, 'security_label', sec_lab, old_lab)
    4.21 +        if rc == False:
    4.22 +            raise SecurityError(-xsconstants.XSERR_BAD_LABEL)
    4.23 +        return xen_api_success(xsconstants.XSERR_SUCCESS)
    4.24 +
    4.25 +
    4.26      # Xen API: Class VIF_metrics
    4.27      # ----------------------------------------------------------------
    4.28  
     5.1 --- a/tools/python/xen/xend/XendConfig.py	Thu Jul 19 13:39:10 2007 +0100
     5.2 +++ b/tools/python/xen/xend/XendConfig.py	Thu Jul 19 16:59:48 2007 +0100
     5.3 @@ -1085,6 +1085,12 @@ class XendConfig(dict):
     5.4  
     5.5              self.device_duplicate_check(dev_type, dev_info, target)
     5.6  
     5.7 +            if dev_type == 'vif':
     5.8 +                if dev_info.get('policy') and dev_info.get('label'):
     5.9 +                    dev_info['security_label'] = "%s:%s:%s" % \
    5.10 +                        (xsconstants.ACM_POLICY_ID,
    5.11 +                         dev_info['policy'],dev_info['label'])
    5.12 +
    5.13              # create uuid if it doesn't exist
    5.14              dev_uuid = dev_info.get('uuid', None)
    5.15              if not dev_uuid:
    5.16 @@ -1159,6 +1165,10 @@ class XendConfig(dict):
    5.17                      network = XendAPIStore.get(
    5.18                          cfg_xenapi.get('network'), 'network')
    5.19                      dev_info['bridge'] = network.get_name_label()
    5.20 +
    5.21 +                if cfg_xenapi.get('security_label'):
    5.22 +                    dev_info['security_label'] = \
    5.23 +                         cfg_xenapi.get('security_label')
    5.24                  
    5.25                  dev_uuid = cfg_xenapi.get('uuid', None)
    5.26                  if not dev_uuid:
     6.1 --- a/tools/python/xen/xend/XendDomain.py	Thu Jul 19 13:39:10 2007 +0100
     6.2 +++ b/tools/python/xen/xend/XendDomain.py	Thu Jul 19 16:59:48 2007 +0100
     6.3 @@ -688,6 +688,29 @@ class XendDomain:
     6.4          
     6.5          return value
     6.6  
     6.7 +    def set_dev_property_by_uuid(self, klass, dev_uuid, field, value,
     6.8 +                                 old_val = None):
     6.9 +        rc = True
    6.10 +        self.domains_lock.acquire()
    6.11 +
    6.12 +        try:
    6.13 +            try:
    6.14 +                dom = self.get_vm_with_dev_uuid(klass, dev_uuid)
    6.15 +                if dom:
    6.16 +                    o_val = dom.get_dev_property(klass, dev_uuid, field)
    6.17 +                    log.info("o_val=%s, old_val=%s" % (o_val, old_val))
    6.18 +                    if old_val and old_val != o_val:
    6.19 +                        return False
    6.20 +
    6.21 +                    dom.set_dev_property(klass, dev_uuid, field, value)
    6.22 +                    self.managed_config_save(dom)
    6.23 +            except ValueError, e:
    6.24 +                pass
    6.25 +        finally:
    6.26 +            self.domains_lock.release()
    6.27 +
    6.28 +        return rc
    6.29 +
    6.30      def is_valid_vm(self, vm_ref):
    6.31          return (self.get_vm_by_uuid(vm_ref) != None)
    6.32  
     7.1 --- a/tools/python/xen/xend/XendDomainInfo.py	Thu Jul 19 13:39:10 2007 +0100
     7.2 +++ b/tools/python/xen/xend/XendDomainInfo.py	Thu Jul 19 16:59:48 2007 +0100
     7.3 @@ -2420,6 +2420,8 @@ class XendDomainInfo:
     7.4                  config['io_read_kbs'] = 0.0
     7.5                  config['io_write_kbs'] = 0.0                
     7.6  
     7.7 +            config['security_label'] = config.get('security_label', '')
     7.8 +
     7.9          if dev_class == 'vbd':
    7.10  
    7.11              if self._stateGet() not in (XEN_API_VM_POWER_STATE_HALTED,):
     8.1 --- a/tools/python/xen/xend/XendXSPolicyAdmin.py	Thu Jul 19 13:39:10 2007 +0100
     8.2 +++ b/tools/python/xen/xend/XendXSPolicyAdmin.py	Thu Jul 19 16:59:48 2007 +0100
     8.3 @@ -312,6 +312,18 @@ class XSPolicyAdmin:
     8.4              vmlabel = pol.policy_get_domain_label_by_ssidref_formatted(ssidref)
     8.5          return vmlabel
     8.6  
     8.7 +    def get_stes_of_vmlabel(self, vmlabel_xapi):
     8.8 +        """ Get the list of STEs given a VM label in XenAPI format """
     8.9 +        stes = []
    8.10 +        loadedpol = self.get_loaded_policy()
    8.11 +        if loadedpol:
    8.12 +            tmp = vmlabel_xapi.split(":")
    8.13 +            if len(tmp) != 3:
    8.14 +                return []
    8.15 +            stes = loadedpol.policy_get_stes_of_vmlabel(tmp[2])
    8.16 +        return stes
    8.17 +
    8.18 +
    8.19  poladmin = None
    8.20  
    8.21  def XSPolicyAdminInstance(maxpolicies=1):
     9.1 --- a/tools/python/xen/xend/server/netif.py	Thu Jul 19 13:39:10 2007 +0100
     9.2 +++ b/tools/python/xen/xend/server/netif.py	Thu Jul 19 16:59:48 2007 +0100
     9.3 @@ -26,6 +26,11 @@ import re
     9.4  
     9.5  from xen.xend import XendOptions
     9.6  from xen.xend.server.DevController import DevController
     9.7 +from xen.xend.XendError import VmError
     9.8 +from xen.util import security
     9.9 +from xen.xend.XendXSPolicyAdmin import XSPolicyAdminInstance
    9.10 +
    9.11 +from xen.xend.XendLogging import log
    9.12  
    9.13  xoptions = XendOptions.instance()
    9.14  
    9.15 @@ -108,6 +113,7 @@ class NetifController(DevController):
    9.16          ipaddr  = config.get('ip')
    9.17          model   = config.get('model')
    9.18          accel   = config.get('accel')
    9.19 +        sec_lab = config.get('security_label')
    9.20  
    9.21          if not typ:
    9.22              typ = xoptions.netback_type
    9.23 @@ -134,6 +140,8 @@ class NetifController(DevController):
    9.24              back['model'] = model
    9.25          if accel:
    9.26              back['accel'] = accel
    9.27 +        if sec_lab:
    9.28 +            back['security_label'] = sec_lab
    9.29  
    9.30          config_path = "device/%s/%d/" % (self.deviceClass, devid)
    9.31          for x in back:
    9.32 @@ -149,9 +157,34 @@ class NetifController(DevController):
    9.33              front = { 'handle' : "%i" % devid,
    9.34                        'mac'    : mac }
    9.35  
    9.36 +        if security.on():
    9.37 +            self.do_access_control(config)
    9.38 +
    9.39          return (devid, back, front)
    9.40  
    9.41  
    9.42 +    def do_access_control(self, config):
    9.43 +        """ do access control checking. Throws a VMError if access is denied """
    9.44 +        domain_label = self.vm.get_security_label()
    9.45 +        stes = XSPolicyAdminInstance().get_stes_of_vmlabel(domain_label)
    9.46 +        res_label = config.get('security_label')
    9.47 +        if len(stes) > 1 or res_label:
    9.48 +            if not res_label:
    9.49 +                raise VmError("'VIF' must be labeled")
    9.50 +            (label, ssidref, policy) = \
    9.51 +                              security.security_label_to_details(res_label)
    9.52 +            if domain_label:
    9.53 +                rc = security.res_security_check_xapi(label, ssidref,
    9.54 +                                                      policy,
    9.55 +                                                      domain_label)
    9.56 +                if rc == 0:
    9.57 +                    raise VmError("VM's access to network device denied. "
    9.58 +                                  "Check labeling")
    9.59 +            else:
    9.60 +                raise VmError("VM must have a security label to access "
    9.61 +                              "network device")
    9.62 +
    9.63 +
    9.64      def getDeviceConfiguration(self, devid):
    9.65          """@see DevController.configuration"""
    9.66  
    9.67 @@ -160,10 +193,12 @@ class NetifController(DevController):
    9.68          config_path = "device/%s/%d/" % (self.deviceClass, devid)
    9.69          devinfo = ()
    9.70          for x in ( 'script', 'ip', 'bridge', 'mac',
    9.71 -                   'type', 'vifname', 'rate', 'uuid', 'model', 'accel'):
    9.72 +                   'type', 'vifname', 'rate', 'uuid', 'model', 'accel',
    9.73 +                   'security_label'):
    9.74              y = self.vm._readVm(config_path + x)
    9.75              devinfo += (y,)
    9.76 -        (script, ip, bridge, mac, typ, vifname, rate, uuid, model, accel) = devinfo
    9.77 +        (script, ip, bridge, mac, typ, vifname, rate, uuid,
    9.78 +         model, accel, security_label) = devinfo
    9.79  
    9.80          if script:
    9.81              result['script'] = script
    9.82 @@ -185,5 +220,7 @@ class NetifController(DevController):
    9.83              result['model'] = model
    9.84          if accel:
    9.85              result['accel'] = accel
    9.86 -            
    9.87 +        if security_label:
    9.88 +            result['security_label'] = security_label
    9.89 +
    9.90          return result
    10.1 --- a/tools/python/xen/xm/addlabel.py	Thu Jul 19 13:39:10 2007 +0100
    10.2 +++ b/tools/python/xen/xm/addlabel.py	Thu Jul 19 16:59:48 2007 +0100
    10.3 @@ -34,6 +34,7 @@ def help():
    10.4      Format: xm addlabel <label> dom <configfile> [<policy>]
    10.5              xm addlabel <label> mgt <domain name> [<policy type>:<policy>]
    10.6              xm addlabel <label> res <resource> [[<policy type>:]<policy>]
    10.7 +            xm addlabel <label> vif-<idx> <domain name> [<policy type>:<policy>]
    10.8      
    10.9      This program adds an acm_label entry into the 'configfile'
   10.10      for a domain or allows to label a xend-managed domain.
   10.11 @@ -162,6 +163,32 @@ def add_domain_label_xapi(label, domainn
   10.12              print "Set the label of dormant domain '%s' to '%s'." % \
   10.13                    (domainname,label)
   10.14  
   10.15 +def add_vif_label(label, vmname, idx, policyref, policy_type):
   10.16 +    if xm_main.serverType != xm_main.SERVER_XEN_API:
   10.17 +        raise OptionError('Need to be configure for using xen-api.')
   10.18 +    vm_refs = server.xenapi.VM.get_by_name_label(vmname)
   10.19 +    if len(vm_refs) == 0:
   10.20 +        raise OptionError('A VM with the name %s does not exist.' %
   10.21 +                          vmname)
   10.22 +    vif_refs = server.xenapi.VM.get_VIFs(vm_refs[0])
   10.23 +    if len(vif_refs) <= idx:
   10.24 +        raise OptionError("Bad VIF index.")
   10.25 +    vif_ref = server.xenapi.VIF.get_by_uuid(vif_refs[idx])
   10.26 +    if not vif_ref:
   10.27 +        print "Internal error: VIF does not exist."
   10.28 +    sec_lab = "%s:%s:%s" % (policy_type, policyref, label)
   10.29 +    try:
   10.30 +        old_lab = server.xenapi.VIF.get_security_label(vif_ref)
   10.31 +        rc = server.xenapi.VIF.set_security_label(vif_ref,
   10.32 +                                                  sec_lab, old_lab)
   10.33 +        if int(rc) != 0:
   10.34 +            print "Could not label the VIF."
   10.35 +        else:
   10.36 +            print "Successfully labeled the VIF."
   10.37 +    except Exception, e:
   10.38 +        print "Could not label the VIF: %s" % str(e)
   10.39 +
   10.40 +
   10.41  def main(argv):
   10.42      policyref = None
   10.43      policy_type = ""
   10.44 @@ -209,6 +236,20 @@ def main(argv):
   10.45              else:
   10.46                  raise OptionError("Policy name in wrong format.")
   10.47          add_resource_label(label, resource, policyref, policy_type)
   10.48 +    elif argv[2].lower().startswith("vif-"):
   10.49 +        try:
   10.50 +            idx = int(argv[2][4:])
   10.51 +            if idx < 0:
   10.52 +                raise
   10.53 +        except:
   10.54 +            raise OptionError("Bad VIF device index.")
   10.55 +        vmname = argv[3]
   10.56 +        if policy_type == "":
   10.57 +            tmp = policyref.split(":")
   10.58 +            if len(tmp) != 2:
   10.59 +                raise OptionError("Policy name in wrong format.")
   10.60 +            policy_type, policyref = tmp
   10.61 +        add_vif_label(label, vmname, idx, policyref, policy_type)
   10.62      else:
   10.63          raise OptionError('Need to specify either "dom", "mgt" or "res" as '
   10.64                            'object to add label to.')
    11.1 --- a/tools/python/xen/xm/create.dtd	Thu Jul 19 13:39:10 2007 +0100
    11.2 +++ b/tools/python/xen/xm/create.dtd	Thu Jul 19 16:59:48 2007 +0100
    11.3 @@ -74,7 +74,8 @@
    11.4                   mtu             CDATA       #REQUIRED
    11.5                   device          CDATA       #REQUIRED
    11.6                   qos_algorithm_type CDATA    #REQUIRED
    11.7 -                 network         CDATA       #IMPLIED> 
    11.8 +                 network         CDATA       #IMPLIED
    11.9 +                 security_label  CDATA       #IMPLIED>
   11.10  
   11.11  <!ELEMENT vtpm   (name*)>
   11.12  <!ATTLIST vtpm   backend         CDATA #REQUIRED>
    12.1 --- a/tools/python/xen/xm/create.py	Thu Jul 19 13:39:10 2007 +0100
    12.2 +++ b/tools/python/xen/xm/create.py	Thu Jul 19 16:59:48 2007 +0100
    12.3 @@ -704,7 +704,8 @@ def configure_vifs(config_devs, vals):
    12.4  
    12.5          def f(k):
    12.6              if k not in ['backend', 'bridge', 'ip', 'mac', 'script', 'type',
    12.7 -                         'vifname', 'rate', 'model', 'accel']:
    12.8 +                         'vifname', 'rate', 'model', 'accel',
    12.9 +                         'policy', 'label']:
   12.10                  err('Invalid vif option: ' + k)
   12.11  
   12.12              config_vif.append([k, d[k]])
    13.1 --- a/tools/python/xen/xm/getlabel.py	Thu Jul 19 13:39:10 2007 +0100
    13.2 +++ b/tools/python/xen/xm/getlabel.py	Thu Jul 19 16:59:48 2007 +0100
    13.3 @@ -31,6 +31,7 @@ def help():
    13.4      Usage: xm getlabel dom <configfile>
    13.5             xm getlabel mgt <domain name>
    13.6             xm getlabel res <resource>
    13.7 +           xm getlabel vif-<idx> <vmname>
    13.8             
    13.9      This program shows the label for a domain, resource or virtual network
   13.10      interface of a Xend-managed domain."""
   13.11 @@ -103,6 +104,22 @@ def get_domain_label(configfile):
   13.12      data = data.rstrip("\']")
   13.13      print "policytype=%s," % xsconstants.ACM_POLICY_ID + data
   13.14  
   13.15 +def get_vif_label(vmname, idx):
   13.16 +    if xm_main.serverType != xm_main.SERVER_XEN_API:
   13.17 +        raise OptionError('xm needs to be configure to use the xen-api.')
   13.18 +    vm_refs = server.xenapi.VM.get_by_name_label(vmname)
   13.19 +    if len(vm_refs) == 0:
   13.20 +        raise OptionError('A VM with the name %s does not exist.' %
   13.21 +                          vmname)
   13.22 +    vif_refs = server.xenapi.VM.get_VIFs(vm_refs[0])
   13.23 +    if len(vif_refs) <= idx:
   13.24 +        raise OptionError("Bad VIF index.")
   13.25 +    vif_ref = server.xenapi.VIF.get_by_uuid(vif_refs[idx])
   13.26 +    if not vif_ref:
   13.27 +        print "No VIF with this UUID."
   13.28 +    sec_lab = server.xenapi.VIF.get_security_label(vif_ref)
   13.29 +    print "%s" % sec_lab
   13.30 +
   13.31  def get_domain_label_xapi(domainname):
   13.32      if xm_main.serverType != xm_main.SERVER_XEN_API:
   13.33          raise OptionError('xm needs to be configure to use the xen-api.')
   13.34 @@ -128,6 +145,15 @@ def main(argv):
   13.35      elif argv[1].lower() == "res":
   13.36          resource = argv[2]
   13.37          get_resource_label(resource)
   13.38 +    elif argv[1].lower().startswith("vif-"):
   13.39 +        try:
   13.40 +            idx = int(argv[1][4:])
   13.41 +            if idx < 0:
   13.42 +                raise
   13.43 +        except:
   13.44 +            raise OptionError("Bad VIF device index.")
   13.45 +        vmname = argv[2]
   13.46 +        get_vif_label(vmname, idx)
   13.47      else:
   13.48          raise OptionError('First subcommand argument must be "dom"'
   13.49                            ', "mgt" or "res"')
    14.1 --- a/tools/python/xen/xm/rmlabel.py	Thu Jul 19 13:39:10 2007 +0100
    14.2 +++ b/tools/python/xen/xm/rmlabel.py	Thu Jul 19 16:59:48 2007 +0100
    14.3 @@ -30,6 +30,7 @@ def help():
    14.4      Example: xm rmlabel dom <configfile>
    14.5               xm rmlabel res <resource>
    14.6               xm rmlabel mgt <domain name>
    14.7 +             xm rmlabel vif-<idx> <domain name>
    14.8  
    14.9      This program removes an acm_label entry from the 'configfile'
   14.10      for a domain, from a Xend-managed domain, from the global resource label
   14.11 @@ -129,24 +130,55 @@ def rm_domain_label_xapi(domainname):
   14.12      except Exception, e:
   14.13          print('Could not remove label from domain: %s' % e)
   14.14  
   14.15 +def rm_vif_label(vmname, idx):
   14.16 +    if xm_main.serverType != xm_main.SERVER_XEN_API:
   14.17 +        raise OptionError('Need to be configure for using xen-api.')
   14.18 +    vm_refs = server.xenapi.VM.get_by_name_label(vmname)
   14.19 +    if len(vm_refs) == 0:
   14.20 +        raise OptionError('A VM with the name %s does not exist.' %
   14.21 +                          vmname)
   14.22 +    vif_refs = server.xenapi.VM.get_VIFs(vm_refs[0])
   14.23 +    if len(vif_refs) <= idx:
   14.24 +        raise OptionError("Bad VIF index.")
   14.25 +    vif_ref = server.xenapi.VIF.get_by_uuid(vif_refs[idx])
   14.26 +    if not vif_ref:
   14.27 +        print "A VIF with this UUID does not exist."
   14.28 +    try:
   14.29 +        old_lab = server.xenapi.VIF.get_security_label(vif_ref)
   14.30 +        rc = server.xenapi.VIF.set_security_label(vif_ref, "", old_lab)
   14.31 +        if int(rc) != 0:
   14.32 +            print "Could not remove the label from the VIF."
   14.33 +        else:
   14.34 +            print "Successfully removed the label from the VIF."
   14.35 +    except Exception, e:
   14.36 +        print "Could not remove the label the VIF: %s" % str(e)
   14.37 +
   14.38  
   14.39  def main (argv):
   14.40  
   14.41      if len(argv) != 3:
   14.42          raise OptionError('Requires 2 arguments')
   14.43      
   14.44 -    if argv[1].lower() not in ('dom', 'mgt', 'res'):
   14.45 -        raise OptionError('Unrecognised type argument: %s' % argv[1])
   14.46 -
   14.47      if argv[1].lower() == "dom":
   14.48          configfile = argv[2]
   14.49          rm_domain_label(configfile)
   14.50      elif argv[1].lower() == "mgt":
   14.51          domain = argv[2]
   14.52          rm_domain_label_xapi(domain)
   14.53 +    elif argv[1].lower().startswith("vif-"):
   14.54 +        try:
   14.55 +            idx = int(argv[1][4:])
   14.56 +            if idx < 0:
   14.57 +                raise
   14.58 +        except:
   14.59 +            raise OptionError("Bad VIF device index.")
   14.60 +        vmname = argv[2]
   14.61 +        rm_vif_label(vmname, idx)
   14.62      elif argv[1].lower() == "res":
   14.63          resource = argv[2]
   14.64          rm_resource_label(resource)
   14.65 +    else:
   14.66 +        raise OptionError('Unrecognised type argument: %s' % argv[1])
   14.67  
   14.68  if __name__ == '__main__':
   14.69      try:
    15.1 --- a/tools/python/xen/xm/xenapi_create.py	Thu Jul 19 13:39:10 2007 +0100
    15.2 +++ b/tools/python/xen/xm/xenapi_create.py	Thu Jul 19 16:59:48 2007 +0100
    15.3 @@ -440,7 +440,9 @@ class xenapi_create:
    15.4                  vif.attributes["qos_algorithm_type"].value,
    15.5              "qos_algorithm_params":
    15.6                  get_child_nodes_as_dict(vif,
    15.7 -                    "qos_algorithm_param", "key", "value")
    15.8 +                    "qos_algorithm_param", "key", "value"),
    15.9 +            "security_label":
   15.10 +                vif.attributes["security_label"].value
   15.11          }
   15.12  
   15.13          return server.xenapi.VIF.create(vif_record)
   15.14 @@ -748,6 +750,15 @@ class sxp2xml:
   15.15          vif.attributes["device"] = dev
   15.16          vif.attributes["qos_algorithm_type"] = ""
   15.17  
   15.18 +        policy = get_child_by_name(vif_sxp, "policy")
   15.19 +        label = get_child_by_name(vif_sxp, "label")
   15.20 +
   15.21 +        if label and policy:
   15.22 +            vif.attributes["security_label"] \
   15.23 +                 = "%s:%s:%s" % (xsconstants.ACM_POLICY_ID, policy, label)
   15.24 +        else:
   15.25 +            vif.attributes["security_label"] = ""
   15.26 +
   15.27          if get_child_by_name(vif_sxp, "bridge") is not None:
   15.28              vif.attributes["network"] \
   15.29                  = get_child_by_name(vif_sxp, "bridge")