ia64/xen-unstable

changeset 15835:49b67fdefcd6

[XSM] correctly rename, relocate and patch the security.py file

This patch corrects an error in the original XSM tools patch. The
original patch did not rename, relocate and patch the security.py file
from changeset 15730:256160ff19b7. This patch addresses this issue as
well as any updates made to security.py in xen-staging during the
merge of XSM.

Signed-off-by: George Coker <gscoker@alpha.ncsc.mil>
author kfraser@localhost.localdomain
date Thu Sep 06 18:05:18 2007 +0100 (2007-09-06)
parents 453f87d6e7f0
children 9813c9c79055
files tools/python/xen/util/security.py tools/python/xen/util/xsm/acm/acm.py
line diff
     1.1 --- a/tools/python/xen/util/security.py	Thu Sep 06 18:04:42 2007 +0100
     1.2 +++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.3 @@ -1,1301 +0,0 @@
     1.4 -#===========================================================================
     1.5 -# This library is free software; you can redistribute it and/or
     1.6 -# modify it under the terms of version 2.1 of the GNU Lesser General Public
     1.7 -# License as published by the Free Software Foundation.
     1.8 -#
     1.9 -# This library is distributed in the hope that it will be useful,
    1.10 -# but WITHOUT ANY WARRANTY; without even the implied warranty of
    1.11 -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    1.12 -# Lesser General Public License for more details.
    1.13 -#
    1.14 -# You should have received a copy of the GNU Lesser General Public
    1.15 -# License along with this library; if not, write to the Free Software
    1.16 -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
    1.17 -#============================================================================
    1.18 -# Copyright (C) 2006 International Business Machines Corp.
    1.19 -# Author: Reiner Sailer
    1.20 -# Author: Bryan D. Payne <bdpayne@us.ibm.com>
    1.21 -# Author: Stefan Berger <stefanb@us.ibm.com>
    1.22 -#============================================================================
    1.23 -
    1.24 -import commands
    1.25 -import logging
    1.26 -import os, string, re
    1.27 -import threading
    1.28 -import struct
    1.29 -import stat
    1.30 -from xen.lowlevel import acm
    1.31 -from xen.xend import sxp
    1.32 -from xen.xend import XendConstants
    1.33 -from xen.xend.XendLogging import log
    1.34 -from xen.xend.XendError import VmError
    1.35 -from xen.util import dictio, xsconstants
    1.36 -from xen.xend.XendConstants import *
    1.37 -
    1.38 -#global directories and tools for security management
    1.39 -policy_dir_prefix = "/etc/xen/acm-security/policies"
    1.40 -res_label_filename = policy_dir_prefix + "/resource_labels"
    1.41 -boot_filename = "/boot/grub/menu.lst"
    1.42 -altboot_filename = "/boot/grub/grub.conf"
    1.43 -xensec_xml2bin = "/usr/sbin/xensec_xml2bin"
    1.44 -xensec_tool = "/usr/sbin/xensec_tool"
    1.45 -
    1.46 -#global patterns for map file
    1.47 -#police_reference_tagname = "POLICYREFERENCENAME"
    1.48 -primary_entry_re = re.compile("\s*PRIMARY\s+.*", re.IGNORECASE)
    1.49 -secondary_entry_re = re.compile("\s*SECONDARY\s+.*", re.IGNORECASE)
    1.50 -label_template_re =  re.compile(".*security_label_template.xml", re.IGNORECASE)
    1.51 -mapping_filename_re = re.compile(".*\.map", re.IGNORECASE)
    1.52 -policy_reference_entry_re = re.compile("\s*POLICYREFERENCENAME\s+.*", re.IGNORECASE)
    1.53 -vm_label_re = re.compile("\s*LABEL->SSID\s+VM\s+.*", re.IGNORECASE)
    1.54 -res_label_re = re.compile("\s*LABEL->SSID\s+RES\s+.*", re.IGNORECASE)
    1.55 -all_label_re = re.compile("\s*LABEL->SSID\s+.*", re.IGNORECASE)
    1.56 -access_control_re = re.compile("\s*access_control\s*=", re.IGNORECASE)
    1.57 -
    1.58 -#global patterns for boot configuration file
    1.59 -xen_title_re = re.compile("\s*title\s+XEN", re.IGNORECASE)
    1.60 -any_title_re = re.compile("\s*title\s", re.IGNORECASE)
    1.61 -xen_kernel_re = re.compile("\s*kernel.*xen.*\.gz", re.IGNORECASE)
    1.62 -kernel_ver_re = re.compile("\s*module.*vmlinuz", re.IGNORECASE)
    1.63 -any_module_re = re.compile("\s*module\s", re.IGNORECASE)
    1.64 -empty_line_re = re.compile("^\s*$")
    1.65 -binary_name_re = re.compile(".*[chwall|ste|chwall_ste].*\.bin", re.IGNORECASE)
    1.66 -policy_name_re = re.compile(".*[chwall|ste|chwall_ste].*", re.IGNORECASE)
    1.67 -
    1.68 -#decision hooks known to the hypervisor
    1.69 -ACMHOOK_sharing = 1
    1.70 -ACMHOOK_authorization = 2
    1.71 -
    1.72 -#other global variables
    1.73 -NULL_SSIDREF = 0
    1.74 -
    1.75 -#general Rlock for map files; only one lock for all mapfiles
    1.76 -__mapfile_lock = threading.RLock()
    1.77 -__resfile_lock = threading.RLock()
    1.78 -
    1.79 -log = logging.getLogger("xend.util.security")
    1.80 -
    1.81 -# Our own exception definition. It is masked (pass) if raised and
    1.82 -# whoever raises this exception must provide error information.
    1.83 -class ACMError(Exception):
    1.84 -    def __init__(self,value):
    1.85 -        self.value = value
    1.86 -    def __str__(self):
    1.87 -        return repr(self.value)
    1.88 -
    1.89 -
    1.90 -
    1.91 -def err(msg):
    1.92 -    """Raise ACM exception.
    1.93 -    """
    1.94 -    raise ACMError(msg)
    1.95 -
    1.96 -
    1.97 -
    1.98 -active_policy = None
    1.99 -
   1.100 -
   1.101 -def mapfile_lock():
   1.102 -    __mapfile_lock.acquire()
   1.103 -
   1.104 -def mapfile_unlock():
   1.105 -    __mapfile_lock.release()
   1.106 -
   1.107 -
   1.108 -def refresh_security_policy():
   1.109 -    """
   1.110 -    retrieves security policy
   1.111 -    """
   1.112 -    global active_policy
   1.113 -
   1.114 -    try:
   1.115 -        active_policy = acm.policy()
   1.116 -    except:
   1.117 -        active_policy = "INACTIVE"
   1.118 -
   1.119 -# now set active_policy
   1.120 -refresh_security_policy()
   1.121 -
   1.122 -def on():
   1.123 -    """
   1.124 -    returns none if security policy is off (not compiled),
   1.125 -    any string otherwise, use it: if not security.on() ...
   1.126 -    """
   1.127 -    refresh_security_policy()
   1.128 -    return (active_policy not in ['INACTIVE', 'NULL'])
   1.129 -
   1.130 -
   1.131 -def calc_dom_ssidref_from_info(info):
   1.132 -    """
   1.133 -       Calculate a domain's ssidref from the security_label in its
   1.134 -       info.
   1.135 -       This function is called before the domain is started and
   1.136 -       makes sure that:
   1.137 -        - the type of the policy is the same as indicated in the label
   1.138 -        - the name of the policy is the same as indicated in the label
   1.139 -        - calculates an up-to-date ssidref for the domain
   1.140 -       The latter is necessary since the domain's ssidref could have
   1.141 -       changed due to changes to the policy.
   1.142 -    """
   1.143 -    import xen.xend.XendConfig
   1.144 -    if isinstance(info, xen.xend.XendConfig.XendConfig):
   1.145 -        if info.has_key('security_label'):
   1.146 -            seclab = info['security_label']
   1.147 -            tmp = seclab.split(":")
   1.148 -            if len(tmp) != 3:
   1.149 -                raise VmError("VM label '%s' in wrong format." % seclab)
   1.150 -            typ, policyname, vmlabel = seclab.split(":")
   1.151 -            if typ != xsconstants.ACM_POLICY_ID:
   1.152 -                raise VmError("Policy type '%s' must be changed." % typ)
   1.153 -            refresh_security_policy()
   1.154 -            if active_policy != policyname:
   1.155 -                raise VmError("Active policy '%s' different than "
   1.156 -                              "what in VM's label ('%s')." %
   1.157 -                              (active_policy, policyname))
   1.158 -            ssidref = label2ssidref(vmlabel, policyname, "dom")
   1.159 -            return ssidref
   1.160 -        else:
   1.161 -            return 0x0
   1.162 -    raise VmError("security.calc_dom_ssidref_from_info: info of type '%s'"
   1.163 -                  "not supported." % type(info))
   1.164 -
   1.165 -
   1.166 -def getmapfile(policyname):
   1.167 -    """
   1.168 -    in: if policyname is None then the currently
   1.169 -    active hypervisor policy is used
   1.170 -    out: 1. primary policy, 2. secondary policy,
   1.171 -    3. open file descriptor for mapping file, and
   1.172 -    4. True if policy file is available, False otherwise
   1.173 -    """
   1.174 -    if not policyname:
   1.175 -        policyname = active_policy
   1.176 -    map_file_ok = False
   1.177 -    primary = None
   1.178 -    secondary = None
   1.179 -    #strip last part of policy as file name part
   1.180 -    policy_dir_list = string.split(policyname, ".")
   1.181 -    policy_file = policy_dir_list.pop()
   1.182 -    if len(policy_dir_list) > 0:
   1.183 -        policy_dir = string.join(policy_dir_list, "/") + "/"
   1.184 -    else:
   1.185 -        policy_dir = ""
   1.186 -
   1.187 -    map_filename = policy_dir_prefix + "/" + policy_dir + policy_file + ".map"
   1.188 -    # check if it is there, if not check if policy file is there
   1.189 -    if not os.path.isfile(map_filename):
   1.190 -        policy_filename =  policy_dir_prefix + "/" + policy_dir + policy_file + "-security_policy.xml"
   1.191 -        if not os.path.isfile(policy_filename):
   1.192 -            err("Policy file \'" + policy_filename + "\' not found.")
   1.193 -        else:
   1.194 -            err("Mapping file \'" + map_filename + "\' not found." +
   1.195 -                " Use xm makepolicy to create it.")
   1.196 -
   1.197 -    f = open(map_filename)
   1.198 -    for line in f:
   1.199 -        if policy_reference_entry_re.match(line):
   1.200 -            l = line.split()
   1.201 -            if (len(l) == 2) and (l[1] == policyname):
   1.202 -                map_file_ok = True
   1.203 -        elif primary_entry_re.match(line):
   1.204 -            l = line.split()
   1.205 -            if len(l) == 2:
   1.206 -                primary = l[1]
   1.207 -        elif secondary_entry_re.match(line):
   1.208 -            l = line.split()
   1.209 -            if len(l) == 2:
   1.210 -                secondary = l[1]
   1.211 -    f.close()
   1.212 -    f = open(map_filename)
   1.213 -    if map_file_ok and primary and secondary:
   1.214 -        return (primary, secondary, f, True)
   1.215 -    else:
   1.216 -        err("Mapping file inconsistencies found. Try makepolicy to create a new one.")
   1.217 -
   1.218 -
   1.219 -
   1.220 -def ssidref2label(ssidref_var):
   1.221 -    """
   1.222 -    returns labelname corresponding to ssidref;
   1.223 -    maps current policy to default directory
   1.224 -    to find mapping file
   1.225 -    """
   1.226 -    #1. translated permitted input formats
   1.227 -    if isinstance(ssidref_var, str):
   1.228 -        ssidref_var.strip()
   1.229 -        if ssidref_var[0:2] == "0x":
   1.230 -            ssidref = int(ssidref_var[2:], 16)
   1.231 -        else:
   1.232 -            ssidref = int(ssidref_var)
   1.233 -    elif isinstance(ssidref_var, int):
   1.234 -        ssidref = ssidref_var
   1.235 -    else:
   1.236 -        err("Instance type of ssidref not supported (must be of type 'str' or 'int')")
   1.237 -
   1.238 -    if ssidref == 0:
   1.239 -        from xen.util.acmpolicy import ACM_LABEL_UNLABELED
   1.240 -        return ACM_LABEL_UNLABELED
   1.241 -
   1.242 -    try:
   1.243 -        mapfile_lock()
   1.244 -
   1.245 -        (primary, secondary, f, pol_exists) = getmapfile(None)
   1.246 -        if not f:
   1.247 -            if (pol_exists):
   1.248 -                err("Mapping file for policy not found.\n" +
   1.249 -                    "Please use makepolicy command to create mapping file!")
   1.250 -            else:
   1.251 -                err("Policy file for \'" + active_policy + "\' not found.")
   1.252 -
   1.253 -        #2. get labelnames for both ssidref parts
   1.254 -        pri_ssid = ssidref & 0xffff
   1.255 -        sec_ssid = ssidref >> 16
   1.256 -        pri_null_ssid = NULL_SSIDREF & 0xffff
   1.257 -        sec_null_ssid = NULL_SSIDREF >> 16
   1.258 -        pri_labels = []
   1.259 -        sec_labels = []
   1.260 -        labels = []
   1.261 -
   1.262 -        for line in f:
   1.263 -            l = line.split()
   1.264 -            if (len(l) < 5) or (l[0] != "LABEL->SSID"):
   1.265 -                continue
   1.266 -            if primary and (l[2] == primary) and (int(l[4], 16) == pri_ssid):
   1.267 -                pri_labels.append(l[3])
   1.268 -            if secondary and (l[2] == secondary) and (int(l[4], 16) == sec_ssid):
   1.269 -                sec_labels.append(l[3])
   1.270 -        f.close()
   1.271 -    finally:
   1.272 -        mapfile_unlock()
   1.273 -
   1.274 -    #3. get the label that is in both lists (combination must be a single label)
   1.275 -    if (primary == "CHWALL") and (pri_ssid == pri_null_ssid) and (sec_ssid != sec_null_ssid):
   1.276 -        labels = sec_labels
   1.277 -    elif (secondary == "CHWALL") and (pri_ssid != pri_null_ssid) and (sec_ssid == sec_null_ssid):
   1.278 -        labels = pri_labels
   1.279 -    elif secondary == "NULL":
   1.280 -        labels = pri_labels
   1.281 -    else:
   1.282 -        for i in pri_labels:
   1.283 -            for j in sec_labels:
   1.284 -                if (i==j):
   1.285 -                    labels.append(i)
   1.286 -    if len(labels) != 1:
   1.287 -        err("Label for ssidref \'" +  str(ssidref) +
   1.288 -            "\' unknown or not unique in policy \'" + active_policy + "\'")
   1.289 -
   1.290 -    return labels[0]
   1.291 -
   1.292 -
   1.293 -
   1.294 -def label2ssidref(labelname, policyname, typ):
   1.295 -    """
   1.296 -    returns ssidref corresponding to labelname;
   1.297 -    maps current policy to default directory
   1.298 -    to find mapping file    """
   1.299 -
   1.300 -    if policyname in ['NULL', 'INACTIVE', 'DEFAULT']:
   1.301 -        err("Cannot translate labels for \'" + policyname + "\' policy.")
   1.302 -
   1.303 -    allowed_types = ['ANY']
   1.304 -    if typ == 'dom':
   1.305 -        allowed_types.append('VM')
   1.306 -    elif typ == 'res':
   1.307 -        allowed_types.append('RES')
   1.308 -    else:
   1.309 -        err("Invalid type.  Must specify 'dom' or 'res'.")
   1.310 -
   1.311 -    try:
   1.312 -        mapfile_lock()
   1.313 -        (primary, secondary, f, pol_exists) = getmapfile(policyname)
   1.314 -
   1.315 -        #2. get labelnames for ssidref parts and find a common label
   1.316 -        pri_ssid = []
   1.317 -        sec_ssid = []
   1.318 -        for line in f:
   1.319 -            l = line.split()
   1.320 -            if (len(l) < 5) or (l[0] != "LABEL->SSID"):
   1.321 -                continue
   1.322 -            if primary and (l[1] in allowed_types) and \
   1.323 -                           (l[2] == primary) and \
   1.324 -                           (l[3] == labelname):
   1.325 -                pri_ssid.append(int(l[4], 16))
   1.326 -            if secondary and (l[1] in allowed_types) and \
   1.327 -                             (l[2] == secondary) and \
   1.328 -                             (l[3] == labelname):
   1.329 -                sec_ssid.append(int(l[4], 16))
   1.330 -        f.close()
   1.331 -        if (typ == 'res') and (primary == "CHWALL") and (len(pri_ssid) == 0):
   1.332 -            pri_ssid.append(NULL_SSIDREF)
   1.333 -        elif (typ == 'res') and (secondary == "CHWALL") and \
   1.334 -             (len(sec_ssid) == 0):
   1.335 -            sec_ssid.append(NULL_SSIDREF)
   1.336 -
   1.337 -        #3. sanity check and composition of ssidref
   1.338 -        if (len(pri_ssid) == 0) or ((len(sec_ssid) == 0) and \
   1.339 -            (secondary != "NULL")):
   1.340 -            err("Label \'" + labelname + "\' not found.")
   1.341 -        elif (len(pri_ssid) > 1) or (len(sec_ssid) > 1):
   1.342 -            err("Label \'" + labelname + "\' not unique in policy (policy error)")
   1.343 -        if secondary == "NULL":
   1.344 -            return pri_ssid[0]
   1.345 -        else:
   1.346 -            return (sec_ssid[0] << 16) | pri_ssid[0]
   1.347 -    finally:
   1.348 -       mapfile_unlock()
   1.349 -
   1.350 -
   1.351 -def refresh_ssidref(config):
   1.352 -    """
   1.353 -    looks up ssidref from security field
   1.354 -    and refreshes the value if label exists
   1.355 -    """
   1.356 -    #called by dom0, policy could have changed after xen.utils.security was initialized
   1.357 -    refresh_security_policy()
   1.358 -
   1.359 -    security = None
   1.360 -    if isinstance(config, dict):
   1.361 -        security = config['security']
   1.362 -    elif isinstance(config, list):
   1.363 -        security = sxp.child_value(config, 'security')
   1.364 -    else:
   1.365 -        err("Instance type of config parameter not supported.")
   1.366 -    if not security:
   1.367 -        #nothing to do (no security label attached)
   1.368 -        return config
   1.369 -
   1.370 -    policyname = None
   1.371 -    labelname = None
   1.372 -    # compose new security field
   1.373 -    for idx in range(0, len(security)):
   1.374 -        if security[idx][0] == 'ssidref':
   1.375 -            security.pop(idx)
   1.376 -            break
   1.377 -        elif security[idx][0] == 'access_control':
   1.378 -            for jdx in [1, 2]:
   1.379 -                if security[idx][jdx][0] == 'label':
   1.380 -                    labelname = security[idx][jdx][1]
   1.381 -                elif security[idx][jdx][0] == 'policy':
   1.382 -                    policyname = security[idx][jdx][1]
   1.383 -                else:
   1.384 -                    err("Illegal field in access_control")
   1.385 -    #verify policy is correct
   1.386 -    if active_policy != policyname:
   1.387 -        err("Policy \'" + str(policyname) +
   1.388 -            "\' in label does not match active policy \'"
   1.389 -            + str(active_policy) +"\'!")
   1.390 -
   1.391 -    new_ssidref = label2ssidref(labelname, policyname, 'dom')
   1.392 -    if not new_ssidref:
   1.393 -        err("SSIDREF refresh failed!")
   1.394 -
   1.395 -    security.append([ 'ssidref',str(new_ssidref)])
   1.396 -    security = ['security', security ]
   1.397 -
   1.398 -    for idx in range(0,len(config)):
   1.399 -        if config[idx][0] == 'security':
   1.400 -            config.pop(idx)
   1.401 -            break
   1.402 -        config.append(security)
   1.403 -
   1.404 -
   1.405 -
   1.406 -def get_ssid(domain):
   1.407 -    """
   1.408 -    enables domains to retrieve the label / ssidref of a running domain
   1.409 -    """
   1.410 -    if not on():
   1.411 -        err("No policy active.")
   1.412 -
   1.413 -    if isinstance(domain, str):
   1.414 -        domain_int = int(domain)
   1.415 -    elif isinstance(domain, int):
   1.416 -        domain_int = domain
   1.417 -    else:
   1.418 -        err("Illegal parameter type.")
   1.419 -    try:
   1.420 -        ssid_info = acm.getssid(int(domain_int))
   1.421 -    except:
   1.422 -        err("Cannot determine security information.")
   1.423 -
   1.424 -    if active_policy in ["DEFAULT"]:
   1.425 -        label = "DEFAULT"
   1.426 -    else:
   1.427 -        label = ssidref2label(ssid_info["ssidref"])
   1.428 -    return(ssid_info["policyreference"],
   1.429 -           label,
   1.430 -           ssid_info["policytype"],
   1.431 -           ssid_info["ssidref"])
   1.432 -
   1.433 -
   1.434 -
   1.435 -def get_decision(arg1, arg2):
   1.436 -    """
   1.437 -    enables domains to retrieve access control decisions from
   1.438 -    the hypervisor Access Control Module.
   1.439 -    IN: args format = ['domid', id] or ['ssidref', ssidref]
   1.440 -    or ['access_control', ['policy', policy], ['label', label], ['type', type]]
   1.441 -    """
   1.442 -
   1.443 -    if not on():
   1.444 -        err("No policy active.")
   1.445 -
   1.446 -    #translate labels before calling low-level function
   1.447 -    if arg1[0] == 'access_control':
   1.448 -        if (arg1[1][0] != 'policy') or (arg1[2][0] != 'label') or (arg1[3][0] != 'type'):
   1.449 -            err("Argument type not supported.")
   1.450 -        ssidref = label2ssidref(arg1[2][1], arg1[1][1], arg1[3][1])
   1.451 -        arg1 = ['ssidref', str(ssidref)]
   1.452 -    if arg2[0] == 'access_control':
   1.453 -        if (arg2[1][0] != 'policy') or (arg2[2][0] != 'label') or (arg2[3][0] != 'type'):
   1.454 -            err("Argument type not supported.")
   1.455 -        ssidref = label2ssidref(arg2[2][1], arg2[1][1], arg2[3][1])
   1.456 -        arg2 = ['ssidref', str(ssidref)]
   1.457 -
   1.458 -    # accept only int or string types for domid and ssidref
   1.459 -    if isinstance(arg1[1], int):
   1.460 -        arg1[1] = str(arg1[1])
   1.461 -    if isinstance(arg2[1], int):
   1.462 -        arg2[1] = str(arg2[1])
   1.463 -    if not isinstance(arg1[1], str) or not isinstance(arg2[1], str):
   1.464 -        err("Invalid id or ssidref type, string or int required")
   1.465 -
   1.466 -    try:
   1.467 -        decision = acm.getdecision(arg1[0], arg1[1], arg2[0], arg2[1],
   1.468 -                                   ACMHOOK_sharing)
   1.469 -    except:
   1.470 -        err("Cannot determine decision.")
   1.471 -
   1.472 -    if decision:
   1.473 -        return decision
   1.474 -    else:
   1.475 -        err("Cannot determine decision (Invalid parameter).")
   1.476 -
   1.477 -
   1.478 -def has_authorization(ssidref):
   1.479 -    """ Check if the domain with the given ssidref has authorization to
   1.480 -        run on this system. To have authoriztion dom0's STE types must
   1.481 -        be a superset of that of the domain's given through its ssidref.
   1.482 -    """
   1.483 -    rc = True
   1.484 -    dom0_ssidref = int(acm.getssid(0)['ssidref'])
   1.485 -    decision = acm.getdecision('ssidref', str(dom0_ssidref),
   1.486 -                               'ssidref', str(ssidref),
   1.487 -                               ACMHOOK_authorization)
   1.488 -    if decision == "DENIED":
   1.489 -        rc = False
   1.490 -    return rc
   1.491 -
   1.492 -
   1.493 -def hv_chg_policy(bin_pol, del_array, chg_array):
   1.494 -    """
   1.495 -        Change the binary policy in the hypervisor
   1.496 -        The 'del_array' and 'chg_array' give hints about deleted ssidrefs
   1.497 -        and changed ssidrefs which can be due to deleted VM labels
   1.498 -        or reordered VM labels
   1.499 -    """
   1.500 -    rc = -xsconstants.XSERR_GENERAL_FAILURE
   1.501 -    errors = ""
   1.502 -    if not on():
   1.503 -        err("No policy active.")
   1.504 -    try:
   1.505 -        rc, errors = acm.chgpolicy(bin_pol, del_array, chg_array)
   1.506 -    except Exception, e:
   1.507 -        pass
   1.508 -    if len(errors) > 0:
   1.509 -        rc = -xsconstants.XSERR_HV_OP_FAILED
   1.510 -    return rc, errors
   1.511 -
   1.512 -
   1.513 -def make_policy(policy_name):
   1.514 -    policy_file = string.join(string.split(policy_name, "."), "/")
   1.515 -    if not os.path.isfile(policy_dir_prefix + "/" + policy_file + "-security_policy.xml"):
   1.516 -        err("Unknown policy \'" + policy_name + "\'")
   1.517 -
   1.518 -    (ret, output) = commands.getstatusoutput(xensec_xml2bin + " -d " + policy_dir_prefix + " " + policy_file)
   1.519 -    if ret:
   1.520 -        err("Creating policy failed:\n" + output)
   1.521 -
   1.522 -def load_policy(policy_name):
   1.523 -    global active_policy
   1.524 -    policy_file = policy_dir_prefix + "/" + string.join(string.split(policy_name, "."), "/")
   1.525 -    if not os.path.isfile(policy_file + ".bin"):
   1.526 -        if os.path.isfile(policy_file + "-security_policy.xml"):
   1.527 -            err("Binary file does not exist." +
   1.528 -                "Please use makepolicy to build the policy binary.")
   1.529 -        else:
   1.530 -            err("Unknown Policy " + policy_name)
   1.531 -
   1.532 -    #require this policy to be the first or the same as installed
   1.533 -    if active_policy not in ['DEFAULT', policy_name]:
   1.534 -        err("Active policy \'" + active_policy +
   1.535 -            "\' incompatible with new policy \'" + policy_name + "\'")
   1.536 -    (ret, output) = commands.getstatusoutput(xensec_tool + " loadpolicy " + policy_file + ".bin")
   1.537 -    if ret:
   1.538 -        err("Loading policy failed:\n" + output)
   1.539 -    else:
   1.540 -        # refresh active policy
   1.541 -        refresh_security_policy()
   1.542 -
   1.543 -
   1.544 -
   1.545 -def dump_policy():
   1.546 -    if active_policy in ['NULL', 'INACTIVE']:
   1.547 -        err("\'" + active_policy + "\' policy. Nothing to dump.")
   1.548 -
   1.549 -    (ret, output) = commands.getstatusoutput(xensec_tool + " getpolicy")
   1.550 -    if ret:
   1.551 -       err("Dumping hypervisor policy failed:\n" + output)
   1.552 -    print output
   1.553 -
   1.554 -
   1.555 -
   1.556 -def list_labels(policy_name, condition):
   1.557 -    if (not policy_name) and (active_policy) in ["NULL", "INACTIVE", "DEFAULT"]:
   1.558 -        err("Current policy \'" + active_policy + "\' has no labels defined.\n")
   1.559 -
   1.560 -    (primary, secondary, f, pol_exists) = getmapfile(policy_name)
   1.561 -    if not f:
   1.562 -        if pol_exists:
   1.563 -            err("Cannot find mapfile for policy \'" + policy_name +
   1.564 -                "\'.\nPlease use makepolicy to create mapping file.")
   1.565 -        else:
   1.566 -            err("Unknown policy \'" + policy_name + "\'")
   1.567 -
   1.568 -    labels = []
   1.569 -    for line in f:
   1.570 -        if condition.match(line):
   1.571 -            label = line.split()[3]
   1.572 -            if label not in labels:
   1.573 -                labels.append(label)
   1.574 -    return labels
   1.575 -
   1.576 -
   1.577 -def get_res_label(resource):
   1.578 -    """Returns resource label information (policytype, label, policy) if
   1.579 -       it exists. Otherwise returns null label and policy.
   1.580 -    """
   1.581 -    def default_res_label():
   1.582 -        ssidref = NULL_SSIDREF
   1.583 -        if on():
   1.584 -            label = ssidref2label(ssidref)
   1.585 -        else:
   1.586 -            label = None
   1.587 -        return (xsconstants.ACM_POLICY_ID, 'NULL', label)
   1.588 -
   1.589 -
   1.590 -    tmp = get_resource_label(resource)
   1.591 -    if len(tmp) == 2:
   1.592 -        policytype = xsconstants.ACM_POLICY_ID
   1.593 -        policy, label = tmp
   1.594 -    elif len(tmp) == 3:
   1.595 -        policytype, policy, label = tmp
   1.596 -    else:
   1.597 -        policytype, policy, label = default_res_label()
   1.598 -
   1.599 -    return (policytype, label, policy)
   1.600 -
   1.601 -
   1.602 -def get_res_security_details(resource):
   1.603 -    """Returns the (label, ssidref, policy) associated with a given
   1.604 -       resource from the global resource label file.
   1.605 -    """
   1.606 -    def default_security_details():
   1.607 -        ssidref = NULL_SSIDREF
   1.608 -        if on():
   1.609 -            label = ssidref2label(ssidref)
   1.610 -        else:
   1.611 -            label = None
   1.612 -        policy = active_policy
   1.613 -        return (label, ssidref, policy)
   1.614 -
   1.615 -    (label, ssidref, policy) = default_security_details()
   1.616 -
   1.617 -    # find the entry associated with this resource
   1.618 -    (policytype, label, policy) = get_res_label(resource)
   1.619 -    if policy == 'NULL':
   1.620 -        log.info("Resource label for "+resource+" not in file, using DEFAULT.")
   1.621 -        return default_security_details()
   1.622 -
   1.623 -    # is this resource label for the running policy?
   1.624 -    if policy == active_policy:
   1.625 -        ssidref = label2ssidref(label, policy, 'res')
   1.626 -    else:
   1.627 -        log.info("Resource label not for active policy, using DEFAULT.")
   1.628 -        return default_security_details()
   1.629 -
   1.630 -    return (label, ssidref, policy)
   1.631 -
   1.632 -def security_label_to_details(seclab):
   1.633 -    """ Convert a Xen-API type of security label into details """
   1.634 -    def default_security_details():
   1.635 -        ssidref = NULL_SSIDREF
   1.636 -        if on():
   1.637 -            label = ssidref2label(ssidref)
   1.638 -        else:
   1.639 -            label = None
   1.640 -        policy = active_policy
   1.641 -        return (label, ssidref, policy)
   1.642 -
   1.643 -    (policytype, policy, label) = seclab.split(":")
   1.644 -
   1.645 -    # is this resource label for the running policy?
   1.646 -    if policy == active_policy:
   1.647 -        ssidref = label2ssidref(label, policy, 'res')
   1.648 -    else:
   1.649 -        log.info("Resource label not for active policy, using DEFAULT.")
   1.650 -        return default_security_details()
   1.651 -
   1.652 -    return (label, ssidref, policy)
   1.653 -
   1.654 -def unify_resname(resource, mustexist=True):
   1.655 -    """Makes all resource locations absolute. In case of physical
   1.656 -    resources, '/dev/' is added to local file names"""
   1.657 -
   1.658 -    if not resource:
   1.659 -        return resource
   1.660 -
   1.661 -    # sanity check on resource name
   1.662 -    try:
   1.663 -        (typ, resfile) = resource.split(":", 1)
   1.664 -    except:
   1.665 -        err("Resource spec '%s' contains no ':' delimiter" % resource)
   1.666 -
   1.667 -    if typ == "tap":
   1.668 -        try:
   1.669 -            (subtype, resfile) = resfile.split(":")
   1.670 -        except:
   1.671 -            err("Resource spec '%s' contains no tap subtype" % resource)
   1.672 -
   1.673 -    import os
   1.674 -    if typ in ["phy", "tap"]:
   1.675 -        if not resfile.startswith("/"):
   1.676 -            resfile = "/dev/" + resfile
   1.677 -        if mustexist:
   1.678 -            stats = os.lstat(resfile)
   1.679 -            if stat.S_ISLNK(stats[stat.ST_MODE]):
   1.680 -                resolved = os.readlink(resfile)
   1.681 -                if resolved[0] != "/":
   1.682 -                    resfile = os.path.join(os.path.dirname(resfile), resolved)
   1.683 -                    resfile = os.path.abspath(resfile)
   1.684 -                else:
   1.685 -                    resfile = resolved
   1.686 -                stats = os.lstat(resfile)
   1.687 -            if not (stat.S_ISBLK(stats[stat.ST_MODE])):
   1.688 -                err("Invalid resource")
   1.689 -
   1.690 -    if typ in [ "file", "tap" ]:
   1.691 -        if mustexist:
   1.692 -            stats = os.lstat(resfile)
   1.693 -            if stat.S_ISLNK(stats[stat.ST_MODE]):
   1.694 -                resfile = os.readlink(resfile)
   1.695 -                stats = os.lstat(resfile)
   1.696 -            if not stat.S_ISREG(stats[stat.ST_MODE]):
   1.697 -                err("Invalid resource")
   1.698 -
   1.699 -    #file: resources must specified with absolute path
   1.700 -    #vlan resources don't start with '/'
   1.701 -    if typ != "vlan":
   1.702 -        if (not resfile.startswith("/")) or \
   1.703 -           (mustexist and not os.path.exists(resfile)):
   1.704 -            err("Invalid resource.")
   1.705 -
   1.706 -    # from here on absolute file names with resources
   1.707 -    if typ == "tap":
   1.708 -        typ = typ + ":" + subtype
   1.709 -    resource = typ + ":" + resfile
   1.710 -    return resource
   1.711 -
   1.712 -
   1.713 -def res_security_check(resource, domain_label):
   1.714 -    """Checks if the given resource can be used by the given domain
   1.715 -       label.  Returns 1 if the resource can be used, otherwise 0.
   1.716 -    """
   1.717 -    rtnval = 1
   1.718 -
   1.719 -    # if security is on, ask the hypervisor for a decision
   1.720 -    if on():
   1.721 -        #build canonical resource name
   1.722 -        resource = unify_resname(resource)
   1.723 -
   1.724 -        (label, ssidref, policy) = get_res_security_details(resource)
   1.725 -        domac = ['access_control']
   1.726 -        domac.append(['policy', active_policy])
   1.727 -        domac.append(['label', domain_label])
   1.728 -        domac.append(['type', 'dom'])
   1.729 -        decision = get_decision(domac, ['ssidref', str(ssidref)])
   1.730 -
   1.731 -        # provide descriptive error messages
   1.732 -        if decision == 'DENIED':
   1.733 -            if label == ssidref2label(NULL_SSIDREF):
   1.734 -                raise ACMError("Resource '"+resource+"' is not labeled")
   1.735 -                rtnval = 0
   1.736 -            else:
   1.737 -                raise ACMError("Permission denied for resource '"+resource+"' because label '"+label+"' is not allowed")
   1.738 -                rtnval = 0
   1.739 -
   1.740 -    # security is off, make sure resource isn't labeled
   1.741 -    else:
   1.742 -        # Note, we can't canonicalise the resource here, because people using
   1.743 -        # xm without ACM are free to use relative paths.
   1.744 -        (policytype, label, policy) = get_res_label(resource)
   1.745 -        if policy != 'NULL':
   1.746 -            raise ACMError("Security is off, but '"+resource+"' is labeled")
   1.747 -            rtnval = 0
   1.748 -
   1.749 -    return rtnval
   1.750 -
   1.751 -def res_security_check_xapi(rlabel, rssidref, rpolicy, xapi_dom_label):
   1.752 -    """Checks if the given resource can be used by the given domain
   1.753 -       label.  Returns 1 if the resource can be used, otherwise 0.
   1.754 -    """
   1.755 -    rtnval = 1
   1.756 -    # if security is on, ask the hypervisor for a decision
   1.757 -    if on():
   1.758 -        typ, dpolicy, domain_label = xapi_dom_label.split(":")
   1.759 -        if not dpolicy or not domain_label:
   1.760 -            raise VmError("VM security label in wrong format.")
   1.761 -        if active_policy != rpolicy:
   1.762 -            raise VmError("Resource's policy '%s' != active policy '%s'" %
   1.763 -                          (rpolicy, active_policy))
   1.764 -        domac = ['access_control']
   1.765 -        domac.append(['policy', active_policy])
   1.766 -        domac.append(['label', domain_label])
   1.767 -        domac.append(['type', 'dom'])
   1.768 -        decision = get_decision(domac, ['ssidref', str(rssidref)])
   1.769 -
   1.770 -        log.info("Access Control Decision : %s" % decision)
   1.771 -        # provide descriptive error messages
   1.772 -        if decision == 'DENIED':
   1.773 -            if rlabel == ssidref2label(NULL_SSIDREF):
   1.774 -                #raise ACMError("Resource is not labeled")
   1.775 -                rtnval = 0
   1.776 -            else:
   1.777 -                #raise ACMError("Permission denied for resource because label '"+rlabel+"' is not allowed")
   1.778 -                rtnval = 0
   1.779 -
   1.780 -    # security is off, make sure resource isn't labeled
   1.781 -    else:
   1.782 -        # Note, we can't canonicalise the resource here, because people using
   1.783 -        # xm without ACM are free to use relative paths.
   1.784 -        if rpolicy != 'NULL':
   1.785 -            #raise ACMError("Security is off, but resource is labeled")
   1.786 -            rtnval = 0
   1.787 -
   1.788 -    return rtnval
   1.789 -
   1.790 -
   1.791 -def validate_label(label, policyref):
   1.792 -    """
   1.793 -       Make sure that this label is part of the currently enforced policy
   1.794 -       and that it reference the current policy.
   1.795 -    """
   1.796 -    rc = xsconstants.XSERR_SUCCESS
   1.797 -    from xen.xend.XendXSPolicyAdmin import XSPolicyAdminInstance
   1.798 -    curpol = XSPolicyAdminInstance().get_loaded_policy()
   1.799 -    if not curpol or curpol.get_name() != policyref:
   1.800 -        rc = -xsconstants.XSERR_BAD_LABEL
   1.801 -    else:
   1.802 -        try:
   1.803 -            label2ssidref(label, curpol.get_name() , 'res')
   1.804 -        except:
   1.805 -            rc = -xsconstants.XSERR_BAD_LABEL
   1.806 -    return rc
   1.807 -
   1.808 -
   1.809 -def set_resource_label_xapi(resource, reslabel_xapi, oldlabel_xapi):
   1.810 -    """Assign a resource label to a resource
   1.811 -    @param resource: The name of a resource, i.e., "phy:/dev/hda", or
   1.812 -              "tap:qcow:/path/to/file.qcow"
   1.813 -
   1.814 -    @param reslabel_xapi: A resource label foramtted as in all other parts of
   1.815 -                          the Xen-API, i.e., ACM:xm-test:blue"
   1.816 -    @rtype: int
   1.817 -    @return Success (0) or failure value (< 0)
   1.818 -    """
   1.819 -    olabel = ""
   1.820 -    if reslabel_xapi == "":
   1.821 -        return rm_resource_label(resource, oldlabel_xapi)
   1.822 -    typ, policyref, label = reslabel_xapi.split(":")
   1.823 -    if typ != xsconstants.ACM_POLICY_ID:
   1.824 -        return -xsconstants.XSERR_WRONG_POLICY_TYPE
   1.825 -    if not policyref or not label:
   1.826 -        return -xsconstants.XSERR_BAD_LABEL_FORMAT
   1.827 -    if oldlabel_xapi not in [ "" ]:
   1.828 -        tmp = oldlabel_xapi.split(":")
   1.829 -        if len(tmp) != 3:
   1.830 -            return -xsconstants.XSERR_BAD_LABEL_FORMAT
   1.831 -        otyp, opolicyref, olabel = tmp
   1.832 -        # Only ACM is supported
   1.833 -        if otyp != xsconstants.ACM_POLICY_ID  and \
   1.834 -           otyp != xsconstants.INVALID_POLICY_PREFIX + \
   1.835 -                   xsconstants.ACM_POLICY_ID:
   1.836 -            return -xsconstants.XSERR_WRONG_POLICY_TYPE
   1.837 -    rc = validate_label(label, policyref)
   1.838 -    if rc != xsconstants.XSERR_SUCCESS:
   1.839 -        return rc
   1.840 -    return set_resource_label(resource, typ, policyref, label, olabel)
   1.841 -
   1.842 -
   1.843 -def is_resource_in_use(resource):
   1.844 -    """
   1.845 -       Domain-0 'owns' resources of type 'VLAN', the rest are owned by
   1.846 -       the guests.
   1.847 -    """
   1.848 -    from xen.xend import XendDomain
   1.849 -    lst = []
   1.850 -    if resource.startswith('vlan'):
   1.851 -        from xen.xend.XendXSPolicyAdmin import XSPolicyAdminInstance
   1.852 -        curpol = XSPolicyAdminInstance().get_loaded_policy()
   1.853 -        policytype, label, policy = get_res_label(resource)
   1.854 -        if curpol and \
   1.855 -           policytype == xsconstants.ACM_POLICY_ID and \
   1.856 -           policy == curpol.get_name() and \
   1.857 -           label in curpol.policy_get_resourcelabel_names():
   1.858 -            # VLAN is in use.
   1.859 -            lst.append(XendDomain.instance().
   1.860 -                         get_vm_by_uuid(XendDomain.DOM0_UUID))
   1.861 -    else:
   1.862 -        dominfos = XendDomain.instance().list('all')
   1.863 -        for dominfo in dominfos:
   1.864 -            if is_resource_in_use_by_dom(dominfo, resource):
   1.865 -                lst.append(dominfo)
   1.866 -    return lst
   1.867 -
   1.868 -def devices_equal(res1, res2, mustexist=True):
   1.869 -    """ Determine whether two devices are equal """
   1.870 -    return (unify_resname(res1, mustexist) ==
   1.871 -            unify_resname(res2, mustexist))
   1.872 -
   1.873 -def is_resource_in_use_by_dom(dominfo, resource):
   1.874 -    """ Determine whether a resources is in use by a given domain
   1.875 -        @return True or False
   1.876 -    """
   1.877 -    if not dominfo.domid:
   1.878 -        return False
   1.879 -    if dominfo._stateGet() not in [ DOM_STATE_RUNNING ]:
   1.880 -        return False
   1.881 -    devs = dominfo.info['devices']
   1.882 -    uuids = devs.keys()
   1.883 -    for uuid in uuids:
   1.884 -        dev = devs[uuid]
   1.885 -        if len(dev) >= 2 and dev[1].has_key('uname'):
   1.886 -            # dev[0] is type, i.e. 'vbd'
   1.887 -            if devices_equal(dev[1]['uname'], resource, mustexist=False):
   1.888 -                log.info("RESOURCE IN USE: Domain %d uses %s." %
   1.889 -                         (dominfo.domid, resource))
   1.890 -                return True
   1.891 -    return False
   1.892 -
   1.893 -
   1.894 -def get_domain_resources(dominfo):
   1.895 -    """ Collect all resources of a domain in a map where each entry of
   1.896 -        the map is a list.
   1.897 -        Entries are strored in the following formats:
   1.898 -          tap:qcow:/path/xyz.qcow
   1.899 -    """
   1.900 -    resources = { 'vbd' : [], 'tap' : [], 'vif' : []}
   1.901 -    devs = dominfo.info['devices']
   1.902 -    uuids = devs.keys()
   1.903 -    for uuid in uuids:
   1.904 -        dev = devs[uuid]
   1.905 -        typ = dev[0]
   1.906 -        if typ in [ 'vbd', 'tap' ]:
   1.907 -            resources[typ].append(dev[1]['uname'])
   1.908 -        if typ in [ 'vif' ]:
   1.909 -            sec_lab = dev[1].get('security_label')
   1.910 -            if sec_lab:
   1.911 -                resources[typ].append(sec_lab)
   1.912 -            else:
   1.913 -                # !!! This should really get the label of the domain
   1.914 -                # or at least a resource label that has the same STE type
   1.915 -                # as the domain has
   1.916 -                from xen.util.acmpolicy import ACM_LABEL_UNLABELED
   1.917 -                resources[typ].append("%s:%s:%s" %
   1.918 -                                      (xsconstants.ACM_POLICY_ID,
   1.919 -                                       active_policy,
   1.920 -                                       ACM_LABEL_UNLABELED))
   1.921 -
   1.922 -    return resources
   1.923 -
   1.924 -
   1.925 -def resources_compatible_with_vmlabel(xspol, dominfo, vmlabel):
   1.926 -    """
   1.927 -       Check whether the resources' labels are compatible with the
   1.928 -       given VM label. This is a function to be used when for example
   1.929 -       a running domain is to get the new label 'vmlabel'
   1.930 -    """
   1.931 -    if not xspol:
   1.932 -        return False
   1.933 -
   1.934 -    try:
   1.935 -        __resfile_lock.acquire()
   1.936 -        try:
   1.937 -            access_control = dictio.dict_read("resources",
   1.938 -                                              res_label_filename)
   1.939 -        except:
   1.940 -            # No labeled resources -> must be compatible
   1.941 -            return True
   1.942 -        return __resources_compatible_with_vmlabel(xspol, dominfo, vmlabel,
   1.943 -                                                   access_control)
   1.944 -    finally:
   1.945 -        __resfile_lock.release()
   1.946 -    return False
   1.947 -
   1.948 -
   1.949 -def __resources_compatible_with_vmlabel(xspol, dominfo, vmlabel,
   1.950 -                                        access_control,
   1.951 -                                        is_policy_update=False):
   1.952 -    """
   1.953 -        Check whether the resources' labels are compatible with the
   1.954 -        given VM label. The access_control parameter provides a
   1.955 -        dictionary of the resource name to resource label mappings
   1.956 -        under which the evaluation should be done.
   1.957 -        Call this only for a paused or running domain.
   1.958 -    """
   1.959 -    def collect_labels(reslabels, s_label, polname):
   1.960 -        if len(s_label) != 3 or polname != s_label[1]:
   1.961 -            return False
   1.962 -        label = s_label[2]
   1.963 -        if not label in reslabels:
   1.964 -            reslabels.append(label)
   1.965 -        return True
   1.966 -
   1.967 -    resources = get_domain_resources(dominfo)
   1.968 -    reslabels = []  # all resource labels
   1.969 -
   1.970 -    polname = xspol.get_name()
   1.971 -    for key, value in resources.items():
   1.972 -        if key in [ 'vbd', 'tap' ]:
   1.973 -            for res in resources[key]:
   1.974 -                try:
   1.975 -                    label = access_control[res]
   1.976 -                    if not collect_labels(reslabels, label, polname):
   1.977 -                        return False
   1.978 -                except:
   1.979 -                    return False
   1.980 -        elif key in [ 'vif' ]:
   1.981 -            for xapi_label in value:
   1.982 -                label = xapi_label.split(":")
   1.983 -                from xen.util.acmpolicy import ACM_LABEL_UNLABELED
   1.984 -                if not (is_policy_update and \
   1.985 -                        label[2] == ACM_LABEL_UNLABELED):
   1.986 -                    if not collect_labels(reslabels, label, polname):
   1.987 -                        return False
   1.988 -        else:
   1.989 -            log.error("Unhandled device type: %s" % key)
   1.990 -            return False
   1.991 -
   1.992 -    # Check that all resource labes have a common STE type with the
   1.993 -    # vmlabel
   1.994 -    if len(reslabels) > 0:
   1.995 -        rc = xspol.policy_check_vmlabel_against_reslabels(vmlabel, reslabels)
   1.996 -    else:
   1.997 -        rc = True
   1.998 -    log.info("vmlabel=%s, reslabels=%s, rc=%s" %
   1.999 -             (vmlabel, reslabels, str(rc)))
  1.1000 -    return rc;
  1.1001 -
  1.1002 -def set_resource_label(resource, policytype, policyref, reslabel, \
  1.1003 -                       oreslabel = None):
  1.1004 -    """Assign a label to a resource
  1.1005 -       If the old label (oreslabel) is given, then the resource must have
  1.1006 -       that old label.
  1.1007 -       A resource label may be changed if
  1.1008 -       - the resource is not in use
  1.1009 -    @param resource  : The name of a resource, i.e., "phy:/dev/hda"
  1.1010 -    @param policyref : The name of the policy
  1.1011 -    @param reslabel     : the resource label within the policy
  1.1012 -    @param oreslabel    : optional current resource label
  1.1013 -
  1.1014 -    @rtype: int
  1.1015 -    @return Success (0) or failure value (< 0)
  1.1016 -    """
  1.1017 -    try:
  1.1018 -        resource = unify_resname(resource, mustexist=False)
  1.1019 -    except Exception:
  1.1020 -        return -xsconstants.XSERR_BAD_RESOURCE_FORMAT
  1.1021 -
  1.1022 -    domains = is_resource_in_use(resource)
  1.1023 -    if len(domains) > 0:
  1.1024 -        return -xsconstants.XSERR_RESOURCE_IN_USE
  1.1025 -
  1.1026 -    try:
  1.1027 -        __resfile_lock.acquire()
  1.1028 -        access_control = {}
  1.1029 -        try:
  1.1030 -             access_control = dictio.dict_read("resources", res_label_filename)
  1.1031 -        except:
  1.1032 -            pass
  1.1033 -        if oreslabel:
  1.1034 -            if not access_control.has_key(resource):
  1.1035 -                return -xsconstants.XSERR_BAD_LABEL
  1.1036 -            tmp = access_control[resource]
  1.1037 -            if len(tmp) != 3:
  1.1038 -                return -xsconstants.XSERR_BAD_LABEL
  1.1039 -            if tmp[2] != oreslabel:
  1.1040 -                return -xsconstants.XSERR_BAD_LABEL
  1.1041 -        if reslabel != "":
  1.1042 -            new_entry = { resource : tuple([policytype, policyref, reslabel])}
  1.1043 -            access_control.update(new_entry)
  1.1044 -        else:
  1.1045 -            if access_control.has_key(resource):
  1.1046 -                del access_control[resource]
  1.1047 -        dictio.dict_write(access_control, "resources", res_label_filename)
  1.1048 -    finally:
  1.1049 -        __resfile_lock.release()
  1.1050 -    return xsconstants.XSERR_SUCCESS
  1.1051 -
  1.1052 -def rm_resource_label(resource, oldlabel_xapi):
  1.1053 -    """Remove a resource label from a physical resource
  1.1054 -    @param resource: The name of a resource, i.e., "phy:/dev/hda"
  1.1055 -
  1.1056 -    @rtype: int
  1.1057 -    @return Success (0) or failure value (< 0)
  1.1058 -    """
  1.1059 -    tmp = oldlabel_xapi.split(":")
  1.1060 -    if len(tmp) != 3:
  1.1061 -        return -xsconstants.XSERR_BAD_LABEL_FORMAT
  1.1062 -    otyp, opolicyref, olabel = tmp
  1.1063 -    # Only ACM is supported
  1.1064 -    if otyp != xsconstants.ACM_POLICY_ID and \
  1.1065 -       otyp != xsconstants.INVALID_POLICY_PREFIX + xsconstants.ACM_POLICY_ID:
  1.1066 -        return -xsconstants.XSERR_WRONG_POLICY_TYPE
  1.1067 -    return set_resource_label(resource, "", "", "", olabel)
  1.1068 -
  1.1069 -def get_resource_label_xapi(resource):
  1.1070 -    """Get the assigned resource label of a physical resource
  1.1071 -      in the format used by then Xen-API, i.e., "ACM:xm-test:blue"
  1.1072 -
  1.1073 -      @rtype: string
  1.1074 -      @return the string representing policy type, policy name and label of
  1.1075 -              the resource
  1.1076 -    """
  1.1077 -    res = get_resource_label(resource)
  1.1078 -    return format_resource_label(res)
  1.1079 -
  1.1080 -def format_resource_label(res):
  1.1081 -    if res:
  1.1082 -        if len(res) == 2:
  1.1083 -            return xsconstants.ACM_POLICY_ID + ":" + res[0] + ":" + res[1]
  1.1084 -        if len(res) == 3:
  1.1085 -            return ":".join(res)
  1.1086 -    return ""
  1.1087 -
  1.1088 -def get_resource_label(resource):
  1.1089 -    """Get the assigned resource label of a given resource
  1.1090 -    @param resource: The name of a resource, i.e., "phy:/dev/hda"
  1.1091 -
  1.1092 -    @rtype: list
  1.1093 -    @return tuple of (policy name, resource label), i.e., (xm-test, blue)
  1.1094 -    """
  1.1095 -    try:
  1.1096 -        resource = unify_resname(resource, mustexist=False)
  1.1097 -    except Exception:
  1.1098 -        return []
  1.1099 -
  1.1100 -    reslabel_map = get_labeled_resources()
  1.1101 -
  1.1102 -    if reslabel_map.has_key(resource):
  1.1103 -        return list(reslabel_map[resource])
  1.1104 -    else:
  1.1105 -        #Try to resolve each label entry
  1.1106 -        for key, value in reslabel_map.items():
  1.1107 -            try:
  1.1108 -                if resource == unify_resname(key):
  1.1109 -                    return list(value)
  1.1110 -            except:
  1.1111 -                pass
  1.1112 -
  1.1113 -    return []
  1.1114 -
  1.1115 -
  1.1116 -def get_labeled_resources_xapi():
  1.1117 -    """ Get a map of all labeled resource with the labels formatted in the
  1.1118 -        xen-api resource label format.
  1.1119 -    """
  1.1120 -    reslabel_map = get_labeled_resources()
  1.1121 -    for key, labeldata in reslabel_map.items():
  1.1122 -        reslabel_map[key] = format_resource_label(labeldata)
  1.1123 -    return reslabel_map
  1.1124 -
  1.1125 -
  1.1126 -def get_labeled_resources():
  1.1127 -    """Get a map of all labeled resources
  1.1128 -    @rtype: list
  1.1129 -    @return list of labeled resources
  1.1130 -    """
  1.1131 -    try:
  1.1132 -        __resfile_lock.acquire()
  1.1133 -        try:
  1.1134 -            access_control = dictio.dict_read("resources", res_label_filename)
  1.1135 -        except:
  1.1136 -            return {}
  1.1137 -    finally:
  1.1138 -        __resfile_lock.release()
  1.1139 -    return access_control
  1.1140 -
  1.1141 -
  1.1142 -def relabel_domains(relabel_list):
  1.1143 -    """
  1.1144 -      Relabel the given domains to have a new ssidref.
  1.1145 -      @param relabel_list: a list containing tuples of domid, ssidref
  1.1146 -                           example: [ [0, 0x00020002] ]
  1.1147 -    """
  1.1148 -    rel_rules = ""
  1.1149 -    for r in relabel_list:
  1.1150 -        log.info("Relabeling domain with domid %d to new ssidref 0x%08x",
  1.1151 -                r[0], r[1])
  1.1152 -        rel_rules += struct.pack("ii", r[0], r[1])
  1.1153 -    try:
  1.1154 -        rc, errors = acm.relabel_domains(rel_rules)
  1.1155 -    except Exception, e:
  1.1156 -        log.info("Error after relabel_domains: %s" % str(e))
  1.1157 -        rc = -xsconstants.XSERR_GENERAL_FAILURE
  1.1158 -        errors = ""
  1.1159 -    if (len(errors) > 0):
  1.1160 -        rc = -xsconstants.XSERR_HV_OP_FAILED
  1.1161 -    return rc, errors
  1.1162 -
  1.1163 -
  1.1164 -def change_acm_policy(bin_pol, del_array, chg_array,
  1.1165 -                      vmlabel_map, reslabel_map, cur_acmpol, new_acmpol):
  1.1166 -    """
  1.1167 -       Change the ACM policy of the system by relabeling
  1.1168 -       domains and resources first and doing some access checks.
  1.1169 -       Then update the policy in the hypervisor. If this is all successful,
  1.1170 -       relabel the domains permanently and commit the relabed resources.
  1.1171 -
  1.1172 -       Need to do / check the following:
  1.1173 -        - relabel all resources where there is a 'from' field in
  1.1174 -          the policy. [ NOT DOING THIS: and mark those as unlabeled where the label
  1.1175 -          does not appear in the new policy anymore (deletion) ]
  1.1176 -        - relabel all VMs where there is a 'from' field in the
  1.1177 -          policy and mark those as unlabeled where the label
  1.1178 -          does not appear in the new policy anymore; no running
  1.1179 -          or paused VM may be unlabeled through this
  1.1180 -        - check that under the new labeling conditions the VMs
  1.1181 -          still have access to their resources as before. Unlabeled
  1.1182 -          resources are inaccessible. If this check fails, the
  1.1183 -          update failed.
  1.1184 -        - Attempt changes in the hypervisor; if this step fails,
  1.1185 -          roll back the relabeling of resources and VMs
  1.1186 -        - Make the relabeling of resources and VMs permanent
  1.1187 -    """
  1.1188 -    rc = xsconstants.XSERR_SUCCESS
  1.1189 -
  1.1190 -    domain_label_map = {}
  1.1191 -    new_policyname = new_acmpol.get_name()
  1.1192 -    new_policytype = new_acmpol.get_type_name()
  1.1193 -    cur_policyname = cur_acmpol.get_name()
  1.1194 -    cur_policytype = cur_acmpol.get_type_name()
  1.1195 -    polnew_reslabels = new_acmpol.policy_get_resourcelabel_names()
  1.1196 -    errors=""
  1.1197 -
  1.1198 -    try:
  1.1199 -        __resfile_lock.acquire()
  1.1200 -        mapfile_lock()
  1.1201 -
  1.1202 -        # Get all domains' dominfo.
  1.1203 -        from xen.xend import XendDomain
  1.1204 -        dominfos = XendDomain.instance().list('all')
  1.1205 -
  1.1206 -        log.info("----------------------------------------------")
  1.1207 -        # relabel resources
  1.1208 -
  1.1209 -        access_control = {}
  1.1210 -        try:
  1.1211 -            access_control = dictio.dict_read("resources", res_label_filename)
  1.1212 -        except:
  1.1213 -            pass
  1.1214 -        for key, labeldata in access_control.items():
  1.1215 -            if len(labeldata) == 2:
  1.1216 -                policy, label = labeldata
  1.1217 -                policytype = xsconstants.ACM_POLICY_ID
  1.1218 -            elif len(labeldata) == 3:
  1.1219 -                policytype, policy, label = labeldata
  1.1220 -            else:
  1.1221 -                return -xsconstants.XSERR_BAD_LABEL_FORMAT, ""
  1.1222 -
  1.1223 -            if policytype != cur_policytype or \
  1.1224 -               policy     != cur_policyname:
  1.1225 -                continue
  1.1226 -
  1.1227 -            # label been renamed or deleted?
  1.1228 -            if reslabel_map.has_key(label) and cur_policyname == policy:
  1.1229 -                label = reslabel_map[label]
  1.1230 -            elif label not in polnew_reslabels:
  1.1231 -                policytype = xsconstants.INVALID_POLICY_PREFIX + policytype
  1.1232 -            # Update entry
  1.1233 -            access_control[key] = \
  1.1234 -                   tuple([ policytype, new_policyname, label ])
  1.1235 -
  1.1236 -        # All resources have new labels in the access_control map
  1.1237 -        # There may still be labels in there that are invalid now.
  1.1238 -
  1.1239 -        # Do this in memory without writing to disk:
  1.1240 -        #  - Relabel all domains independent of whether they are running
  1.1241 -        #    or not
  1.1242 -        #  - later write back to config files
  1.1243 -        polnew_vmlabels = new_acmpol.policy_get_virtualmachinelabel_names()
  1.1244 -
  1.1245 -        for dominfo in dominfos:
  1.1246 -            sec_lab = dominfo.get_security_label()
  1.1247 -            if not sec_lab:
  1.1248 -                continue
  1.1249 -            policytype, policy, vmlabel = sec_lab.split(":")
  1.1250 -            name  = dominfo.getName()
  1.1251 -
  1.1252 -            if policytype != cur_policytype or \
  1.1253 -               policy     != cur_policyname:
  1.1254 -                continue
  1.1255 -
  1.1256 -            new_vmlabel = vmlabel
  1.1257 -            if vmlabel_map.has_key(vmlabel):
  1.1258 -                new_vmlabel = vmlabel_map[vmlabel]
  1.1259 -            if new_vmlabel not in polnew_vmlabels:
  1.1260 -                policytype = xsconstants.INVALID_POLICY_PREFIX + policytype
  1.1261 -            new_seclab = "%s:%s:%s" % \
  1.1262 -                    (policytype, new_policyname, new_vmlabel)
  1.1263 -
  1.1264 -            domain_label_map[dominfo] = [ sec_lab, new_seclab ]
  1.1265 -
  1.1266 -            if dominfo._stateGet() in (DOM_STATE_PAUSED, DOM_STATE_RUNNING):
  1.1267 -                compatible = __resources_compatible_with_vmlabel(new_acmpol,
  1.1268 -                                                      dominfo,
  1.1269 -                                                      new_vmlabel,
  1.1270 -                                                      access_control,
  1.1271 -                                                      is_policy_update=True)
  1.1272 -                log.info("Domain %s with new label '%s' can access its "
  1.1273 -                         "resources? : %s" %
  1.1274 -                         (name, new_vmlabel, str(compatible)))
  1.1275 -                log.info("VM labels in new policy: %s" %
  1.1276 -                         new_acmpol.policy_get_virtualmachinelabel_names())
  1.1277 -                if not compatible:
  1.1278 -                    return (-xsconstants.XSERR_RESOURCE_ACCESS, "")
  1.1279 -
  1.1280 -        rc, errors = hv_chg_policy(bin_pol, del_array, chg_array)
  1.1281 -        if rc == 0:
  1.1282 -            # Write the relabeled resources back into the file
  1.1283 -            dictio.dict_write(access_control, "resources", res_label_filename)
  1.1284 -            # Properly update all VMs to their new labels
  1.1285 -            for dominfo, labels in domain_label_map.items():
  1.1286 -                sec_lab, new_seclab = labels
  1.1287 -                if sec_lab != new_seclab:
  1.1288 -                    log.info("Updating domain %s to new label '%s'." % \
  1.1289 -                             (dominfo.getName(), new_seclab))
  1.1290 -                    # This better be working!
  1.1291 -                    res = dominfo.set_security_label(new_seclab,
  1.1292 -                                                     sec_lab,
  1.1293 -                                                     new_acmpol,
  1.1294 -                                                     cur_acmpol)
  1.1295 -                    if res[0] != xsconstants.XSERR_SUCCESS:
  1.1296 -                        log.info("ERROR: Could not chg label on domain %s: %s" %
  1.1297 -                                 (dominfo.getName(),
  1.1298 -                                  xsconstants.xserr2string(-int(res[0]))))
  1.1299 -    finally:
  1.1300 -        log.info("----------------------------------------------")
  1.1301 -        mapfile_unlock()
  1.1302 -        __resfile_lock.release()
  1.1303 -
  1.1304 -    return rc, errors
     2.1 --- a/tools/python/xen/util/xsm/acm/acm.py	Thu Sep 06 18:04:42 2007 +0100
     2.2 +++ b/tools/python/xen/util/xsm/acm/acm.py	Thu Sep 06 18:05:18 2007 +0100
     2.3 @@ -838,13 +838,28 @@ def set_resource_label_xapi(resource, re
     2.4  
     2.5  
     2.6  def is_resource_in_use(resource):
     2.7 -    """ Investigate all running domains whether they use this device """
     2.8 +    """
     2.9 +       Domain-0 'owns' resources of type 'VLAN', the rest are owned by
    2.10 +       the guests.
    2.11 +    """
    2.12      from xen.xend import XendDomain
    2.13 -    dominfos = XendDomain.instance().list('all')
    2.14      lst = []
    2.15 -    for dominfo in dominfos:
    2.16 -        if is_resource_in_use_by_dom(dominfo, resource):
    2.17 -            lst.append(dominfo)
    2.18 +    if resource.startswith('vlan'):
    2.19 +        from xen.xend.XendXSPolicyAdmin import XSPolicyAdminInstance
    2.20 +        curpol = XSPolicyAdminInstance().get_loaded_policy()
    2.21 +        policytype, label, policy = get_res_label(resource)
    2.22 +        if curpol and \
    2.23 +           policytype == xsconstants.ACM_POLICY_ID and \
    2.24 +           policy == curpol.get_name() and \
    2.25 +           label in curpol.policy_get_resourcelabel_names():
    2.26 +            # VLAN is in use.
    2.27 +            lst.append(XendDomain.instance().
    2.28 +                         get_vm_by_uuid(XendDomain.DOM0_UUID))
    2.29 +    else:
    2.30 +        dominfos = XendDomain.instance().list('all')
    2.31 +        for dominfo in dominfos:
    2.32 +            if is_resource_in_use_by_dom(dominfo, resource):
    2.33 +                lst.append(dominfo)
    2.34      return lst
    2.35  
    2.36  def devices_equal(res1, res2, mustexist=True):
    2.37 @@ -892,6 +907,10 @@ def get_domain_resources(dominfo):
    2.38              if sec_lab:
    2.39                  resources[typ].append(sec_lab)
    2.40              else:
    2.41 +                # !!! This should really get the label of the domain
    2.42 +                # or at least a resource label that has the same STE type
    2.43 +                # as the domain has
    2.44 +                from xen.util.acmpolicy import ACM_LABEL_UNLABELED
    2.45                  resources[typ].append("%s:%s:%s" %
    2.46                                        (xsconstants.ACM_POLICY_ID,
    2.47                                         active_policy,
    2.48 @@ -915,7 +934,8 @@ def resources_compatible_with_vmlabel(xs
    2.49              access_control = dictio.dict_read("resources",
    2.50                                                res_label_filename)
    2.51          except:
    2.52 -            return False
    2.53 +            # No labeled resources -> must be compatible
    2.54 +            return True
    2.55          return __resources_compatible_with_vmlabel(xspol, dominfo, vmlabel,
    2.56                                                     access_control)
    2.57      finally:
    2.58 @@ -924,12 +944,14 @@ def resources_compatible_with_vmlabel(xs
    2.59  
    2.60  
    2.61  def __resources_compatible_with_vmlabel(xspol, dominfo, vmlabel,
    2.62 -                                        access_control):
    2.63 +                                        access_control,
    2.64 +                                        is_policy_update=False):
    2.65      """
    2.66          Check whether the resources' labels are compatible with the
    2.67          given VM label. The access_control parameter provides a
    2.68          dictionary of the resource name to resource label mappings
    2.69          under which the evaluation should be done.
    2.70 +        Call this only for a paused or running domain.
    2.71      """
    2.72      def collect_labels(reslabels, s_label, polname):
    2.73          if len(s_label) != 3 or polname != s_label[1]:
    2.74 @@ -955,15 +977,23 @@ def __resources_compatible_with_vmlabel(
    2.75          elif key in [ 'vif' ]:
    2.76              for xapi_label in value:
    2.77                  label = xapi_label.split(":")
    2.78 -                if not collect_labels(reslabels, label, polname):
    2.79 -                    return False
    2.80 +                from xen.util.acmpolicy import ACM_LABEL_UNLABELED
    2.81 +                if not (is_policy_update and \
    2.82 +                        label[2] == ACM_LABEL_UNLABELED):
    2.83 +                    if not collect_labels(reslabels, label, polname):
    2.84 +                        return False
    2.85          else:
    2.86              log.error("Unhandled device type: %s" % key)
    2.87              return False
    2.88  
    2.89      # Check that all resource labes have a common STE type with the
    2.90      # vmlabel
    2.91 -    rc = xspol.policy_check_vmlabel_against_reslabels(vmlabel, reslabels)
    2.92 +    if len(reslabels) > 0:
    2.93 +        rc = xspol.policy_check_vmlabel_against_reslabels(vmlabel, reslabels)
    2.94 +    else:
    2.95 +        rc = True
    2.96 +    log.info("vmlabel=%s, reslabels=%s, rc=%s" %
    2.97 +             (vmlabel, reslabels, str(rc)))
    2.98      return rc;
    2.99  
   2.100  def set_resource_label(resource, policytype, policyref, reslabel, \
   2.101 @@ -1176,7 +1206,7 @@ def change_acm_policy(bin_pol, del_array
   2.102          access_control = {}
   2.103          try:
   2.104              access_control = dictio.dict_read("resources", res_label_filename)
   2.105 -        finally:
   2.106 +        except:
   2.107              pass
   2.108          for key, labeldata in access_control.items():
   2.109              if len(labeldata) == 2:
   2.110 @@ -1234,11 +1264,12 @@ def change_acm_policy(bin_pol, del_array
   2.111                  compatible = __resources_compatible_with_vmlabel(new_acmpol,
   2.112                                                        dominfo,
   2.113                                                        new_vmlabel,
   2.114 -                                                      access_control)
   2.115 +                                                      access_control,
   2.116 +                                                      is_policy_update=True)
   2.117                  log.info("Domain %s with new label '%s' can access its "
   2.118                           "resources? : %s" %
   2.119                           (name, new_vmlabel, str(compatible)))
   2.120 -                log.info("VM labels in new domain: %s" %
   2.121 +                log.info("VM labels in new policy: %s" %
   2.122                           new_acmpol.policy_get_virtualmachinelabel_names())
   2.123                  if not compatible:
   2.124                      return (-xsconstants.XSERR_RESOURCE_ACCESS, "")
   2.125 @@ -1252,11 +1283,16 @@ def change_acm_policy(bin_pol, del_array
   2.126                  sec_lab, new_seclab = labels
   2.127                  if sec_lab != new_seclab:
   2.128                      log.info("Updating domain %s to new label '%s'." % \
   2.129 -                             (sec_lab, new_seclab))
   2.130 +                             (dominfo.getName(), new_seclab))
   2.131                      # This better be working!
   2.132 -                    dominfo.set_security_label(new_seclab,
   2.133 -                                               sec_lab,
   2.134 -                                               new_acmpol)
   2.135 +                    res = dominfo.set_security_label(new_seclab,
   2.136 +                                                     sec_lab,
   2.137 +                                                     new_acmpol,
   2.138 +                                                     cur_acmpol)
   2.139 +                    if res[0] != xsconstants.XSERR_SUCCESS:
   2.140 +                        log.info("ERROR: Could not chg label on domain %s: %s" %
   2.141 +                                 (dominfo.getName(),
   2.142 +                                  xsconstants.xserr2string(-int(res[0]))))
   2.143      finally:
   2.144          log.info("----------------------------------------------")
   2.145          mapfile_unlock()