ia64/xen-unstable

changeset 16521:5255eac35270

Implement legacy XML-RPC interface for ACM commands.

This patch implements a (non Xen-API) legacy XML-RPC interface for the
ACM commands and funnels the calls into code introduced by the Xen-API
support for ACM security management. Since some of the functionality
has changed, also the xm applications have changed. In particular the
following old commands have been removed along with some tools the
have become obsolete now:

- loadpolicy (included in: setpolicy)
- makepolicy (included in: setpolicy)
- cfgbootpolicy (included in: setpolicy)

and the following commands been introduced:

- setpolicy
- getpolicy
- resetpolicy

All tools have been adapted to work in Xen-API and legacy XML-RPC
mode. Both modes support the same functionality.

Signed-off-by: Stefan Berger <stefanb@us.ibm.com>
author Keir Fraser <keir.fraser@citrix.com>
date Wed Dec 05 09:44:20 2007 +0000 (2007-12-05)
parents a583f3a7eafc
children 54482c56e435
files docs/man/xm.pod.1 tools/python/xen/util/acmpolicy.py tools/python/xen/util/xsm/acm/acm.py tools/python/xen/util/xsm/dummy/dummy.py tools/python/xen/util/xsm/flask/flask.py tools/python/xen/xend/XendConfig.py tools/python/xen/xend/XendDomainInfo.py tools/python/xen/xend/XendXSPolicyAdmin.py tools/python/xen/xend/server/XMLRPCServer.py tools/python/xen/xm/activatepolicy.py tools/python/xen/xm/addlabel.py tools/python/xen/xm/cfgbootpolicy.py tools/python/xen/xm/create.py tools/python/xen/xm/dry-run.py tools/python/xen/xm/getlabel.py tools/python/xen/xm/getpolicy.py tools/python/xen/xm/labels.py tools/python/xen/xm/loadpolicy.py tools/python/xen/xm/main.py tools/python/xen/xm/makepolicy.py tools/python/xen/xm/resetpolicy.py tools/python/xen/xm/resources.py tools/python/xen/xm/rmlabel.py tools/python/xen/xm/setpolicy.py tools/security/Makefile tools/security/policies/example/client_v1-security_policy.xml tools/security/policies/example/ste/client_v1-security_policy.xml tools/security/secpol_xml2bin.c tools/security/secpol_xml2bin.h tools/xm-test/lib/XmTestLib/acm.py tools/xm-test/tests/security-acm/01_security-acm_basic.py tools/xm-test/tests/security-acm/acm_utils.py
line diff
     1.1 --- a/docs/man/xm.pod.1	Tue Dec 04 22:54:58 2007 +0000
     1.2 +++ b/docs/man/xm.pod.1	Wed Dec 05 09:44:20 2007 +0000
     1.3 @@ -821,15 +821,13 @@ security in Xen, you must compile Xen wi
     1.4  described under "Configuring Security" below. There, you will find
     1.5  also examples of each subcommand described here.
     1.6  
     1.7 -=item B<setpolicy> ACM I<policy> I<[--load|--boot]>
     1.8 +=item B<setpolicy> ACM I<policy>
     1.9  
    1.10  Makes the given ACM policy available to xend as a I<xend-managed policy>.
    1.11  The policy is compiled and a mapping (.map) as well as a binary (.bin)
    1.12 -version of the policy is created. If the option I<--load> is provided
    1.13 -the policy is loaded into Xen. If the option I<--boot> is provided the
    1.14 -system is configure to be loaded with the policy at boot time. If these
    1.15 -options are not provided with the B<setpolicy> subcommand, the
    1.16 -B<activatepolicy> subcommand provides this functionality.
    1.17 +version of the policy is created. The policy is loaded and the system's
    1.18 +bootloader is prepared to boot the system with this policy the next time
    1.19 +it is started.
    1.20  
    1.21  =over 4
    1.22  
    1.23 @@ -844,16 +842,13 @@ global policy root directory.
    1.24  
    1.25  =back
    1.26  
    1.27 -=item B<activatepolicy> I<[--load|--boot]>
    1.28 +=item B<resetpolicy>
    1.29  
    1.30 -Activates the xend-managed policy by loading it into Xen using the
    1.31 -I<--load> option or configures the system to boot with the
    1.32 -xend-managed policy during the next reboot as a result of the
    1.33 -I<--boot> option. The latter is only supported if the system is booted
    1.34 -with the grub boot loader and the default boot title is modified.
    1.35 -It copies the binary policy representation into the /boot directory and
    1.36 -adds a module line specifying the binary policy to the /boot/grub/menu.lst
    1.37 -or /boot/grub/grub.conf file.
    1.38 +Reset the system's policy to the default state where the DEFAULT policy
    1.39 +is loaded and enforced. This operation may fail if for example guest VMs are
    1.40 +running and and one of them uses a different label than what Domain-0
    1.41 +does. It is best to make sure that no guests are running before issuing
    1.42 +this command.
    1.43  
    1.44  =item B<getpolicy> [--dumpxml]
    1.45  
    1.46 @@ -938,50 +933,42 @@ B<CONFIGURING SECURITY>
    1.47  
    1.48  In xen_source_dir/Config.mk set the following parameter:
    1.49  
    1.50 +    XSM_ENABLE ?= y
    1.51      ACM_SECURITY ?= y
    1.52 +
    1.53  Then recompile and install xen and the security tools and then reboot:
    1.54  
    1.55 -    cd xen_source_dir/xen; make clean; make; cp xen.gz /boot;
    1.56 -    cd xen_source_dir/tools/security; make install;
    1.57 +    cd xen_source_dir; make clean; make install
    1.58      reboot into Xen
    1.59  
    1.60  =back
    1.61  
    1.62 +B<RESETTING THE SYSTEM'S SECURITY>
    1.63 +
    1.64 +=over 4
    1.65 +
    1.66 +To set the system's security policy enforcement into its default state,
    1.67 +the follow command can be issued. Make sure that no guests are running
    1.68 +while doing this.
    1.69 +
    1.70 +    xm resetpolicy
    1.71 +
    1.72 +After this command has successfully completed, the system's DEFAULT policy
    1.73 +is enforced.
    1.74 +
    1.75 +=back
    1.76 +
    1.77  B<SETTING A SECURITY POLICY>
    1.78  
    1.79  =over 4
    1.80  
    1.81 -This step makes the policy available to xend and creates the client_v1.map and
    1.82 -client_v1.bin files in /etc/xen/acm-security/policies/example/chwall_ste.
    1.83 +This step sets the system's policy and automatically loads it into Xen
    1.84 +for enforcement.
    1.85  
    1.86      xm setpolicy ACM example.client_v1
    1.87  
    1.88  =back
    1.89  
    1.90 -B<ACTIVATING THE XEND-MANAGED SECURITY POLICY>
    1.91 -
    1.92 -=over 4
    1.93 -
    1.94 -This step activates the xend-manged policy as new security policy in Xen.
    1.95 -You can use the dumppolicy subcommand before and afterwards to see the
    1.96 -change in the Xen policy state.
    1.97 -
    1.98 -    xm activatpolicy --load
    1.99 -
   1.100 -=back
   1.101 -
   1.102 -B<CONFIGURING A BOOT SECURITY POLICY>
   1.103 -
   1.104 -=over 4
   1.105 -
   1.106 -This configures the boot loader to load the current xend-managed policy at
   1.107 -boot time. During system start, the ACM configures Xen with this policy and
   1.108 -Xen enforces this policy from then on.
   1.109 -
   1.110 -    xm activatepolicy --boot
   1.111 -
   1.112 -=back
   1.113 -
   1.114  B<LISTING SECURITY LABELS>
   1.115  
   1.116  =over 4
     2.1 --- a/tools/python/xen/util/acmpolicy.py	Tue Dec 04 22:54:58 2007 +0000
     2.2 +++ b/tools/python/xen/util/acmpolicy.py	Wed Dec 05 09:44:20 2007 +0000
     2.3 @@ -51,6 +51,19 @@ ACM_SCHEMA_FILE = ACM_POLICIES_DIR + "se
     2.4  ACM_LABEL_UNLABELED = "__UNLABELED__"
     2.5  ACM_LABEL_UNLABELED_DISPLAY = "unlabeled"
     2.6  
     2.7 +"""
     2.8 +   Error codes reported in when trying to test for a new policy
     2.9 +   These error codes are reported in an array of tuples where
    2.10 +   each error code is followed by a parameter describing the error
    2.11 +   more closely, such as a domain id.
    2.12 +"""
    2.13 +ACM_EVTCHN_SHARING_VIOLATION = 0x100
    2.14 +ACM_GNTTAB_SHARING_VIOLATION = 0x101
    2.15 +ACM_DOMAIN_LOOKUP            = 0x102
    2.16 +ACM_CHWALL_CONFLICT          = 0x103
    2.17 +ACM_SSIDREF_IN_USE           = 0x104
    2.18 +
    2.19 +
    2.20  class ACMPolicy(XSPolicy):
    2.21      """
    2.22       ACMPolicy class. Implements methods for getting information from
    2.23 @@ -228,7 +241,7 @@ class ACMPolicy(XSPolicy):
    2.24                  return -xsconstants.XSERR_BAD_LABEL, errors
    2.25  
    2.26              #Get binary and map from the new policy
    2.27 -            rc, map, bin_pol = acmpol_new.policy_create_map_and_bin()
    2.28 +            rc, pol_map, bin_pol = acmpol_new.policy_create_map_and_bin()
    2.29              if rc != xsconstants.XSERR_SUCCESS:
    2.30                  log.error("Could not build the map and binary policy.")
    2.31                  return rc, errors
    2.32 @@ -356,7 +369,7 @@ class ACMPolicy(XSPolicy):
    2.33              pass
    2.34          return ssidref
    2.35  
    2.36 -    def set_vm_bootlabel(self, vm_label):
    2.37 +    def set_vm_bootlabel(self, vm_label, remove=False):
    2.38          parms="<>"
    2.39          if vm_label != "":
    2.40              ssidref = self.vmlabel_to_ssidref(vm_label)
    2.41 @@ -367,6 +380,10 @@ class ACMPolicy(XSPolicy):
    2.42                           self.get_name(),vm_label)
    2.43          else:
    2.44              ssidref = 0 #Identifier for removal
    2.45 +
    2.46 +        if remove == True:
    2.47 +            parms = "<>"
    2.48 +
    2.49          try:
    2.50              def_title = bootloader.get_default_title()
    2.51              bootloader.set_kernel_attval(def_title, "ssidref", parms)
    2.52 @@ -387,7 +404,7 @@ class ACMPolicy(XSPolicy):
    2.53          if name:
    2.54              p = name.split(".")
    2.55              path = ""
    2.56 -            if dotted == True:
    2.57 +            if dotted:
    2.58                  sep = "."
    2.59              else:
    2.60                  sep = "/"
    2.61 @@ -513,8 +530,8 @@ class ACMPolicy(XSPolicy):
    2.62          self.set_frompolicy_name(curpol.policy_dom_get_hdr_item("PolicyName"))
    2.63          version = curpol.policy_dom_get_hdr_item("Version")
    2.64          self.set_frompolicy_version(version)
    2.65 -        (maj, min) = self.__convVersionToTuple(version)
    2.66 -        self.set_policy_version("%s.%s" % (maj, min+1))
    2.67 +        (maj, minor) = self.__convVersionToTuple(version)
    2.68 +        self.set_policy_version("%s.%s" % (maj, minor+1))
    2.69  
    2.70      #
    2.71      # Get all types that are part of a node
    2.72 @@ -877,8 +894,7 @@ class ACMPolicy(XSPolicy):
    2.73          """
    2.74              Determine whether this policy is the active one.
    2.75          """
    2.76 -        security.refresh_security_policy()
    2.77 -        if self.get_name() == security.active_policy:
    2.78 +        if self.get_name() == security.get_active_policy_name():
    2.79              return True
    2.80          return False
    2.81  
     3.1 --- a/tools/python/xen/util/xsm/acm/acm.py	Tue Dec 04 22:54:58 2007 +0000
     3.2 +++ b/tools/python/xen/util/xsm/acm/acm.py	Wed Dec 05 09:44:20 2007 +0000
     3.3 @@ -24,6 +24,7 @@ import os, string, re
     3.4  import threading
     3.5  import struct
     3.6  import stat
     3.7 +import base64
     3.8  from xen.lowlevel import acm
     3.9  from xen.xend import sxp
    3.10  from xen.xend import XendConstants
    3.11 @@ -39,7 +40,6 @@ policy_dir_prefix = security_dir_prefix 
    3.12  res_label_filename = policy_dir_prefix + "/resource_labels"
    3.13  boot_filename = "/boot/grub/menu.lst"
    3.14  altboot_filename = "/boot/grub/grub.conf"
    3.15 -xensec_xml2bin = "/usr/sbin/xensec_xml2bin"
    3.16  xensec_tool = "/usr/sbin/xensec_tool"
    3.17  
    3.18  #global patterns for map file
    3.19 @@ -49,7 +49,7 @@ secondary_entry_re = re.compile("\s*SECO
    3.20  label_template_re =  re.compile(".*security_label_template.xml", re.IGNORECASE)
    3.21  mapping_filename_re = re.compile(".*\.map", re.IGNORECASE)
    3.22  policy_reference_entry_re = re.compile("\s*POLICYREFERENCENAME\s+.*", re.IGNORECASE)
    3.23 -vm_label_re = re.compile("\s*LABEL->SSID\s+VM\s+.*", re.IGNORECASE)
    3.24 +vm_label_re = re.compile("\s*LABEL->SSID\s.+[VM|ANY]\s+.*", re.IGNORECASE)
    3.25  res_label_re = re.compile("\s*LABEL->SSID\s+RES\s+.*", re.IGNORECASE)
    3.26  all_label_re = re.compile("\s*LABEL->SSID\s+.*", re.IGNORECASE)
    3.27  access_control_re = re.compile("\s*access_control\s*=", re.IGNORECASE)
    3.28 @@ -77,9 +77,25 @@ NULL_SSIDREF = 0
    3.29  
    3.30  log = logging.getLogger("xend.util.security")
    3.31  
    3.32 +
    3.33 +#Functions exported through XML-RPC
    3.34 +xmlrpc_exports = [
    3.35 +  'set_resource_label',
    3.36 +  'get_resource_label',
    3.37 +  'list_labels',
    3.38 +  'get_labeled_resources',
    3.39 +  'set_policy',
    3.40 +  'get_policy',
    3.41 +  'activate_policy',
    3.42 +  'rm_bootpolicy',
    3.43 +  'get_xstype',
    3.44 +  'get_domain_label',
    3.45 +  'set_domain_label'
    3.46 +]
    3.47 +
    3.48  # Our own exception definition. It is masked (pass) if raised and
    3.49  # whoever raises this exception must provide error information.
    3.50 -class ACMError(Exception):
    3.51 +class XSMError(Exception):
    3.52      def __init__(self,value):
    3.53          self.value = value
    3.54      def __str__(self):
    3.55 @@ -90,7 +106,7 @@ class ACMError(Exception):
    3.56  def err(msg):
    3.57      """Raise ACM exception.
    3.58      """
    3.59 -    raise ACMError(msg)
    3.60 +    raise XSMError(msg)
    3.61  
    3.62  
    3.63  
    3.64 @@ -118,12 +134,17 @@ def refresh_security_policy():
    3.65      global active_policy
    3.66  
    3.67      active_policy = 'INACCESSIBLE'
    3.68 +
    3.69      if os.access("/proc/xen/privcmd", os.R_OK|os.W_OK):
    3.70          try:
    3.71              active_policy = acm.policy()
    3.72          except:
    3.73              active_policy = "INACTIVE"
    3.74  
    3.75 +def get_active_policy_name():
    3.76 +    refresh_security_policy()
    3.77 +    return active_policy
    3.78 +
    3.79  # now set active_policy
    3.80  refresh_security_policy()
    3.81  
    3.82 @@ -132,8 +153,7 @@ def on():
    3.83      returns none if security policy is off (not compiled),
    3.84      any string otherwise, use it: if not security.on() ...
    3.85      """
    3.86 -    refresh_security_policy()
    3.87 -    return (active_policy not in ['INACTIVE', 'NULL'])
    3.88 +    return (get_active_policy_name() not in ['INACTIVE', 'NULL'])
    3.89  
    3.90  
    3.91  def calc_dom_ssidref_from_info(info):
    3.92 @@ -158,11 +178,10 @@ def calc_dom_ssidref_from_info(info):
    3.93              typ, policyname, vmlabel = seclab.split(":")
    3.94              if typ != xsconstants.ACM_POLICY_ID:
    3.95                  raise VmError("Policy type '%s' must be changed." % typ)
    3.96 -            refresh_security_policy()
    3.97 -            if active_policy != policyname:
    3.98 +            if get_active_policy_name() != policyname:
    3.99                  raise VmError("Active policy '%s' different than "
   3.100                                "what in VM's label ('%s')." %
   3.101 -                              (active_policy, policyname))
   3.102 +                              (get_active_policy_name(), policyname))
   3.103              ssidref = label2ssidref(vmlabel, policyname, "dom")
   3.104              return ssidref
   3.105          else:
   3.106 @@ -180,7 +199,7 @@ def getmapfile(policyname):
   3.107      4. True if policy file is available, False otherwise
   3.108      """
   3.109      if not policyname:
   3.110 -        policyname = active_policy
   3.111 +        policyname = get_active_policy_name()
   3.112      map_file_ok = False
   3.113      primary = None
   3.114      secondary = None
   3.115 @@ -199,8 +218,7 @@ def getmapfile(policyname):
   3.116          if not os.path.isfile(policy_filename):
   3.117              err("Policy file \'" + policy_filename + "\' not found.")
   3.118          else:
   3.119 -            err("Mapping file \'" + map_filename + "\' not found." +
   3.120 -                " Use xm makepolicy to create it.")
   3.121 +            err("Mapping file \'" + map_filename + "\' not found.")
   3.122  
   3.123      f = open(map_filename)
   3.124      for line in f:
   3.125 @@ -221,7 +239,7 @@ def getmapfile(policyname):
   3.126      if map_file_ok and primary and secondary:
   3.127          return (primary, secondary, f, True)
   3.128      else:
   3.129 -        err("Mapping file inconsistencies found. Try makepolicy to create a new one.")
   3.130 +        err("Mapping file inconsistencies found.")
   3.131  
   3.132  
   3.133  
   3.134 @@ -253,10 +271,10 @@ def ssidref2label(ssidref_var):
   3.135          (primary, secondary, f, pol_exists) = getmapfile(None)
   3.136          if not f:
   3.137              if (pol_exists):
   3.138 -                err("Mapping file for policy not found.\n" +
   3.139 -                    "Please use makepolicy command to create mapping file!")
   3.140 +                err("Mapping file for policy not found.")
   3.141              else:
   3.142 -                err("Policy file for \'" + active_policy + "\' not found.")
   3.143 +                err("Policy file for \'" + get_active_policy_name() +
   3.144 +                    "\' not found.")
   3.145  
   3.146          #2. get labelnames for both ssidref parts
   3.147          pri_ssid = ssidref & 0xffff
   3.148 @@ -534,37 +552,99 @@ def hv_get_policy():
   3.149      return rc, bin_pol
   3.150  
   3.151  
   3.152 -def make_policy(policy_name):
   3.153 -    policy_file = string.join(string.split(policy_name, "."), "/")
   3.154 -    if not os.path.isfile(policy_dir_prefix + "/" + policy_file + "-security_policy.xml"):
   3.155 -        err("Unknown policy \'" + policy_name + "\'")
   3.156 -
   3.157 -    (ret, output) = commands.getstatusoutput(xensec_xml2bin + " -d " + policy_dir_prefix + " " + policy_file)
   3.158 -    if ret:
   3.159 -        err("Creating policy failed:\n" + output)
   3.160 +def set_policy(xs_type, xml, flags, overwrite):
   3.161 +    """
   3.162 +        Xend exports this function via XML-RPC
   3.163 +    """
   3.164 +    from xen.xend import XendXSPolicyAdmin
   3.165 +    xspoladmin = XendXSPolicyAdmin.XSPolicyAdminInstance()
   3.166 +    try:
   3.167 +        acmpol, rc, errors = \
   3.168 +             xspoladmin.add_acmpolicy_to_system(xml,
   3.169 +                                                int(flags),
   3.170 +                                                True)
   3.171 +        return rc, base64.b64encode(errors)
   3.172 +    except Exception, e:
   3.173 +        err(str(e))
   3.174  
   3.175 -def load_policy(policy_name):
   3.176 -    global active_policy
   3.177 -    policy_file = policy_dir_prefix + "/" + string.join(string.split(policy_name, "."), "/")
   3.178 -    if not os.path.isfile(policy_file + ".bin"):
   3.179 -        if os.path.isfile(policy_file + "-security_policy.xml"):
   3.180 -            err("Binary file does not exist." +
   3.181 -                "Please use makepolicy to build the policy binary.")
   3.182 -        else:
   3.183 -            err("Unknown Policy " + policy_name)
   3.184  
   3.185 -    #require this policy to be the first or the same as installed
   3.186 -    if active_policy not in ['DEFAULT', policy_name]:
   3.187 -        err("Active policy \'" + active_policy +
   3.188 -            "\' incompatible with new policy \'" + policy_name + "\'")
   3.189 -    (ret, output) = commands.getstatusoutput(xensec_tool + " loadpolicy " + policy_file + ".bin")
   3.190 -    if ret:
   3.191 -        err("Loading policy failed:\n" + output)
   3.192 +def get_policy():
   3.193 +    """
   3.194 +        Xend exports this function via XML-RPC
   3.195 +    """
   3.196 +    from xen.xend import XendXSPolicyAdmin
   3.197 +    poladmin = XendXSPolicyAdmin.XSPolicyAdminInstance()
   3.198 +    try:
   3.199 +        policy = poladmin.get_loaded_policy()
   3.200 +        if policy != None:
   3.201 +            return policy.toxml(), poladmin.get_policy_flags(policy)
   3.202 +    except Exception, e:
   3.203 +        err(str(e))
   3.204 +    return "", 0
   3.205 +
   3.206 +def activate_policy(flags):
   3.207 +    """
   3.208 +        Xend exports this function via XML-RPC
   3.209 +    """
   3.210 +    from xen.xend import XendXSPolicyAdmin
   3.211 +    poladmin = XendXSPolicyAdmin.XSPolicyAdminInstance()
   3.212 +    try:
   3.213 +        policies = poladmin.get_policies()
   3.214 +        if len(policies) > 0:
   3.215 +           flags = int(flags)
   3.216 +           irc = poladmin.activate_xspolicy(policies[0], flags)
   3.217 +           return irc
   3.218 +    except Exception, e:
   3.219 +        err("Error while activating the policy: " % str(e))
   3.220 +    return 0
   3.221 +
   3.222 +
   3.223 +def rm_bootpolicy():
   3.224 +    """
   3.225 +        Xend exports this function via XML-RPC
   3.226 +    """
   3.227 +    from xen.xend import XendXSPolicyAdmin
   3.228 +    rc = XendXSPolicyAdmin.XSPolicyAdminInstance().rm_bootpolicy()
   3.229 +    if rc != xsconstants.XSERR_SUCCESS:
   3.230 +        err("Error while removing boot policy: %s" % \
   3.231 +            str(xsconstants.xserr2string(-rc)))
   3.232 +    return rc
   3.233 +
   3.234 +
   3.235 +def get_xstype():
   3.236 +    """
   3.237 +        Xend exports this function via XML-RPC
   3.238 +    """
   3.239 +    from xen.xend import XendXSPolicyAdmin
   3.240 +    return XendXSPolicyAdmin.XSPolicyAdminInstance().isXSEnabled()
   3.241 +
   3.242 +
   3.243 +def get_domain_label(domain):
   3.244 +    """
   3.245 +        Xend exports this function via XML-RPC
   3.246 +    """
   3.247 +    from xen.xend import XendDomain
   3.248 +    dom = XendDomain.instance().domain_lookup_nr(domain)
   3.249 +    if dom:
   3.250 +        seclab = dom.get_security_label()
   3.251 +        return seclab
   3.252      else:
   3.253 -        # refresh active policy
   3.254 -        refresh_security_policy()
   3.255 +        err("Domain not found.")
   3.256  
   3.257  
   3.258 +def set_domain_label(domain, seclab, old_seclab):
   3.259 +    """
   3.260 +        Xend exports this function via XML-RPC
   3.261 +    """
   3.262 +    from xen.xend import XendDomain
   3.263 +    dom = XendDomain.instance().domain_lookup_nr(domain)
   3.264 +    if dom:
   3.265 +        results = dom.set_security_label(seclab, old_seclab)
   3.266 +        rc, errors, old_label, new_ssidref = results
   3.267 +        return rc, new_ssidref
   3.268 +    else:
   3.269 +        err("Domain not found.")
   3.270 +
   3.271  
   3.272  def dump_policy():
   3.273      if active_policy in ['NULL', 'INACTIVE', 'INACCESSIBLE' ]:
   3.274 @@ -589,16 +669,32 @@ def dump_policy_file(filename, ssidref=N
   3.275      print output
   3.276  
   3.277  
   3.278 -def list_labels(policy_name, condition):
   3.279 -    if (not policy_name) and active_policy in \
   3.280 -              [ 'NULL', 'INACTIVE', 'DEFAULT', 'INACCESSIBLE' ]:
   3.281 -        err("Current policy \'" + active_policy + "\' has no labels defined.\n")
   3.282 +def list_labels(policy_name, ltype):
   3.283 +    """
   3.284 +        Xend exports this function via XML-RPC
   3.285 +
   3.286 +        List the VM,resource or any kind of labels contained in the
   3.287 +        given policy. If no policy name is given, the currently
   3.288 +        active policy's label will be returned if they exist.
   3.289 +    """
   3.290 +    if not policy_name:
   3.291 +        if active_policy in [ 'NULL', 'INACTIVE', "" ]:
   3.292 +            err("Current policy \'" + active_policy + "\' "
   3.293 +                "has no labels defined.\n")
   3.294 +
   3.295 +    if not ltype or ltype == 'dom':
   3.296 +        condition = vm_label_re
   3.297 +    elif ltype == 'res':
   3.298 +        condition = res_label_re
   3.299 +    elif ltype == 'any':
   3.300 +        condition = all_label_re
   3.301 +    else:
   3.302 +        err("Unknown label type \'" + ltype + "\'")
   3.303  
   3.304      (primary, secondary, f, pol_exists) = getmapfile(policy_name)
   3.305      if not f:
   3.306          if pol_exists:
   3.307 -            err("Cannot find mapfile for policy \'" + policy_name +
   3.308 -                "\'.\nPlease use makepolicy to create mapping file.")
   3.309 +            err("Cannot find mapfile for policy \'" + policy_name + "\'.\n")
   3.310          else:
   3.311              err("Unknown policy \'" + policy_name + "\'")
   3.312  
   3.313 @@ -608,6 +704,10 @@ def list_labels(policy_name, condition):
   3.314              label = line.split()[3]
   3.315              if label not in labels:
   3.316                  labels.append(label)
   3.317 +
   3.318 +    if '__NULL_LABEL__' in labels:
   3.319 +        labels.remove('__NULL_LABEL__')
   3.320 +
   3.321      return labels
   3.322  
   3.323  
   3.324 @@ -763,10 +863,10 @@ def res_security_check(resource, domain_
   3.325          # provide descriptive error messages
   3.326          if decision == 'DENIED':
   3.327              if label == ssidref2label(NULL_SSIDREF):
   3.328 -                raise ACMError("Resource '"+resource+"' is not labeled")
   3.329 +                raise XSMError("Resource '"+resource+"' is not labeled")
   3.330                  rtnval = 0
   3.331              else:
   3.332 -                raise ACMError("Permission denied for resource '"+resource+"' because label '"+label+"' is not allowed")
   3.333 +                raise XSMError("Permission denied for resource '"+resource+"' because label '"+label+"' is not allowed")
   3.334                  rtnval = 0
   3.335  
   3.336      # security is off, make sure resource isn't labeled
   3.337 @@ -775,7 +875,7 @@ def res_security_check(resource, domain_
   3.338          # xm without ACM are free to use relative paths.
   3.339          (policytype, label, policy) = get_res_label(resource)
   3.340          if policy != 'NULL':
   3.341 -            raise ACMError("Security is off, but '"+resource+"' is labeled")
   3.342 +            raise XSMError("Security is off, but '"+resource+"' is labeled")
   3.343              rtnval = 0
   3.344  
   3.345      return rtnval
   3.346 @@ -803,10 +903,10 @@ def res_security_check_xapi(rlabel, rssi
   3.347          # provide descriptive error messages
   3.348          if decision == 'DENIED':
   3.349              if rlabel == ssidref2label(NULL_SSIDREF):
   3.350 -                #raise ACMError("Resource is not labeled")
   3.351 +                #raise XSMError("Resource is not labeled")
   3.352                  rtnval = 0
   3.353              else:
   3.354 -                #raise ACMError("Permission denied for resource because label '"+rlabel+"' is not allowed")
   3.355 +                #raise XSMError("Permission denied for resource because label '"+rlabel+"' is not allowed")
   3.356                  rtnval = 0
   3.357  
   3.358      # security is off, make sure resource isn't labeled
   3.359 @@ -814,17 +914,35 @@ def res_security_check_xapi(rlabel, rssi
   3.360          # Note, we can't canonicalise the resource here, because people using
   3.361          # xm without ACM are free to use relative paths.
   3.362          if rpolicy != 'NULL':
   3.363 -            #raise ACMError("Security is off, but resource is labeled")
   3.364 +            #raise XSMError("Security is off, but resource is labeled")
   3.365              rtnval = 0
   3.366  
   3.367      return rtnval
   3.368  
   3.369  
   3.370 -def validate_label(label, policyref):
   3.371 +def validate_label_xapi(xapi_label, dom_or_res):
   3.372 +    """
   3.373 +       Make sure that this label is part of the currently enforced policy
   3.374 +       and that it references the current policy.
   3.375 +       dom_or_res defines whether this is a VM ('res') or resource label
   3.376 +       ('res')
   3.377 +    """
   3.378 +    tmp = xapi_label.split(":")
   3.379 +    if len(tmp) != 3:
   3.380 +        return -xsconstants.XSERR_BAD_LABEL_FORMAT
   3.381 +    policytyp, policyref, label = tmp
   3.382 +    return validate_label(policytyp, policyref, label, dom_or_res)
   3.383 +
   3.384 +
   3.385 +def validate_label(policytype, policyref, label, dom_or_res):
   3.386      """
   3.387         Make sure that this label is part of the currently enforced policy
   3.388         and that it reference the current policy.
   3.389      """
   3.390 +    if policytype != xsconstants.ACM_POLICY_ID:
   3.391 +        return -xsconstants.XSERR_WRONG_POLICY_TYPE
   3.392 +    if not policytype or not label:
   3.393 +        return -xsconstants.XSERR_BAD_LABEL_FORMAT
   3.394      rc = xsconstants.XSERR_SUCCESS
   3.395      from xen.xend.XendXSPolicyAdmin import XSPolicyAdminInstance
   3.396      curpol = XSPolicyAdminInstance().get_loaded_policy()
   3.397 @@ -832,7 +950,7 @@ def validate_label(label, policyref):
   3.398          rc = -xsconstants.XSERR_BAD_LABEL
   3.399      else:
   3.400          try:
   3.401 -            label2ssidref(label, curpol.get_name() , 'res')
   3.402 +            label2ssidref(label, curpol.get_name() , dom_or_res)
   3.403          except:
   3.404              rc = -xsconstants.XSERR_BAD_LABEL
   3.405      return rc
   3.406 @@ -851,11 +969,11 @@ def set_resource_label_xapi(resource, re
   3.407      olabel = ""
   3.408      if reslabel_xapi == "":
   3.409          return rm_resource_label(resource, oldlabel_xapi)
   3.410 -    typ, policyref, label = reslabel_xapi.split(":")
   3.411 -    if typ != xsconstants.ACM_POLICY_ID:
   3.412 -        return -xsconstants.XSERR_WRONG_POLICY_TYPE
   3.413 -    if not policyref or not label:
   3.414 -        return -xsconstants.XSERR_BAD_LABEL_FORMAT
   3.415 +
   3.416 +    rc = validate_label_xapi(reslabel_xapi, 'res')
   3.417 +    if rc != xsconstants.XSERR_SUCCESS:
   3.418 +        return rc
   3.419 +
   3.420      if oldlabel_xapi not in [ "" ]:
   3.421          tmp = oldlabel_xapi.split(":")
   3.422          if len(tmp) != 3:
   3.423 @@ -866,9 +984,7 @@ def set_resource_label_xapi(resource, re
   3.424             otyp != xsconstants.INVALID_POLICY_PREFIX + \
   3.425                     xsconstants.ACM_POLICY_ID:
   3.426              return -xsconstants.XSERR_WRONG_POLICY_TYPE
   3.427 -    rc = validate_label(label, policyref)
   3.428 -    if rc != xsconstants.XSERR_SUCCESS:
   3.429 -        return rc
   3.430 +    typ, policyref, label = reslabel_xapi.split(":")
   3.431      return set_resource_label(resource, typ, policyref, label, olabel)
   3.432  
   3.433  
   3.434 @@ -1033,7 +1149,10 @@ def __resources_compatible_with_vmlabel(
   3.435  
   3.436  def set_resource_label(resource, policytype, policyref, reslabel, \
   3.437                         oreslabel = None):
   3.438 -    """Assign a label to a resource
   3.439 +    """
   3.440 +       Xend exports this function via XML-RPC.
   3.441 +
   3.442 +       Assign a label to a resource
   3.443         If the old label (oreslabel) is given, then the resource must have
   3.444         that old label.
   3.445         A resource label may be changed if
   3.446 @@ -1046,6 +1165,10 @@ def set_resource_label(resource, policyt
   3.447      @rtype: int
   3.448      @return Success (0) or failure value (< 0)
   3.449      """
   3.450 +
   3.451 +    if reslabel != "":
   3.452 +        ssidref = label2ssidref(reslabel, policyref, 'res')
   3.453 +
   3.454      try:
   3.455          resource = unify_resname(resource, mustexist=False)
   3.456      except Exception:
   3.457 @@ -1123,7 +1246,10 @@ def format_resource_label(res):
   3.458      return ""
   3.459  
   3.460  def get_resource_label(resource):
   3.461 -    """Get the assigned resource label of a given resource
   3.462 +    """
   3.463 +       Xend exports this function via XML-RPC.
   3.464 +
   3.465 +       Get the assigned resource label of a given resource
   3.466      @param resource: The name of a resource, i.e., "phy:/dev/hda"
   3.467  
   3.468      @rtype: list
   3.469 @@ -1161,7 +1287,10 @@ def get_labeled_resources_xapi():
   3.470  
   3.471  
   3.472  def get_labeled_resources():
   3.473 -    """Get a map of all labeled resources
   3.474 +    """
   3.475 +        Xend exports this function via XML-RPC
   3.476 +
   3.477 +        Get a map of all labeled resources.
   3.478      @rtype: list
   3.479      @return list of labeled resources
   3.480      """
   3.481 @@ -1225,6 +1354,7 @@ def change_acm_policy(bin_pol, del_array
   3.482         This function should be called with the lock to the domains
   3.483         held (XendDomain.instance().domains_lock)
   3.484      """
   3.485 +    from xen.util.acmpolicy import ACM_LABEL_UNLABELED
   3.486      rc = xsconstants.XSERR_SUCCESS
   3.487  
   3.488      domain_label_map = {}
   3.489 @@ -1266,14 +1396,25 @@ def change_acm_policy(bin_pol, del_array
   3.490                  continue
   3.491  
   3.492              # label been renamed or deleted?
   3.493 -            if reslabel_map.has_key(label) and cur_policyname == policy:
   3.494 +            if policytype != xsconstants.ACM_POLICY_ID:
   3.495 +                continue
   3.496 +            elif reslabel_map.has_key(label) and cur_policyname == policy:
   3.497 +                # renaming of an active label; policy may have been renamed
   3.498                  label = reslabel_map[label]
   3.499 +                polname = new_policyname
   3.500              elif label not in polnew_reslabels:
   3.501 +                # label been removed
   3.502                  policytype = xsconstants.INVALID_POLICY_PREFIX + policytype
   3.503                  run_resource_label_change_script(key, "", "remove")
   3.504 +                polname = policy
   3.505 +            else:
   3.506 +                # no change to label
   3.507 +                policytype = xsconstants.ACM_POLICY_ID
   3.508 +                polname = new_policyname
   3.509 +
   3.510              # Update entry
   3.511              access_control[key] = \
   3.512 -                   tuple([ policytype, new_policyname, label ])
   3.513 +                   tuple([ policytype, polname, label ])
   3.514  
   3.515          # All resources have new labels in the access_control map
   3.516          # There may still be labels in there that are invalid now.
   3.517 @@ -1297,11 +1438,19 @@ def change_acm_policy(bin_pol, del_array
   3.518  
   3.519              new_vmlabel = vmlabel
   3.520              if vmlabel_map.has_key(vmlabel):
   3.521 +                # renaming of the label
   3.522                  new_vmlabel = vmlabel_map[vmlabel]
   3.523 -            if new_vmlabel not in polnew_vmlabels:
   3.524 +                polname = new_policyname
   3.525 +            elif new_vmlabel not in polnew_vmlabels and \
   3.526 +               vmlabel != ACM_LABEL_UNLABELED:
   3.527 +                # removal of VM label and not the 'unlabeled' label
   3.528                  policytype = xsconstants.INVALID_POLICY_PREFIX + policytype
   3.529 +                polname = policy
   3.530 +            else:
   3.531 +                polname = new_policyname
   3.532 +
   3.533              new_seclab = "%s:%s:%s" % \
   3.534 -                    (policytype, new_policyname, new_vmlabel)
   3.535 +                    (policytype, polname, new_vmlabel)
   3.536  
   3.537              domain_label_map[dominfo] = [ sec_lab, new_seclab ]
   3.538  
   3.539 @@ -1383,16 +1532,20 @@ def get_security_label(self, xspol=None)
   3.540      return label
   3.541  
   3.542  def run_resource_label_change_script(resource, label, command):
   3.543 -    script = XendOptions.instance().get_resource_label_change_script()
   3.544 -    if script:
   3.545 -        parms = {
   3.546 -            'resource' : resource,
   3.547 -            'label'    : label,
   3.548 -            'command'  : command,
   3.549 -        }
   3.550 -        log.info("Running resource label change script %s: %s" %
   3.551 -                 (script, parms))
   3.552 -        parms.update(os.environ)
   3.553 -        os.spawnve(os.P_NOWAIT, script[0], script, parms)
   3.554 -    else:
   3.555 -        log.info("No script given for relabeling of resources.")
   3.556 +    def __run_resource_label_change_script(label, command):
   3.557 +        script = XendOptions.instance().get_resource_label_change_script()
   3.558 +        if script:
   3.559 +            parms = {
   3.560 +                'resource' : resource,
   3.561 +                'label'    : label,
   3.562 +                'command'  : command,
   3.563 +            }
   3.564 +            log.info("Running resource label change script %s: %s" %
   3.565 +                     (script, parms))
   3.566 +            parms.update(os.environ)
   3.567 +            os.spawnve(os.P_WAIT, script[0], script, parms)
   3.568 +        else:
   3.569 +            log.info("No script given for relabeling of resources.")
   3.570 +    thread = threading.Thread(target=__run_resource_label_change_script,
   3.571 +                              args=(label,command))
   3.572 +    thread.start()
     4.1 --- a/tools/python/xen/util/xsm/dummy/dummy.py	Tue Dec 04 22:54:58 2007 +0000
     4.2 +++ b/tools/python/xen/util/xsm/dummy/dummy.py	Wed Dec 05 09:44:20 2007 +0000
     4.3 @@ -1,4 +1,6 @@
     4.4  import sys
     4.5 +from xen.util import xsconstants
     4.6 +from xen.xend.XendLogging import log
     4.7  
     4.8  class XSMError(Exception):
     4.9      def __init__(self,value):
    4.10 @@ -6,11 +8,27 @@ class XSMError(Exception):
    4.11      def __str__(self):
    4.12          return repr(self.value)
    4.13  
    4.14 +
    4.15  security_dir_prefix = "";
    4.16  policy_dir_prefix = "";
    4.17  active_policy = "";
    4.18  NULL_SSIDREF = 0;
    4.19  
    4.20 +#Functions exported through XML-RPC
    4.21 +xmlrpc_exports = [
    4.22 +  'set_resource_label',
    4.23 +  'get_resource_label',
    4.24 +  'list_labels',
    4.25 +  'get_labeled_resources',
    4.26 +  'set_policy',
    4.27 +  'get_policy',
    4.28 +  'activate_policy',
    4.29 +  'rm_bootpolicy',
    4.30 +  'get_xstype',
    4.31 +  'get_domain_label',
    4.32 +  'set_domain_label'
    4.33 +]
    4.34 +
    4.35  def err(msg):
    4.36      """Raise XSM-dummy exception.
    4.37      """
    4.38 @@ -45,7 +63,7 @@ def calc_dom_ssidref_from_info(info):
    4.39      return ""
    4.40  
    4.41  def set_security_label(policy, label):
    4.42 -     return ""
    4.43 +    return ""
    4.44  
    4.45  def ssidref2security_label(ssidref):
    4.46      return ""
    4.47 @@ -55,3 +73,49 @@ def has_authorization(ssidref):
    4.48  
    4.49  def get_security_label(self, xspol=None):
    4.50      return ""
    4.51 +
    4.52 +def get_resource_label_xapi(resource):
    4.53 +    return ""
    4.54 +
    4.55 +def get_labeled_resources_xapi():
    4.56 +    return {}
    4.57 +
    4.58 +def set_resource_label_xapi(resource, reslabel_xapi, oldlabel_xapi):
    4.59 +    err("Command not supported under XSM 'dummy' module.")
    4.60 +
    4.61 +def format_resource_label(res):
    4.62 +    return ""
    4.63 +
    4.64 +def set_resource_label(resource, policytype, policyref, reslabel,
    4.65 +                       oreslabel = None):
    4.66 +    err("Command not supported under XSM 'dummy' module.")
    4.67 +
    4.68 +def get_resource_label(resource):
    4.69 +    return ""
    4.70 +
    4.71 +def list_labels(policy_name, ltype):
    4.72 +    return []
    4.73 +
    4.74 +def get_labeled_resources():
    4.75 +    return {}
    4.76 +
    4.77 +def set_policy(xs_type, xml, flags, overwrite):
    4.78 +    err("Command not supported under xsm 'dummy' module.")
    4.79 +
    4.80 +def get_policy():
    4.81 +    return "", 0
    4.82 +
    4.83 +def activate_policy():
    4.84 +    err("Command not supported under xsm 'dummy' module.")
    4.85 +
    4.86 +def rm_bootpolicy():
    4.87 +    err("Command not supported under xsm 'dummy' module.")
    4.88 +
    4.89 +def get_xstype():
    4.90 +    return 0
    4.91 +
    4.92 +def get_domain_label(domain):
    4.93 +    return ""
    4.94 +
    4.95 +def set_domain_label():
    4.96 +    err("Command not supported under xsm 'dummy' module.")
     5.1 --- a/tools/python/xen/util/xsm/flask/flask.py	Tue Dec 04 22:54:58 2007 +0000
     5.2 +++ b/tools/python/xen/util/xsm/flask/flask.py	Wed Dec 05 09:44:20 2007 +0000
     5.3 @@ -2,6 +2,9 @@ import sys
     5.4  from xen.lowlevel import flask
     5.5  from xen.xend import sxp
     5.6  
     5.7 +#Functions exported through XML-RPC
     5.8 +xmlrpc_exports = [ ]
     5.9 +
    5.10  def err(msg):
    5.11      """Raise XSM-Flask exception.
    5.12      """
     6.1 --- a/tools/python/xen/xend/XendConfig.py	Tue Dec 04 22:54:58 2007 +0000
     6.2 +++ b/tools/python/xen/xend/XendConfig.py	Wed Dec 05 09:44:20 2007 +0000
     6.3 @@ -647,11 +647,18 @@ class XendConfig(dict):
     6.4                  except ValueError, e:
     6.5                      raise XendConfigError('cpus = %s: %s' % (cfg['cpus'], e))
     6.6  
     6.7 -        if not 'security' in cfg and sxp.child_value(sxp_cfg, 'security'):
     6.8 -            cfg['security'] = sxp.child_value(sxp_cfg, 'security')
     6.9 -        if 'security' in cfg and not cfg.get('security_label'):
    6.10 -            secinfo = cfg['security']
    6.11 -            if isinstance(secinfo, list):
    6.12 +        import xen.util.xsm.xsm as security
    6.13 +        if security.on():
    6.14 +            from xen.util.acmpolicy import ACM_LABEL_UNLABELED
    6.15 +            if not 'security' in cfg and sxp.child_value(sxp_cfg, 'security'):
    6.16 +                cfg['security'] = sxp.child_value(sxp_cfg, 'security')
    6.17 +            elif not cfg.get('security_label'):
    6.18 +                cfg['security'] = [['access_control',
    6.19 +                                     ['policy', security.get_active_policy_name() ],
    6.20 +                                     ['label', ACM_LABEL_UNLABELED ]]]
    6.21 +
    6.22 +            if 'security' in cfg and not cfg.get('security_label'):
    6.23 +                secinfo = cfg['security']
    6.24                  # The xm command sends a list formatted like this:
    6.25                  # [['access_control', ['policy', 'xm-test'],['label', 'red']],
    6.26                  #                     ['ssidref', 196611]]
    6.27 @@ -664,12 +671,16 @@ class XendConfig(dict):
    6.28                                  policy = secinfo[idx][aidx][1]
    6.29                              if secinfo[idx][aidx][0] == "label":
    6.30                                  label  = secinfo[idx][aidx][1]
    6.31 -                import xen.util.xsm.xsm as security
    6.32                  cfg['security_label'] = \
    6.33                      security.set_security_label(policy, label)
    6.34                  if not sxp.child_value(sxp_cfg, 'security_label'):
    6.35                      del cfg['security']
    6.36  
    6.37 +            sec_lab = cfg['security_label'].split(":")
    6.38 +            if len(sec_lab) != 3:
    6.39 +                raise XendConfigError("Badly formatted security label: %s"
    6.40 +                                      % cfg['security_label'])
    6.41 +
    6.42          old_state = sxp.child_value(sxp_cfg, 'state')
    6.43          if old_state:
    6.44              for i in range(len(CONFIG_OLD_DOM_STATES)):
     7.1 --- a/tools/python/xen/xend/XendDomainInfo.py	Tue Dec 04 22:54:58 2007 +0000
     7.2 +++ b/tools/python/xen/xend/XendDomainInfo.py	Wed Dec 05 09:44:20 2007 +0000
     7.3 @@ -2460,12 +2460,14 @@ class XendDomainInfo:
     7.4                            self, label):
     7.5                      return (-xsconstants.XSERR_BAD_LABEL, "", "", 0)
     7.6  
     7.7 -                #Check label against expected one.
     7.8 -                old_label = self.get_security_label(xspol_old)
     7.9 -                if old_label != old_seclab:
    7.10 -                    log.info("old_label != old_seclab: %s != %s" %
    7.11 -                             (old_label, old_seclab))
    7.12 -                    return (-xsconstants.XSERR_BAD_LABEL, "", "", 0)
    7.13 +                #Check label against expected one. Can only do this
    7.14 +                # if the policy hasn't changed underneath in the meantime
    7.15 +                if xspol_old == None:
    7.16 +                    old_label = self.get_security_label()
    7.17 +                    if old_label != old_seclab:
    7.18 +                        log.info("old_label != old_seclab: %s != %s" %
    7.19 +                                 (old_label, old_seclab))
    7.20 +                        return (-xsconstants.XSERR_BAD_LABEL, "", "", 0)
    7.21  
    7.22                  # relabel domain in the hypervisor
    7.23                  rc, errors = security.relabel_domains([[domid, new_ssidref]])
    7.24 @@ -2477,6 +2479,7 @@ class XendDomainInfo:
    7.25              # HALTED, RUNNING or PAUSED
    7.26              if domid == 0:
    7.27                  if xspol:
    7.28 +                    self.info['security_label'] = seclab
    7.29                      ssidref = poladmin.set_domain0_bootlabel(xspol, label)
    7.30                  else:
    7.31                      return (-xsconstants.XSERR_POLICY_NOT_LOADED, "", "", 0)
    7.32 @@ -2488,6 +2491,7 @@ class XendDomainInfo:
    7.33                          return (-xsconstants.XSERR_BAD_LABEL, "", "", 0)
    7.34  
    7.35                  self.info['security_label'] = seclab
    7.36 +
    7.37                  try:
    7.38                      xen.xend.XendDomain.instance().managed_config_save(self)
    7.39                  except:
     8.1 --- a/tools/python/xen/xend/XendXSPolicyAdmin.py	Tue Dec 04 22:54:58 2007 +0000
     8.2 +++ b/tools/python/xen/xend/XendXSPolicyAdmin.py	Wed Dec 05 09:44:20 2007 +0000
     8.3 @@ -99,9 +99,10 @@ class XSPolicyAdmin:
     8.4              # This is meant as an update to a currently loaded policy
     8.5              if flags & xsconstants.XS_INST_LOAD == 0:
     8.6                  raise SecurityError(-xsconstants.XSERR_POLICY_LOADED)
     8.7 +            if flags & xsconstants.XS_INST_BOOT == 0:
     8.8 +                self.rm_bootpolicy()
     8.9              rc, errors = loadedpol.update(xmltext)
    8.10              if rc == 0:
    8.11 -                self.rm_bootpolicy()
    8.12                  irc = self.activate_xspolicy(loadedpol, flags)
    8.13                  # policy is loaded; if setting the boot flag fails it's ok.
    8.14              return (loadedpol, rc, errors)
    8.15 @@ -279,8 +280,7 @@ class XSPolicyAdmin:
    8.16          return None
    8.17  
    8.18      def get_hv_loaded_policy_name(self):
    8.19 -        security.refresh_security_policy()
    8.20 -        return security.active_policy
    8.21 +        return security.get_active_policy_name()
    8.22  
    8.23      def get_policy_by_name(self, name):
    8.24          for pol in self.xsobjs.values():
    8.25 @@ -300,8 +300,10 @@ class XSPolicyAdmin:
    8.26          return title
    8.27  
    8.28      def set_domain0_bootlabel(self, xspol, label):
    8.29 -        """ Set the domain-0 bootlabel under the given policy """
    8.30 -        return xspol.set_vm_bootlabel(label)
    8.31 +        """ Set the domain-0 bootlabel under the given policy. If the
    8.32 +            current policy is the default policy, it will remove it. """
    8.33 +        rm_entry = (xspol.get_name() == "DEFAULT")
    8.34 +        return xspol.set_vm_bootlabel(label, rm_entry)
    8.35  
    8.36      def rm_domain0_bootlabel(self):
    8.37          """ Remove the domain-0 bootlabel from the default boot title """
     9.1 --- a/tools/python/xen/xend/server/XMLRPCServer.py	Tue Dec 04 22:54:58 2007 +0000
     9.2 +++ b/tools/python/xen/xend/server/XMLRPCServer.py	Wed Dec 05 09:44:20 2007 +0000
     9.3 @@ -207,6 +207,12 @@ class XMLRPCServer:
     9.4          self.server.register_function(domain_create, 'xend.domain.create')
     9.5          self.server.register_function(domain_restore, 'xend.domain.restore')
     9.6  
     9.7 +        # A couple of the security functions
     9.8 +        from xen.util.xsm import xsm as security
     9.9 +        for name in security.xmlrpc_exports:
    9.10 +            fn = getattr(security, name)
    9.11 +            self.server.register_function(fn, "xend.security.%s" % name)
    9.12 +
    9.13          self.server.register_introspection_functions()
    9.14          self.ready = True
    9.15  
    10.1 --- a/tools/python/xen/xm/activatepolicy.py	Tue Dec 04 22:54:58 2007 +0000
    10.2 +++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
    10.3 @@ -1,111 +0,0 @@
    10.4 -#============================================================================
    10.5 -# This library is free software; you can redistribute it and/or
    10.6 -# modify it under the terms of version 2.1 of the GNU Lesser General Public
    10.7 -# License as published by the Free Software Foundation.
    10.8 -#
    10.9 -# This library is distributed in the hope that it will be useful,
   10.10 -# but WITHOUT ANY WARRANTY; without even the implied warranty of
   10.11 -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   10.12 -# Lesser General Public License for more details.
   10.13 -#
   10.14 -# You should have received a copy of the GNU Lesser General Public
   10.15 -# License along with this library; if not, write to the Free Software
   10.16 -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   10.17 -#============================================================================
   10.18 -# Copyright (C) 2007 International Business Machines Corp.
   10.19 -# Author: Stefan Berger <stefanb@us.ibm.com>
   10.20 -#============================================================================
   10.21 -
   10.22 -"""Activate the managed policy of the system.
   10.23 -"""
   10.24 -
   10.25 -import sys
   10.26 -from xen.util import xsconstants
   10.27 -from xml.dom import minidom
   10.28 -from xen.xm.opts import OptionError
   10.29 -from xen.xm import getpolicy, setpolicy
   10.30 -from xen.xm import main as xm_main
   10.31 -from xen.xm.main import server
   10.32 -
   10.33 -def help():
   10.34 -    return """
   10.35 -    Usage: xm activatepolicy [options]
   10.36 -
   10.37 -    Activate the xend-managed policy.
   10.38 -
   10.39 -    The following options are defined:
   10.40 -      --load     Load the policy into the hypervisor.
   10.41 -      --boot     Have the system boot with the policy. Changes the default
   10.42 -                 title in grub.conf.
   10.43 -      --noboot   Remove the policy from the default entry in grub.conf.
   10.44 -      --remove   Attempt to remove the current policy by installing the
   10.45 -                 default policy; this works only if no domains are
   10.46 -                 running.
   10.47 -    """
   10.48 -
   10.49 -def activate_policy(flags):
   10.50 -    policystate = server.xenapi.XSPolicy.get_xspolicy()
   10.51 -    xs_ref = policystate['xs_ref']
   10.52 -    if int(policystate['type']) == 0 or xs_ref == "":
   10.53 -        print "No policy is installed."
   10.54 -        return
   10.55 -    rc = int(server.xenapi.XSPolicy.activate_xspolicy(xs_ref, flags))
   10.56 -    if rc == flags:
   10.57 -        print "Successfully activated the policy."
   10.58 -    else:
   10.59 -        print "An error occurred trying to activate the policy: %s" % \
   10.60 -              xsconstants.xserr2string(rc)
   10.61 -
   10.62 -def remove_bootpolicy():
   10.63 -    server.xenapi.XSPolicy.rm_xsbootpolicy()
   10.64 -
   10.65 -def install_default_policy():
   10.66 -    if xm_main.serverType != xm_main.SERVER_XEN_API:
   10.67 -        raise OptionError('xm needs to be configured to use the xen-api.')
   10.68 -    xs_type = int(server.xenapi.XSPolicy.get_xstype())
   10.69 -    if xs_type & xsconstants.XS_POLICY_ACM == 0:
   10.70 -        raise OptionError('ACM policy type not supported on system.')
   10.71 -    policystate = server.xenapi.XSPolicy.get_xspolicy()
   10.72 -    if int(policystate['type']) == 0:
   10.73 -        print 'No policy is installed.'
   10.74 -        return
   10.75 -    if int(policystate['type']) != xsconstants.XS_POLICY_ACM:
   10.76 -        print "Unknown policy type '%s'." % policystate['type']
   10.77 -    flags = int(policystate['flags'])
   10.78 -    if flags & xsconstants.XS_INST_LOAD == 0:
   10.79 -        print "Default policy is already loaded."
   10.80 -        return
   10.81 -    setpolicy.setpolicy(xsconstants.ACM_POLICY_ID, 'default', flags, True,
   10.82 -                        False)
   10.83 -
   10.84 -def main(argv):
   10.85 -    if xm_main.serverType != xm_main.SERVER_XEN_API:
   10.86 -        raise OptionError('xm needs to be configured to use the xen-api.')
   10.87 -    flags = 0
   10.88 -    c = 1
   10.89 -
   10.90 -    while c < len(argv):
   10.91 -        if '--boot' == argv[c]:
   10.92 -            flags |= xsconstants.XS_INST_BOOT
   10.93 -        elif '--load' == argv[c]:
   10.94 -            flags |= xsconstants.XS_INST_LOAD
   10.95 -        elif '--noboot' == argv[c]:
   10.96 -            remove_bootpolicy()
   10.97 -        elif '--remove' == argv[c]:
   10.98 -            install_default_policy()
   10.99 -            return
  10.100 -        else:
  10.101 -            raise OptionError("Unknown command line option '%s'" % argv[c])
  10.102 -        c += 1
  10.103 -
  10.104 -    if flags != 0:
  10.105 -        activate_policy(flags)
  10.106 -
  10.107 -    getpolicy.getpolicy(False)
  10.108 -
  10.109 -if __name__ == '__main__':
  10.110 -    try:
  10.111 -        main(sys.argv)
  10.112 -    except Exception, e:
  10.113 -        sys.stderr.write('Error: %s\n' % str(e))
  10.114 -        sys.exit(-1)
    11.1 --- a/tools/python/xen/xm/addlabel.py	Tue Dec 04 22:54:58 2007 +0000
    11.2 +++ b/tools/python/xen/xm/addlabel.py	Wed Dec 05 09:44:20 2007 +0000
    11.3 @@ -22,7 +22,6 @@
    11.4  import os
    11.5  import sys
    11.6  
    11.7 -from xen.util import dictio
    11.8  import xen.util.xsm.xsm as security
    11.9  from xen.xm.opts import OptionError
   11.10  from xen.util import xsconstants
   11.11 @@ -37,14 +36,12 @@ def help():
   11.12              xm addlabel <label> vif-<idx> <domain name> [<policy type>:<policy>]
   11.13      
   11.14      This program adds an acm_label entry into the 'configfile'
   11.15 -    for a domain or allows to label a xend-managed domain.
   11.16 -    The global resource label file for is extended with labels for
   11.17 -    resources. It derives the policy from the running hypervisor
   11.18 -    if it is not given (optional parameter). If a label already
   11.19 -    exists for the given domain or resource, then addlabel fails.
   11.20 +    for a domain, allows to label a xend-managed domain, resources
   11.21 +    of the VIF of a mangaged domain (requires xm to be used in
   11.22 +    Xen-API mode).
   11.23  
   11.24      For xend-managed domains, the 'mgt' parameter should be used and
   11.25 -    the 'xm' tool must have been configured to use the xen-api for
   11.26 +    the 'xm' tool must have been configured to use the xen-npi for
   11.27      communication with xen. If a policy is provided as last parameter,
   11.28      its type must also be given. Currently only one type of policy is
   11.29      supported and identified as 'ACM'. An example for a valid string
   11.30 @@ -84,29 +81,22 @@ def add_resource_label(label, resource, 
   11.31      """
   11.32  
   11.33      if xm_main.serverType != xm_main.SERVER_XEN_API:
   11.34 -
   11.35 -        # sanity check: make sure this label can be instantiated later on
   11.36 -        ssidref = security.label2ssidref(label, policyref, 'res')
   11.37 -
   11.38 -        #build canonical resource name
   11.39 -        resource = security.unify_resname(resource,mustexist=False)
   11.40 -
   11.41 -        # see if this resource is already in the file
   11.42 -        access_control = {}
   11.43 -        fil = security.res_label_filename
   11.44 -        try:
   11.45 -            access_control = dictio.dict_read("resources", fil)
   11.46 -        except:
   11.47 -            print "Resource file not found, creating new file at:"
   11.48 -            print "%s" % (fil)
   11.49 -
   11.50 -        if access_control.has_key(resource):
   11.51 -            security.err("This resource is already labeled.")
   11.52 -
   11.53 -        # write the data to file
   11.54 -        new_entry = { resource : tuple([policy_type, policyref, label]) }
   11.55 -        access_control.update(new_entry)
   11.56 -        dictio.dict_write(access_control, "resources", fil)
   11.57 +        old = server.xend.security.get_resource_label(resource)
   11.58 +        if len(old) == 0:
   11.59 +            try:
   11.60 +                rc = server.xend.security.set_resource_label(resource,
   11.61 +                                                             policy_type,
   11.62 +                                                             policyref,
   11.63 +                                                             label)
   11.64 +            except Exception, e:
   11.65 +                raise
   11.66 +            if rc != xsconstants.XSERR_SUCCESS:
   11.67 +                security.err("An error occurred labeling the resource: %s" % \
   11.68 +                             xsconstants.xserr2string(-rc))
   11.69 +        else:
   11.70 +            old = security.format_resource_label(old)
   11.71 +            security.err("'%s' is already labeled with '%s'." % \
   11.72 +                         (resource,old))
   11.73      else:
   11.74          res = [ policy_type, policyref, label ]
   11.75          res_xapi = security.format_resource_label(res)
   11.76 @@ -141,30 +131,48 @@ def add_domain_label(label, configfile, 
   11.77      config_fd.close()
   11.78  
   11.79  def add_domain_label_xapi(label, domainname, policyref, policy_type):
   11.80 -    if xm_main.serverType != xm_main.SERVER_XEN_API:
   11.81 -        raise OptionError('Xm must be configured to use the xen-api.')
   11.82 -    uuids = server.xenapi.VM.get_by_name_label(domainname)
   11.83 -    if len(uuids) == 0:
   11.84 -        raise OptionError('A VM with that name does not exist.')
   11.85 -    if len(uuids) != 1:
   11.86 -        raise OptionError('There are multiple domains with the same name.')
   11.87 -    uuid = uuids[0]
   11.88      sec_lab = "%s:%s:%s" % (policy_type, policyref, label)
   11.89 -    try:
   11.90 -        old_lab = server.xenapi.VM.get_security_label(uuid)
   11.91 -        rc = server.xenapi.VM.set_security_label(uuid, sec_lab, old_lab)
   11.92 -    except Exception, e:
   11.93 -        raise security.XSMError("Could not label the domain: %s" % e)
   11.94 -    if int(rc) < 0:
   11.95 -        raise OptionError('Could not label domain.')
   11.96 +    if xm_main.serverType != xm_main.SERVER_XEN_API:
   11.97 +        old_seclab = server.xend.security.get_domain_label(domainname)
   11.98 +        if old_seclab[0] == '\'':
   11.99 +            old_seclab = old_seclab[1:]
  11.100 +        results = server.xend.security.set_domain_label(domainname,
  11.101 +                                                        sec_lab,
  11.102 +                                                        old_seclab)
  11.103 +        rc, ssidref = results
  11.104 +        if rc == xsconstants.XSERR_SUCCESS:
  11.105 +            if ssidref != 0:
  11.106 +                print "Successfully set the label of domain '%s' to '%s'.\n" \
  11.107 +                      % (domainname,label)
  11.108 +            else:
  11.109 +                print "Successfully set the label of the dormant domain " \
  11.110 +                      "'%s' to '%s'." % (domainname,label)
  11.111 +        else:
  11.112 +            msg = xsconstants.xserr2string(-rc)
  11.113 +            raise security.XSMError("An error occurred relabeling "
  11.114 +                                    "the domain: %s" % msg)
  11.115      else:
  11.116 -        ssidref = int(rc)
  11.117 -        if ssidref != 0:
  11.118 -            print "Set the label of domain '%s' to '%s'. New ssidref = %08x" %\
  11.119 -                  (domainname,label,ssidref)
  11.120 +        uuids = server.xenapi.VM.get_by_name_label(domainname)
  11.121 +        if len(uuids) == 0:
  11.122 +            raise OptionError('A VM with that name does not exist.')
  11.123 +        if len(uuids) != 1:
  11.124 +            raise OptionError('There are multiple domains with the same name.')
  11.125 +        uuid = uuids[0]
  11.126 +        try:
  11.127 +            old_lab = server.xenapi.VM.get_security_label(uuid)
  11.128 +            rc = server.xenapi.VM.set_security_label(uuid, sec_lab, old_lab)
  11.129 +        except Exception, e:
  11.130 +            raise security.XSMError("Could not label the domain: %s" % e)
  11.131 +        if int(rc) < 0:
  11.132 +            raise OptionError('Could not label domain.')
  11.133          else:
  11.134 -            print "Set the label of dormant domain '%s' to '%s'." % \
  11.135 -                  (domainname,label)
  11.136 +            ssidref = int(rc)
  11.137 +            if ssidref != 0:
  11.138 +                print "Successfully set the label of domain '%s' to '%s'.\n" \
  11.139 +                      % (domainname,label)
  11.140 +            else:
  11.141 +                print "Successfully set the label of the dormant domain " \
  11.142 +                      "'%s' to '%s'." % (domainname,label)
  11.143  
  11.144  def add_vif_label(label, vmname, idx, policyref, policy_type):
  11.145      if xm_main.serverType != xm_main.SERVER_XEN_API:
  11.146 @@ -212,7 +220,7 @@ def main(argv):
  11.147      if argv[2].lower() == "dom":
  11.148          configfile = argv[3]
  11.149          if configfile[0] != '/':
  11.150 -            for prefix in [".", "/etc/xen"]:
  11.151 +            for prefix in [os.path.realpath(os.path.curdir), "/etc/xen"]:
  11.152                  configfile = prefix + "/" + configfile
  11.153                  if os.path.isfile(configfile):
  11.154                      break
    12.1 --- a/tools/python/xen/xm/cfgbootpolicy.py	Tue Dec 04 22:54:58 2007 +0000
    12.2 +++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
    12.3 @@ -1,227 +0,0 @@
    12.4 -#============================================================================
    12.5 -# This library is free software; you can redistribute it and/or
    12.6 -# modify it under the terms of version 2.1 of the GNU Lesser General Public
    12.7 -# License as published by the Free Software Foundation.
    12.8 -#
    12.9 -# This library is distributed in the hope that it will be useful,
   12.10 -# but WITHOUT ANY WARRANTY; without even the implied warranty of
   12.11 -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   12.12 -# Lesser General Public License for more details.
   12.13 -#
   12.14 -# You should have received a copy of the GNU Lesser General Public
   12.15 -# License along with this library; if not, write to the Free Software
   12.16 -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   12.17 -#============================================================================
   12.18 -# Copyright (C) 2006 International Business Machines Corp.
   12.19 -# Author: Reiner Sailer <sailer@us.ibm.com>
   12.20 -# Contributions: Stefan Berger <stefanb@us.ibm.com>
   12.21 -#============================================================================
   12.22 -"""Configuring a security policy into the boot configuration
   12.23 -"""
   12.24 -
   12.25 -import sys
   12.26 -import traceback
   12.27 -import tempfile
   12.28 -import os, stat
   12.29 -import shutil
   12.30 -import string
   12.31 -import re
   12.32 -from xen.util.xsm.xsm import err
   12.33 -from xen.util.xsm.xsm import policy_dir_prefix, xen_title_re
   12.34 -from xen.util.xsm.xsm import boot_filename, altboot_filename
   12.35 -from xen.util.xsm.xsm import any_title_re, xen_kernel_re, any_module_re
   12.36 -from xen.util.xsm.xsm import empty_line_re, binary_name_re, policy_name_re
   12.37 -from xen.util import xsconstants
   12.38 -from xen.xm.opts import OptionError
   12.39 -from xen.xm import main as xm_main
   12.40 -from xen.xm.main import server
   12.41 -from xen.util.acmpolicy import ACMPolicy
   12.42 -
   12.43 -def help():
   12.44 -    return """
   12.45 -    Adds a 'module' line to the Xen grub configuration file entry
   12.46 -    so that Xen boots with a specific access control policy. If
   12.47 -    boot-title is not given, then this script tries to determine
   12.48 -    it by looking for a title starting with \"XEN\". If there are
   12.49 -    multiple entries matching, then it must be called with the unique
   12.50 -    beginning of the title's name.\n"""
   12.51 -
   12.52 -def strip_title(line):
   12.53 -    """
   12.54 -    strips whitespace left and right and cuts 'title'
   12.55 -    """
   12.56 -    s_title = string.strip(line)
   12.57 -    pos = string.index(s_title, "title")
   12.58 -    if pos >= 0:
   12.59 -        return s_title[pos+6:]
   12.60 -    else:
   12.61 -        return s_title
   12.62 -
   12.63 -
   12.64 -def insert_policy(boot_file, alt_boot_file, user_title, policy_name):
   12.65 -    """
   12.66 -    inserts policy binary file as last line of the grub entry
   12.67 -    matching the user_title or default title
   12.68 -    """
   12.69 -    if user_title:
   12.70 -        #replace "(" by "\(" and ")" by "\)" for matching
   12.71 -        user_title = string.replace(user_title, "(", "\(")
   12.72 -        user_title = string.replace(user_title, ")", "\)")
   12.73 -        user_title_re = re.compile("\s*title\s+.*%s" \
   12.74 -                                   % user_title, re.IGNORECASE)
   12.75 -    else:
   12.76 -        user_title_re = xen_title_re
   12.77 -
   12.78 -    within_xen_title = 0
   12.79 -    within_xen_entry = 0
   12.80 -    insert_at_end_of_entry = 0
   12.81 -    path_prefix = ''
   12.82 -    this_title = ''
   12.83 -    extended_titles = []
   12.84 -    (tmp_fd, tmp_grub) = tempfile.mkstemp()
   12.85 -    #First check whether menu.lst exists
   12.86 -    if not os.path.isfile(boot_file):
   12.87 -        #take alternate boot file (grub.conf) instead
   12.88 -        boot_file = alt_boot_file
   12.89 -    #follow symlink since menue.lst might be linked to grub.conf
   12.90 -    if stat.S_ISLNK(os.lstat(boot_file)[stat.ST_MODE]):
   12.91 -        new_name = os.readlink(boot_file)
   12.92 -        if new_name[0] == "/":
   12.93 -            boot_file = new_name
   12.94 -        else:
   12.95 -            path = boot_file.split('/')
   12.96 -            path[len(path)-1] = new_name
   12.97 -            boot_file = '/'.join(path)
   12.98 -        if not os.path.exists(boot_file):
   12.99 -            err("Boot file \'%s\' not found." % boot_file)
  12.100 -    grub_fd = open(boot_file)
  12.101 -    for line in grub_fd:
  12.102 -        if user_title_re.match(line):
  12.103 -            this_title = strip_title(line)
  12.104 -            within_xen_title = 1
  12.105 -        elif within_xen_title and xen_kernel_re.match(line):
  12.106 -            insert_at_end_of_entry = 1
  12.107 -            #use prefix from xen.gz path for policy
  12.108 -            path_prefix = line.split()[1]
  12.109 -            idx = path_prefix.rfind('/')
  12.110 -            if idx >= 0:
  12.111 -                path_prefix = path_prefix[0:idx+1]
  12.112 -            else:
  12.113 -                path_prefix = ''
  12.114 -        elif any_module_re.match(line) and insert_at_end_of_entry:
  12.115 -            if binary_name_re.match(line):
  12.116 -                #delete existing policy module line
  12.117 -                line=''
  12.118 -        elif any_title_re.match(line):
  12.119 -            within_xen_title = 0
  12.120 -
  12.121 -        if (empty_line_re.match(line) or any_title_re.match(line)) and \
  12.122 -            insert_at_end_of_entry:
  12.123 -            #newline or new title: we insert the policy module line here
  12.124 -            os.write(tmp_fd, "\tmodule " + path_prefix + policy_name + ".bin\n")
  12.125 -            extended_titles.append(this_title)
  12.126 -            insert_at_end_of_entry = 0
  12.127 -        #write the line that was read (except potential existing policy entry)
  12.128 -        os.write(tmp_fd, line)
  12.129 -
  12.130 -    if insert_at_end_of_entry:
  12.131 -        #last entry, no empty line at end of file
  12.132 -        os.write(tmp_fd, "\tmodule " + path_prefix + policy_name + ".bin\n")
  12.133 -        extended_titles.append(this_title)
  12.134 -
  12.135 -    #if more than one entry was changed, abort
  12.136 -    if len(extended_titles) > 1:
  12.137 -        err("Following boot entries matched: %s. \nPlease specify "
  12.138 -            "unique part of the boot title." % extended_titles)
  12.139 -    if len(extended_titles) == 0:
  12.140 -        err("Boot entry not found. Please specify unique part "
  12.141 -            "of the boot title.")
  12.142 -
  12.143 -    #temp file might be destroyed when closing it, first copy it
  12.144 -    shutil.move(boot_file, boot_file+"_save")
  12.145 -    shutil.copyfile(tmp_grub, boot_file)
  12.146 -    os.close(tmp_fd)
  12.147 -    #sometimes the temp file does not disappear
  12.148 -    try:
  12.149 -        os.remove(tmp_grub)
  12.150 -    except:
  12.151 -        pass
  12.152 -    return extended_titles[0]
  12.153 -
  12.154 -def cfgbootpolicy_xapi(policy, user_title=None):
  12.155 -    xstype = int(server.xenapi.XSPolicy.get_xstype())
  12.156 -    if xstype & xsconstants.XS_POLICY_ACM == 0:
  12.157 -        raise OptionError("ACM policy not supported on system.")
  12.158 -    if user_title:
  12.159 -        raise OptionError("Only the default title is supported with Xen-API.")
  12.160 -
  12.161 -    policystate = server.xenapi.XSPolicy.get_xspolicy()
  12.162 -    if int(policystate['type']) == 0:
  12.163 -        print "No policy is installed."
  12.164 -        return
  12.165 -
  12.166 -    if int(policystate['type']) != xsconstants.XS_POLICY_ACM:
  12.167 -        print "Unknown policy type '%s'." % policystate['type']
  12.168 -        return
  12.169 -    else:
  12.170 -        xml = policystate['repr']
  12.171 -        xs_ref = policystate['xs_ref']
  12.172 -        if not xml:
  12.173 -            OptionError("No policy installed on system?")
  12.174 -        acmpol = ACMPolicy(xml=xml)
  12.175 -        if acmpol.get_name() != policy:
  12.176 -            raise OptionError("Policy installed on system '%s' does not "
  12.177 -                              "match the requested policy '%s'" %
  12.178 -                              (acmpol.get_name(), policy))
  12.179 -        flags = int(policystate['flags']) | xsconstants.XS_INST_BOOT
  12.180 -        rc = int(server.xenapi.XSPolicy.activate_xspolicy(xs_ref, flags))
  12.181 -        if rc == flags:
  12.182 -            print "Successfully enabled the policy for having the system" \
  12.183 -                  " booted with."
  12.184 -        else:
  12.185 -            print "An error occurred during the operation: %s" % \
  12.186 -                  xsconstants.xserr2string(rc)
  12.187 -
  12.188 -
  12.189 -def main(argv):
  12.190 -    user_kver = None
  12.191 -    user_title = None
  12.192 -    if len(argv) == 2:
  12.193 -        policy = argv[1]
  12.194 -    elif len(argv) == 3:
  12.195 -        policy = argv[1]
  12.196 -        user_title = argv[2]
  12.197 -    else:
  12.198 -        raise OptionError('Invalid number of arguments')
  12.199 -    
  12.200 -    if not policy_name_re.match(policy):
  12.201 -        raise OptionError("Illegal policy name: '%s'" % policy)
  12.202 -
  12.203 -    if xm_main.serverType == xm_main.SERVER_XEN_API:
  12.204 -        cfgbootpolicy_xapi(policy)
  12.205 -    else:
  12.206 -        policy_file = '/'.join([policy_dir_prefix] + policy.split('.'))
  12.207 -        src_binary_policy_file = policy_file + ".bin"
  12.208 -        #check if .bin exists or if policy file exists
  12.209 -        if not os.path.isfile(src_binary_policy_file):
  12.210 -            if not os.path.isfile(policy_file + "-security_policy.xml"):
  12.211 -                raise OptionError("Unknown policy '%s'" % policy)
  12.212 -            else:
  12.213 -                err_msg = "Cannot find binary file for policy '%s'." % policy
  12.214 -                err_msg += " Please use makepolicy to create binary file."
  12.215 -                raise OptionError(err_msg)
  12.216 -    
  12.217 -        dst_binary_policy_file = "/boot/" + policy + ".bin"
  12.218 -        shutil.copyfile(src_binary_policy_file, dst_binary_policy_file)
  12.219 -    
  12.220 -        entryname = insert_policy(boot_filename, altboot_filename,
  12.221 -                                  user_title, policy)
  12.222 -        print "Boot entry '%s' extended and \'%s\' copied to /boot" \
  12.223 -              % (entryname, policy + ".bin")
  12.224 -
  12.225 -if __name__ == '__main__':
  12.226 -    try:
  12.227 -        main(sys.argv)
  12.228 -    except Exception, e:
  12.229 -        sys.stderr.write('Error: ' + str(e) + '\n')    
  12.230 -        sys.exit(-1)
    13.1 --- a/tools/python/xen/xm/create.py	Tue Dec 04 22:54:58 2007 +0000
    13.2 +++ b/tools/python/xen/xm/create.py	Wed Dec 05 09:44:20 2007 +0000
    13.3 @@ -659,11 +659,7 @@ def configure_security(config, vals):
    13.4                                   ['policy', policy],
    13.5                                   ['label', label] ]
    13.6  
    13.7 -        #calculate ssidref from label
    13.8 -        ssidref = security.label2ssidref(label, policy, 'dom')
    13.9 -        if not ssidref :
   13.10 -            err("ERROR calculating ssidref from access_control.")
   13.11 -        security_label = ['security', [ config_access_control, ['ssidref' , ssidref ] ] ]
   13.12 +        security_label = ['security', [ config_access_control ] ]
   13.13          config.append(security_label)
   13.14      elif num > 1:
   13.15          err("VM config error: Multiple access_control definitions!")
   13.16 @@ -1151,121 +1147,6 @@ def parseCommandLine(argv):
   13.17  
   13.18      return (gopts, config)
   13.19  
   13.20 -
   13.21 -def check_domain_label(config, verbose):
   13.22 -    """All that we need to check here is that the domain label exists and
   13.23 -       is not null when security is on.  Other error conditions are
   13.24 -       handled when the config file is parsed.
   13.25 -    """
   13.26 -    answer = 0
   13.27 -    default_label = None
   13.28 -    secon = 0
   13.29 -    if security.on():
   13.30 -        default_label = security.ssidref2label(security.NULL_SSIDREF)
   13.31 -        secon = 1
   13.32 -
   13.33 -    # get the domain acm_label
   13.34 -    dom_label = None
   13.35 -    dom_name = None
   13.36 -    for x in sxp.children(config):
   13.37 -        if sxp.name(x) == 'security':
   13.38 -            dom_label = sxp.child_value(sxp.name(sxp.child0(x)), 'label')
   13.39 -        if sxp.name(x) == 'name':
   13.40 -            dom_name = sxp.child0(x)
   13.41 -
   13.42 -    # sanity check on domain label
   13.43 -    if verbose:
   13.44 -        print "Checking domain:"
   13.45 -    if (not secon) and (not dom_label):
   13.46 -        answer = 1
   13.47 -        if verbose:
   13.48 -            print "   %s: PERMITTED" % (dom_name)
   13.49 -    elif (secon) and (dom_label) and (dom_label != default_label):
   13.50 -        answer = 1
   13.51 -        if verbose:
   13.52 -            print "   %s: PERMITTED" % (dom_name)
   13.53 -    else:
   13.54 -        print "   %s: DENIED" % (dom_name)
   13.55 -        if not secon:
   13.56 -            print "   --> Security off, but domain labeled"
   13.57 -        else:
   13.58 -            print "   --> Domain not labeled"
   13.59 -        answer = 0
   13.60 -
   13.61 -    return answer
   13.62 -
   13.63 -def config_security_check(config, verbose):
   13.64 -    """Checks each resource listed in the config to see if the active
   13.65 -       policy will permit creation of a new domain using the config.
   13.66 -       Returns 1 if the config passes all tests, otherwise 0.
   13.67 -    """
   13.68 -    answer = 1
   13.69 -
   13.70 -    # get the domain acm_label
   13.71 -    domain_label = None
   13.72 -    domain_policy = None
   13.73 -    for x in sxp.children(config):
   13.74 -        if sxp.name(x) == 'security':
   13.75 -            domain_label = sxp.child_value(sxp.name(sxp.child0(x)), 'label')
   13.76 -            domain_policy = sxp.child_value(sxp.name(sxp.child0(x)), 'policy')
   13.77 -
   13.78 -    # if no domain label, use default
   13.79 -    if not domain_label and security.on():
   13.80 -        try:
   13.81 -            domain_label = security.ssidref2label(security.NULL_SSIDREF)
   13.82 -        except:
   13.83 -            import traceback
   13.84 -            traceback.print_exc(limit=1)
   13.85 -            return 0
   13.86 -        domain_policy = 'NULL'
   13.87 -    elif not domain_label:
   13.88 -        domain_label = ""
   13.89 -        domain_policy = 'NULL'
   13.90 -
   13.91 -    if verbose:
   13.92 -        print "Checking resources:"
   13.93 -
   13.94 -    # build a list of all resources in the config file
   13.95 -    resources = []
   13.96 -    for x in sxp.children(config):
   13.97 -        if sxp.name(x) == 'device':
   13.98 -            if sxp.name(sxp.child0(x)) == 'vbd':
   13.99 -                resources.append(sxp.child_value(sxp.child0(x), 'uname'))
  13.100 -
  13.101 -    # perform a security check on each resource
  13.102 -    for resource in resources:
  13.103 -        try:
  13.104 -            security.res_security_check(resource, domain_label)
  13.105 -            if verbose:
  13.106 -                print "   %s: PERMITTED" % (resource)
  13.107 -
  13.108 -        except security.ACMError:
  13.109 -            print "   %s: DENIED" % (resource)
  13.110 -            (poltype, res_label, res_policy) = security.get_res_label(resource)
  13.111 -            if not res_label:
  13.112 -                res_label = ""
  13.113 -            print "   --> res: %s (%s:%s)" % (str(res_label),
  13.114 -                                           str(poltype), str(res_policy))
  13.115 -            print "   --> dom: %s (%s:%s)" % (str(domain_label),
  13.116 -                                           str(poltype), str(domain_policy))
  13.117 -
  13.118 -            answer = 0
  13.119 -
  13.120 -    return answer
  13.121 -
  13.122 -def create_security_check(config):
  13.123 -    passed = 0
  13.124 -    try:
  13.125 -        if check_domain_label(config, verbose=0):
  13.126 -            if config_security_check(config, verbose=0):
  13.127 -                passed = 1
  13.128 -        else:
  13.129 -            print "Checking resources: (skipped)"
  13.130 -    except security.XSMError:
  13.131 -        sys.exit(-1)
  13.132 -
  13.133 -    return passed
  13.134 -  
  13.135  def help():
  13.136      return str(gopts)
  13.137  
  13.138 @@ -1317,9 +1198,6 @@ def main(argv):
  13.139  
  13.140          map(lambda vm_ref: server.xenapi.VM.start(vm_ref, 0), vm_refs)
  13.141      elif not opts.is_xml:
  13.142 -        if not create_security_check(config):
  13.143 -            raise security.XSMError(
  13.144 -                'Security Configuration prevents domain from starting')
  13.145          dom = make_domain(opts, config)
  13.146          
  13.147  def do_console(domain_name):
    14.1 --- a/tools/python/xen/xm/dry-run.py	Tue Dec 04 22:54:58 2007 +0000
    14.2 +++ b/tools/python/xen/xm/dry-run.py	Wed Dec 05 09:44:20 2007 +0000
    14.3 @@ -31,14 +31,117 @@ def help():
    14.4      the resources.  The status of each resource is listed
    14.5      individually along with the final security decision."""
    14.6  
    14.7 +
    14.8 +def check_domain_label(config, verbose):
    14.9 +    """All that we need to check here is that the domain label exists and
   14.10 +       is not null when security is on.  Other error conditions are
   14.11 +       handled when the config file is parsed.
   14.12 +    """
   14.13 +    answer = 0
   14.14 +    default_label = None
   14.15 +    secon = 0
   14.16 +    if security.on():
   14.17 +        default_label = security.ssidref2label(security.NULL_SSIDREF)
   14.18 +        secon = 1
   14.19 +
   14.20 +    # get the domain acm_label
   14.21 +    dom_label = None
   14.22 +    dom_name = None
   14.23 +    for x in sxp.children(config):
   14.24 +        if sxp.name(x) == 'security':
   14.25 +            dom_label = sxp.child_value(sxp.name(sxp.child0(x)), 'label')
   14.26 +        if sxp.name(x) == 'name':
   14.27 +            dom_name = sxp.child0(x)
   14.28 +
   14.29 +    # sanity check on domain label
   14.30 +    if verbose:
   14.31 +        print "Checking domain:"
   14.32 +    if (not secon) and (not dom_label):
   14.33 +        answer = 1
   14.34 +        if verbose:
   14.35 +            print "   %s: PERMITTED" % (dom_name)
   14.36 +    elif (secon) and (dom_label) and (dom_label != default_label):
   14.37 +        answer = 1
   14.38 +        if verbose:
   14.39 +            print "   %s: PERMITTED" % (dom_name)
   14.40 +    else:
   14.41 +        print "   %s: DENIED" % (dom_name)
   14.42 +        if not secon:
   14.43 +            print "   --> Security off, but domain labeled"
   14.44 +        else:
   14.45 +            print "   --> Domain not labeled"
   14.46 +        answer = 0
   14.47 +
   14.48 +    return answer
   14.49 +
   14.50 +def config_security_check(config, verbose):
   14.51 +    """Checks each resource listed in the config to see if the active
   14.52 +       policy will permit creation of a new domain using the config.
   14.53 +       Returns 1 if the config passes all tests, otherwise 0.
   14.54 +    """
   14.55 +    answer = 1
   14.56 +
   14.57 +    # get the domain acm_label
   14.58 +    domain_label = None
   14.59 +    domain_policy = None
   14.60 +    for x in sxp.children(config):
   14.61 +        if sxp.name(x) == 'security':
   14.62 +            domain_label = sxp.child_value(sxp.name(sxp.child0(x)), 'label')
   14.63 +            domain_policy = sxp.child_value(sxp.name(sxp.child0(x)), 'policy')
   14.64 +
   14.65 +    # if no domain label, use default
   14.66 +    if not domain_label and security.on():
   14.67 +        try:
   14.68 +            domain_label = security.ssidref2label(security.NULL_SSIDREF)
   14.69 +        except:
   14.70 +            import traceback
   14.71 +            traceback.print_exc(limit=1)
   14.72 +            return 0
   14.73 +        domain_policy = 'NULL'
   14.74 +    elif not domain_label:
   14.75 +        domain_label = ""
   14.76 +        domain_policy = 'NULL'
   14.77 +
   14.78 +    if verbose:
   14.79 +        print "Checking resources:"
   14.80 +
   14.81 +    # build a list of all resources in the config file
   14.82 +    resources = []
   14.83 +    for x in sxp.children(config):
   14.84 +        if sxp.name(x) == 'device':
   14.85 +            if sxp.name(sxp.child0(x)) == 'vbd':
   14.86 +                resources.append(sxp.child_value(sxp.child0(x), 'uname'))
   14.87 +
   14.88 +    # perform a security check on each resource
   14.89 +    for resource in resources:
   14.90 +        try:
   14.91 +            security.res_security_check(resource, domain_label)
   14.92 +            if verbose:
   14.93 +                print "   %s: PERMITTED" % (resource)
   14.94 +
   14.95 +        except security.XSMError:
   14.96 +            print "   %s: DENIED" % (resource)
   14.97 +            (poltype, res_label, res_policy) = security.get_res_label(resource)
   14.98 +            if not res_label:
   14.99 +                res_label = ""
  14.100 +            print "   --> res: %s (%s:%s)" % (str(res_label),
  14.101 +                                           str(poltype), str(res_policy))
  14.102 +            print "   --> dom: %s (%s:%s)" % (str(domain_label),
  14.103 +                                           str(poltype), str(domain_policy))
  14.104 +
  14.105 +            answer = 0
  14.106 +
  14.107 +    return answer
  14.108 +
  14.109 +
  14.110  def main (argv):
  14.111      if len(argv) != 2:
  14.112          raise OptionError('Invalid number of arguments')
  14.113      
  14.114      passed = 0
  14.115      (opts, config) = create.parseCommandLine(argv)
  14.116 -    if create.check_domain_label(config, verbose=1):
  14.117 -        if create.config_security_check(config, verbose=1):
  14.118 +    if check_domain_label(config, verbose=1):
  14.119 +        if config_security_check(config, verbose=1):
  14.120              passed = 1
  14.121      else:
  14.122          print "Checking resources: (skipped)"
    15.1 --- a/tools/python/xen/xm/getlabel.py	Tue Dec 04 22:54:58 2007 +0000
    15.2 +++ b/tools/python/xen/xm/getlabel.py	Wed Dec 05 09:44:20 2007 +0000
    15.3 @@ -19,7 +19,6 @@
    15.4  """Show the label for a domain or resoruce.
    15.5  """
    15.6  import sys, os, re
    15.7 -from xen.util import dictio
    15.8  import xen.util.xsm.xsm as security
    15.9  from xen.util import xsconstants
   15.10  from xen.xm.opts import OptionError
   15.11 @@ -33,36 +32,25 @@ def help():
   15.12             xm getlabel res <resource>
   15.13             xm getlabel vif-<idx> <vmname>
   15.14             
   15.15 -    This program shows the label for a domain, resource or virtual network
   15.16 -    interface of a Xend-managed domain."""
   15.17 +    This program shows the label for a domain from its configuration
   15.18 +    file, the label of a Xend-managed domain, that of a resources or
   15.19 +    the label of a virtual network interface of a managed domain
   15.20 +    (requires xm to be used in Xen-API mode).
   15.21 +    """
   15.22  
   15.23  def get_resource_label(resource):
   15.24      """Gets the resource label
   15.25      """
   15.26 -    #build canonical resource name
   15.27 -    resource = security.unify_resname(resource)
   15.28 -
   15.29 -    # read in the resource file
   15.30 -    fil = security.res_label_filename
   15.31 -    try:
   15.32 -        access_control = dictio.dict_read("resources", fil)
   15.33 -    except:
   15.34 -        raise OptionError("Resource label file not found")
   15.35 -
   15.36 -    # get the entry and print label
   15.37 -    if access_control.has_key(resource):
   15.38 -        tmp = access_control[resource]
   15.39 -        if len(tmp) == 2:
   15.40 -            policy, label = tmp
   15.41 -            policytype = xsconstants.ACM_POLICY_ID
   15.42 -        elif len(tmp) == 3:
   15.43 -            policytype, policy, label = tmp
   15.44 -        else:
   15.45 -            raise security.ACMError("Resource not properly labeled. "
   15.46 -                                    "Please relabel the resource.")
   15.47 -        print policytype+":"+policy+":"+label
   15.48 +    if xm_main.serverType == xm_main.SERVER_XEN_API:
   15.49 +        reslabel = server.xenapi.XSPolicy.get_resource_label(resource)
   15.50 +        if reslabel == "":
   15.51 +            raise security.XSMError("Resource not labeled")
   15.52 +        print reslabel
   15.53      else:
   15.54 -        raise security.XSMError("Resource not labeled")
   15.55 +        reslabel = server.xend.security.get_resource_label(resource)
   15.56 +        if len(reslabel) == 0:
   15.57 +            raise security.XSMError("Resource not labeled")
   15.58 +        print ":".join(reslabel)
   15.59  
   15.60  
   15.61  def get_domain_label(configfile):
   15.62 @@ -120,16 +108,19 @@ def get_vif_label(vmname, idx):
   15.63      sec_lab = server.xenapi.VIF.get_security_label(vif_ref)
   15.64      print "%s" % sec_lab
   15.65  
   15.66 -def get_domain_label_xapi(domainname):
   15.67 +def get_domain_label_xapi(domain):
   15.68      if xm_main.serverType != xm_main.SERVER_XEN_API:
   15.69 -        raise OptionError('xm needs to be configure to use the xen-api.')
   15.70 -    uuids = server.xenapi.VM.get_by_name_label(domainname)
   15.71 -    if len(uuids) == 0:
   15.72 -        raise OptionError('A VM with that name does not exist.')
   15.73 -    if len(uuids) != 1:
   15.74 -        raise OptionError('There are multiple domains with the same name.')
   15.75 -    uuid = uuids[0]
   15.76 -    sec_lab = server.xenapi.VM.get_security_label(uuid)
   15.77 +        sec_lab = server.xend.security.get_domain_label(domain)
   15.78 +        if len(sec_lab) > 0 and sec_lab[0] == '\'':
   15.79 +            sec_lab = sec_lab[1:]
   15.80 +    else:
   15.81 +        uuids = server.xenapi.VM.get_by_name_label(domain)
   15.82 +        if len(uuids) == 0:
   15.83 +            raise OptionError('A VM with that name does not exist.')
   15.84 +        if len(uuids) != 1:
   15.85 +            raise OptionError('There are multiple domains with the same name.')
   15.86 +        uuid = uuids[0]
   15.87 +        sec_lab = server.xenapi.VM.get_security_label(uuid)
   15.88      print "%s" %sec_lab
   15.89  
   15.90  def main(argv):
   15.91 @@ -164,4 +155,3 @@ if __name__ == '__main__':
   15.92      except Exception, e:
   15.93          sys.stderr.write('Error: %s\n' % str(e))
   15.94          sys.exit(-1)
   15.95 -
    16.1 --- a/tools/python/xen/xm/getpolicy.py	Tue Dec 04 22:54:58 2007 +0000
    16.2 +++ b/tools/python/xen/xm/getpolicy.py	Wed Dec 05 09:44:20 2007 +0000
    16.3 @@ -36,47 +36,88 @@ def help():
    16.4  
    16.5      Get the policy managed by xend."""
    16.6  
    16.7 -def getpolicy(dumpxml):
    16.8 -    if xm_main.serverType != xm_main.SERVER_XEN_API:
    16.9 -        raise OptionError('xm needs to be configured to use the xen-api.')
   16.10 +
   16.11 +def display_policy_info(acmpol, policytype, uuid, version, flags,
   16.12 +                        dumpxml, xml):
   16.13 +    print "Policy name           : %s" % acmpol.get_name()
   16.14 +    print "Policy type           : %s" % policytype
   16.15 +    if uuid:
   16.16 +        print "Reference             : %s" % uuid
   16.17 +    print "Version of XML policy : %s" % version
   16.18 +
   16.19 +    state = []
   16.20 +    if flags & xsconstants.XS_INST_LOAD:
   16.21 +        state.append("loaded")
   16.22 +    if flags & xsconstants.XS_INST_BOOT:
   16.23 +        state.append("activated for boot")
   16.24 +    print "Policy configuration  : %s" % ", ".join(state)
   16.25 +    if dumpxml:
   16.26 +        if xml:
   16.27 +            dom = minidom.parseString(xml.encode("utf-8"))
   16.28 +            print "%s" % dom.toprettyxml(indent="   ",newl="\n")
   16.29 +
   16.30 +
   16.31 +def display_security_subsystems(xstype):
   16.32      types = []
   16.33 -    xstype = int(server.xenapi.XSPolicy.get_xstype())
   16.34      if xstype & xsconstants.XS_POLICY_ACM:
   16.35          types.append("ACM")
   16.36          xstype ^= xsconstants.XS_POLICY_ACM
   16.37      if xstype != 0:
   16.38          types.append("unsupported (%08x)" % xstype)
   16.39 +    if len(types) == 0:
   16.40 +        types.append("None")
   16.41      print "Supported security subsystems   : %s \n" % ", ".join(types)
   16.42  
   16.43 -    policystate = server.xenapi.XSPolicy.get_xspolicy()
   16.44 -    if int(policystate['type']) == 0:
   16.45 -        print "No policy is installed."
   16.46 -        return
   16.47 -    if int(policystate['type']) != xsconstants.XS_POLICY_ACM:
   16.48 -        print "Unknown policy type '%s'." % policystate['type']
   16.49 +
   16.50 +def getpolicy(dumpxml):
   16.51 +    if xm_main.serverType == xm_main.SERVER_XEN_API:
   16.52 +        xstype = int(server.xenapi.XSPolicy.get_xstype())
   16.53 +        display_security_subsystems(xstype)
   16.54 +
   16.55 +        policystate = server.xenapi.XSPolicy.get_xspolicy()
   16.56 +        if int(policystate['type']) == 0:
   16.57 +            print "No policy is installed."
   16.58 +            return
   16.59 +        if int(policystate['type']) != xsconstants.XS_POLICY_ACM:
   16.60 +            print "Unknown policy type '%s'." % policystate['type']
   16.61 +        else:
   16.62 +            xml = policystate['repr']
   16.63 +            acmpol = None
   16.64 +            if xml:
   16.65 +                acmpol = ACMPolicy(xml=xml)
   16.66 +
   16.67 +            display_policy_info(acmpol,
   16.68 +                                xsconstants.ACM_POLICY_ID,
   16.69 +                                policystate['xs_ref'],
   16.70 +                                policystate['version'],
   16.71 +                                int(policystate['flags']),
   16.72 +                                dumpxml,
   16.73 +                                xml)
   16.74      else:
   16.75 -        xml = policystate['repr']
   16.76 +        xstype = server.xend.security.get_xstype()
   16.77 +        display_security_subsystems(xstype)
   16.78 +
   16.79 +        xml, flags = server.xend.security.get_policy()
   16.80          acmpol = None
   16.81 -        if xml:
   16.82 -            acmpol = ACMPolicy(xml=xml)
   16.83 -        print "Policy installed on the system:"
   16.84 +        if xml != "":
   16.85 +            dom = None
   16.86 +            try:
   16.87 +                dom = minidom.parseString(xml)
   16.88 +                if dom:
   16.89 +                    acmpol = ACMPolicy(dom=dom)
   16.90 +            except Exception, e:
   16.91 +                print "Error parsing the library: " + str(e)
   16.92 +
   16.93          if acmpol:
   16.94 -            print "Policy name           : %s" % acmpol.get_name()
   16.95 -        print "Policy type           : %s" % xsconstants.ACM_POLICY_ID
   16.96 -        print "Reference             : %s" % policystate['xs_ref']
   16.97 -        print "Version of XML policy : %s" % policystate['version']
   16.98 -        state = []
   16.99 -        flags = int(policystate['flags'])
  16.100 -        if flags & xsconstants.XS_INST_LOAD:
  16.101 -            state.append("loaded")
  16.102 -        if flags & xsconstants.XS_INST_BOOT:
  16.103 -            state.append("system booted with")
  16.104 -        print "State of the policy   : %s" % ", ".join(state)
  16.105 -        if dumpxml:
  16.106 -            xml = policystate['repr']
  16.107 -            if xml:
  16.108 -                dom = minidom.parseString(xml.encode("utf-8"))
  16.109 -                print "%s" % dom.toprettyxml(indent="   ",newl="\n")
  16.110 +            display_policy_info(acmpol,
  16.111 +                                xsconstants.ACM_POLICY_ID,
  16.112 +                                None,
  16.113 +                                acmpol.get_version(),
  16.114 +                                flags,
  16.115 +                                dumpxml,
  16.116 +                                xml)
  16.117 +        else:
  16.118 +            print "No policy is installed."
  16.119  
  16.120  def main(argv):
  16.121      dumpxml = False
    17.1 --- a/tools/python/xen/xm/labels.py	Tue Dec 04 22:54:58 2007 +0000
    17.2 +++ b/tools/python/xen/xm/labels.py	Wed Dec 05 09:44:20 2007 +0000
    17.3 @@ -20,9 +20,7 @@
    17.4  """
    17.5  import sys
    17.6  import traceback
    17.7 -import string
    17.8 -from xen.util.xsm.xsm import XSMError, err, list_labels, active_policy
    17.9 -from xen.util.xsm.xsm import vm_label_re, res_label_re, all_label_re
   17.10 +from xen.util.xsm.xsm import XSMError, err
   17.11  from xen.xm.opts import OptionError
   17.12  from xen.util.acmpolicy import ACMPolicy
   17.13  from xen.util import xsconstants
   17.14 @@ -58,32 +56,12 @@ def main(argv):
   17.15          labels_xapi(policy, ptype)
   17.16  
   17.17  def labels(policy, ptype):
   17.18 -    if not policy:
   17.19 -        policy = active_policy
   17.20 -        if active_policy in ['NULL', 'INACTIVE', 'DEFAULT']:
   17.21 -            raise OptionError('No policy active, you must specify a <policy>')
   17.22 -        if active_policy in ['INACCESSIBLE']:
   17.23 -            raise OptionError('Cannot access the policy. Try as root.')
   17.24  
   17.25 -    if not ptype or ptype == 'dom':
   17.26 -        condition = vm_label_re
   17.27 -    elif ptype == 'res':
   17.28 -        condition = res_label_re
   17.29 -    elif ptype == 'any':
   17.30 -        condition = all_label_re
   17.31 -    else:
   17.32 -        err("Unknown label type \'" + ptype + "\'")
   17.33 +    labels = server.xend.security.list_labels(policy, ptype)
   17.34 +    labels.sort()
   17.35 +    for label in labels:
   17.36 +        print label
   17.37  
   17.38 -    try:
   17.39 -        labels = list_labels(policy, condition)
   17.40 -        labels.sort()
   17.41 -        for label in labels:
   17.42 -            print label
   17.43 -
   17.44 -    except XSMError:
   17.45 -        sys.exit(-1)
   17.46 -    except:
   17.47 -        traceback.print_exc(limit = 1)
   17.48  
   17.49  def labels_xapi(policy, ptype):
   17.50      policystate = server.xenapi.XSPolicy.get_xspolicy()
    18.1 --- a/tools/python/xen/xm/loadpolicy.py	Tue Dec 04 22:54:58 2007 +0000
    18.2 +++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
    18.3 @@ -1,70 +0,0 @@
    18.4 -#============================================================================
    18.5 -# This library is free software; you can redistribute it and/or
    18.6 -# modify it under the terms of version 2.1 of the GNU Lesser General Public
    18.7 -# License as published by the Free Software Foundation.
    18.8 -#
    18.9 -# This library is distributed in the hope that it will be useful,
   18.10 -# but WITHOUT ANY WARRANTY; without even the implied warranty of
   18.11 -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   18.12 -# Lesser General Public License for more details.
   18.13 -#
   18.14 -# You should have received a copy of the GNU Lesser General Public
   18.15 -# License along with this library; if not, write to the Free Software
   18.16 -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   18.17 -#============================================================================
   18.18 -# Copyright (C) 2006 International Business Machines Corp.
   18.19 -# Author: Reiner Sailer <sailer@us.ibm.com>
   18.20 -#============================================================================
   18.21 -
   18.22 -"""Loading a compiled binary policy into the hypervisor.
   18.23 -"""
   18.24 -import sys
   18.25 -import traceback
   18.26 -from xen.util.xsm.xsm import XSMError, err, load_policy
   18.27 -from xen.xm.opts import OptionError
   18.28 -from xen.xm import main as xm_main
   18.29 -from xen.util import xsconstants
   18.30 -from xen.xm.activatepolicy import activate_policy
   18.31 -from xen.xm.main import server
   18.32 -from xen.util.acmpolicy import ACMPolicy
   18.33 -
   18.34 -def help():
   18.35 -    return """Load the compiled binary (.bin) policy into the running
   18.36 -    hypervisor."""
   18.37 -
   18.38 -def main(argv):
   18.39 -    if len(argv) != 2:
   18.40 -        raise OptionError('No policy defined')
   18.41 -    if xm_main.serverType == xm_main.SERVER_XEN_API:
   18.42 -        policy = argv[1]
   18.43 -        print "This command is deprecated for use with Xen-API " \
   18.44 -              "configuration. Consider using\n'xm activatepolicy'."
   18.45 -        policystate = server.xenapi.XSPolicy.get_xspolicy()
   18.46 -        if int(policystate['type']) == 0:
   18.47 -            print "No policy is installed."
   18.48 -            return
   18.49 -
   18.50 -        if int(policystate['type']) != xsconstants.XS_POLICY_ACM:
   18.51 -            print "Unknown policy type '%s'." % policystate['type']
   18.52 -            return
   18.53 -        else:
   18.54 -            xml = policystate['repr']
   18.55 -            xs_ref = policystate['xs_ref']
   18.56 -            if not xml:
   18.57 -                OptionError("No policy installed on system?")
   18.58 -            acmpol = ACMPolicy(xml=xml)
   18.59 -            if acmpol.get_name() != policy:
   18.60 -                OptionError("Policy installed on system '%s' does not match"\
   18.61 -                            " the request policy '%s'" % \
   18.62 -                            (acmpol.get_name(), policy))
   18.63 -            activate_policy(xsconstants.XS_INST_LOAD)
   18.64 -    else:
   18.65 -        load_policy(argv[1])
   18.66 -
   18.67 -if __name__ == '__main__':
   18.68 -    try:
   18.69 -        main(sys.argv)
   18.70 -    except Exception, e:
   18.71 -        sys.stderr.write('Error: %s\n' % str(e))
   18.72 -        sys.exit(-1)
   18.73 -        
    19.1 --- a/tools/python/xen/xm/main.py	Tue Dec 04 22:54:58 2007 +0000
    19.2 +++ b/tools/python/xen/xm/main.py	Wed Dec 05 09:44:20 2007 +0000
    19.3 @@ -187,16 +187,12 @@ SUBCOMMAND_HELP = {
    19.4      'dry-run'       :  ('<ConfigFile>',
    19.5                          'Test if a domain can access its resources.'),
    19.6      'resources'     :  ('', 'Show info for each labeled resource.'),
    19.7 -    'cfgbootpolicy' :  ('<policy> [boot-title]',
    19.8 -                        'Add policy to boot configuration.'),
    19.9      'dumppolicy'    :  ('', 'Print hypervisor ACM state information.'),
   19.10 -    'loadpolicy'    :  ('<policy.bin>', 'Load binary policy into hypervisor.'),
   19.11 -    'makepolicy'    :  ('<policy>', 'Build policy and create .bin/.map '
   19.12 -                        'files.'),
   19.13      'setpolicy'     :  ('<policytype> <policyfile> [options]',
   19.14                          'Set the policy of the system.'),
   19.15 +    'resetpolicy'   :  ('',
   19.16 +                        'Set the policy of the system to the default policy.'),
   19.17      'getpolicy'     :  ('[options]', 'Get the policy of the system.'),
   19.18 -    'activatepolicy':  ('[options]', 'Activate the xend-managed policy.'),
   19.19      'labels'        :  ('[policy] [type=dom|res|any]',
   19.20                          'List <type> labels for (active) policy.'),
   19.21      'serve'         :  ('', 'Proxy Xend XMLRPC over stdio.'),
   19.22 @@ -350,12 +346,9 @@ acm_commands = [
   19.23      "getlabel",
   19.24      "dry-run",
   19.25      "resources",
   19.26 -    "makepolicy",
   19.27 -    "loadpolicy",
   19.28 -    "cfgbootpolicy",
   19.29      "dumppolicy",
   19.30 -    "activatepolicy",
   19.31      "setpolicy",
   19.32 +    "resetpolicy",
   19.33      "getpolicy",
   19.34      ]
   19.35  
   19.36 @@ -942,18 +935,13 @@ def xm_label_list(doms):
   19.37      format = '%(name)-40s %(domid)5s %(mem)5d %(vcpus)5d %(state)10s ' \
   19.38               '%(cpu_time)8.1f %(seclabel)10s'
   19.39  
   19.40 -    import xen.util.xsm.xsm as security
   19.41 -        
   19.42      for dom in doms:
   19.43          d = parse_doms_info(dom)
   19.44 -        if security.active_policy not in ['INACTIVE', 'NULL', 'DEFAULT']:
   19.45 -            if not d['seclabel']:
   19.46 -                d['seclabel'] = ACM_LABEL_UNLABELED_DISPLAY
   19.47 -        elif security.active_policy in ['DEFAULT']:
   19.48 -            d['seclabel'] = 'DEFAULT'
   19.49 -        else:
   19.50 -            d['seclabel'] = 'INACTIVE'
   19.51 -
   19.52 +        if d['seclabel'] == "" and serverType != SERVER_XEN_API:
   19.53 +            seclab = server.xend.security.get_domain_label(d['name'])
   19.54 +            if len(seclab) > 0 and seclab[0] == '\'':
   19.55 +                seclab = seclab[1:]
   19.56 +            d['seclabel'] = seclab
   19.57          output.append((format % d, d['seclabel']))
   19.58          
   19.59      #sort by labels
   19.60 @@ -2471,9 +2459,6 @@ IMPORTED_COMMANDS = [
   19.61      'new',    
   19.62      'migrate',
   19.63      'labels',
   19.64 -    'cfgbootpolicy',
   19.65 -    'makepolicy',
   19.66 -    'loadpolicy',
   19.67      'dumppolicy',        
   19.68      'addlabel',
   19.69      'rmlabel',
   19.70 @@ -2482,7 +2467,7 @@ IMPORTED_COMMANDS = [
   19.71      'resources',
   19.72      'getpolicy',
   19.73      'setpolicy',
   19.74 -    'activatepolicy',
   19.75 +    'resetpolicy',
   19.76      ]
   19.77  
   19.78  for c in IMPORTED_COMMANDS:
    20.1 --- a/tools/python/xen/xm/makepolicy.py	Tue Dec 04 22:54:58 2007 +0000
    20.2 +++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
    20.3 @@ -1,51 +0,0 @@
    20.4 -#============================================================================
    20.5 -# This library is free software; you can redistribute it and/or
    20.6 -# modify it under the terms of version 2.1 of the GNU Lesser General Public
    20.7 -# License as published by the Free Software Foundation.
    20.8 -#
    20.9 -# This library is distributed in the hope that it will be useful,
   20.10 -# but WITHOUT ANY WARRANTY; without even the implied warranty of
   20.11 -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   20.12 -# Lesser General Public License for more details.
   20.13 -#
   20.14 -# You should have received a copy of the GNU Lesser General Public
   20.15 -# License along with this library; if not, write to the Free Software
   20.16 -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   20.17 -#============================================================================
   20.18 -# Copyright (C) 2006 International Business Machines Corp.
   20.19 -# Author: Reiner Sailer <sailer@us.ibm.com>
   20.20 -#============================================================================
   20.21 -"""Compiling a XML source policy file into mapping and binary versions.
   20.22 -"""
   20.23 -import sys
   20.24 -import traceback
   20.25 -from xen.util.xsm.xsm import ACMError, err, make_policy
   20.26 -from xen.util import xsconstants
   20.27 -from xen.xm.opts import OptionError
   20.28 -from xen.xm import main as xm_main
   20.29 -from xen.xm.setpolicy import setpolicy
   20.30 -
   20.31 -def usage():
   20.32 -    print "\nUsage: xm makepolicy <policy>\n"
   20.33 -    print " Translate an XML source policy and create"
   20.34 -    print " mapping file and binary policy.\n"
   20.35 -    err("Usage")
   20.36 -
   20.37 -
   20.38 -def main(argv):
   20.39 -    if len(argv) != 2:
   20.40 -        raise OptionError('No XML policy file specified')
   20.41 -    if xm_main.serverType == xm_main.SERVER_XEN_API:
   20.42 -        print "This command is deprecated for use with Xen-API " \
   20.43 -              "configuration. Consider using\n'xm setpolicy'."
   20.44 -        setpolicy(xsconstants.ACM_POLICY_ID, argv[1],
   20.45 -                  xsconstants.XS_INST_LOAD, True)
   20.46 -    else:
   20.47 -        make_policy(argv[1])
   20.48 -
   20.49 -if __name__ == '__main__':
   20.50 -    try:
   20.51 -        main(sys.argv)
   20.52 -    except Exception, e:
   20.53 -        sys.stderr.write('Error: %s\n' % str(e))
   20.54 -        sys.exit(-1)
    21.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    21.2 +++ b/tools/python/xen/xm/resetpolicy.py	Wed Dec 05 09:44:20 2007 +0000
    21.3 @@ -0,0 +1,162 @@
    21.4 +#============================================================================
    21.5 +# This library is free software; you can redistribute it and/or
    21.6 +# modify it under the terms of version 2.1 of the GNU Lesser General Public
    21.7 +# License as published by the Free Software Foundation.
    21.8 +#
    21.9 +# This library is distributed in the hope that it will be useful,
   21.10 +# but WITHOUT ANY WARRANTY; without even the implied warranty of
   21.11 +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   21.12 +# Lesser General Public License for more details.
   21.13 +#
   21.14 +# You should have received a copy of the GNU Lesser General Public
   21.15 +# License along with this library; if not, write to the Free Software
   21.16 +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   21.17 +#============================================================================
   21.18 +# Copyright (C) 2007 International Business Machines Corp.
   21.19 +# Author: Stefan Berger <stefanb@us.ibm.com>
   21.20 +#============================================================================
   21.21 +""" Reset the system's current policy to the default state.
   21.22 +"""
   21.23 +import sys
   21.24 +import xen.util.xsm.xsm as security
   21.25 +from xen.util.xsm.xsm import XSMError
   21.26 +from xen.xm.opts import OptionError
   21.27 +from xen.xm import main as xm_main
   21.28 +from xen.xm.main import server
   21.29 +from xen.util import xsconstants
   21.30 +from xen.util.acmpolicy import ACMPolicy
   21.31 +
   21.32 +DOM0_UUID = "00000000-0000-0000-0000-000000000000"
   21.33 +
   21.34 +DEFAULT_policy_template = \
   21.35 +"<?xml version=\"1.0\" ?>" +\
   21.36 +"<SecurityPolicyDefinition xmlns=\"http://www.ibm.com\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.ibm.com ../../security_policy.xsd\">" +\
   21.37 +"  <PolicyHeader>" +\
   21.38 +"    <PolicyName>DEFAULT</PolicyName>" +\
   21.39 +"    <Version>1.0</Version>" +\
   21.40 +"  </PolicyHeader>" +\
   21.41 +"  <SimpleTypeEnforcement>" +\
   21.42 +"    <SimpleTypeEnforcementTypes>" +\
   21.43 +"      <Type>SystemManagement</Type>" +\
   21.44 +"    </SimpleTypeEnforcementTypes>" +\
   21.45 +"  </SimpleTypeEnforcement>" +\
   21.46 +"  <ChineseWall>" +\
   21.47 +"    <ChineseWallTypes>" +\
   21.48 +"      <Type>SystemManagement</Type>" +\
   21.49 +"    </ChineseWallTypes>" +\
   21.50 +"  </ChineseWall>" +\
   21.51 +"  <SecurityLabelTemplate>" +\
   21.52 +"    <SubjectLabels bootstrap=\"SystemManagement\">" +\
   21.53 +"      <VirtualMachineLabel>" +\
   21.54 +"        <Name%s>SystemManagement</Name>" +\
   21.55 +"        <SimpleTypeEnforcementTypes>" +\
   21.56 +"          <Type>SystemManagement</Type>" +\
   21.57 +"        </SimpleTypeEnforcementTypes>" +\
   21.58 +"        <ChineseWallTypes>" +\
   21.59 +"          <Type/>" +\
   21.60 +"        </ChineseWallTypes>" +\
   21.61 +"      </VirtualMachineLabel>" +\
   21.62 +"    </SubjectLabels>" +\
   21.63 +"  </SecurityLabelTemplate>" +\
   21.64 +"</SecurityPolicyDefinition>"
   21.65 +
   21.66 +
   21.67 +def help():
   21.68 +    return """
   21.69 +    Reset the system's policy to the default.
   21.70 +
   21.71 +    When the system's policy is reset, all guest VMs should be halted,
   21.72 +    since otherwise this operation will fail.
   21.73 +    """
   21.74 +
   21.75 +def get_reset_policy_xml(dom0_seclab):
   21.76 +    if dom0_seclab == "":
   21.77 +        return DEFAULT_policy_template % ""
   21.78 +    else:
   21.79 +        poltyp, policy, label = dom0_seclab.split(":")
   21.80 +        if label != "SystemManagement":
   21.81 +            return DEFAULT_policy_template % \
   21.82 +                   (" from=\"%s\"" % label)
   21.83 +        else:
   21.84 +            return DEFAULT_policy_template % ""
   21.85 +
   21.86 +def resetpolicy():
   21.87 +    msg = None
   21.88 +    xs_type = xsconstants.XS_POLICY_ACM
   21.89 +    flags = xsconstants.XS_INST_LOAD
   21.90 +
   21.91 +    if xm_main.serverType == xm_main.SERVER_XEN_API:
   21.92 +        if int(server.xenapi.XSPolicy.get_xstype()) & xs_type == 0:
   21.93 +            raise security.XSMError("ACM policy type not supported.")
   21.94 +
   21.95 +        policystate = server.xenapi.XSPolicy.get_xspolicy()
   21.96 +
   21.97 +        acmpol = ACMPolicy(xml=policystate['repr'])
   21.98 +
   21.99 +        now_flags = int(policystate['flags'])
  21.100 +
  21.101 +        if now_flags & xsconstants.XS_INST_BOOT == 0 and \
  21.102 +           not acmpol.is_default_policy():
  21.103 +            msg = "Old policy not found in bootloader file."
  21.104 +
  21.105 +        seclab = server.xenapi.VM.get_security_label(DOM0_UUID)
  21.106 +        xml = get_reset_policy_xml(seclab)
  21.107 +        try:
  21.108 +            policystate = server.xenapi.XSPolicy.set_xspolicy(xs_type,
  21.109 +                                                              xml,
  21.110 +                                                              flags,
  21.111 +                                                              True)
  21.112 +        except Exception, e:
  21.113 +            raise security.XSMError("An error occurred resetting the "
  21.114 +                                    "policy: %s" % str(e))
  21.115 +
  21.116 +        xserr = int(policystate['xserr'])
  21.117 +        if xserr != xsconstants.XSERR_SUCCESS:
  21.118 +            raise security.XSMError("Could not reset the system's policy. "
  21.119 +                                    "Try to halt all guests.")
  21.120 +        else:
  21.121 +            print "Successfully reset the system's policy."
  21.122 +            if msg:
  21.123 +                print msg
  21.124 +    else:
  21.125 +        if server.xend.security.get_xstype() & xs_type == 0:
  21.126 +           raise security.XSMError("ACM policy type not supported.")
  21.127 +
  21.128 +        xml, now_flags = server.xend.security.get_policy()
  21.129 +
  21.130 +        acmpol = ACMPolicy(xml=xml)
  21.131 +
  21.132 +        if int(now_flags) & xsconstants.XS_INST_BOOT == 0 and \
  21.133 +           not acmpol.is_default_policy():
  21.134 +            msg = "Old policy not found in bootloader file."
  21.135 +
  21.136 +        seclab = server.xend.security.get_domain_label(0)
  21.137 +        if seclab[0] == '\'':
  21.138 +            seclab =  seclab[1:]
  21.139 +        xml = get_reset_policy_xml(seclab)
  21.140 +        rc, errors = server.xend.security.set_policy(xs_type,
  21.141 +                                                     xml,
  21.142 +                                                     flags,
  21.143 +                                                     True)
  21.144 +        if rc != xsconstants.XSERR_SUCCESS:
  21.145 +            raise security.XSMError("Could not reset the system's policy. "
  21.146 +                                    "Try to halt all guests.")
  21.147 +        else:
  21.148 +            print "Successfully reset the system's policy."
  21.149 +            if msg:
  21.150 +                print msg
  21.151 +
  21.152 +
  21.153 +def main(argv):
  21.154 +    if len(argv) != 1:
  21.155 +        raise OptionError("No arguments expected.")
  21.156 +
  21.157 +    resetpolicy()
  21.158 +
  21.159 +
  21.160 +if __name__ == '__main__':
  21.161 +    try:
  21.162 +        main(sys.argv)
  21.163 +    except Exception, e:
  21.164 +        sys.stderr.write('Error: %s\n' % str(e))
  21.165 +        sys.exit(-1)
    22.1 --- a/tools/python/xen/xm/resources.py	Tue Dec 04 22:54:58 2007 +0000
    22.2 +++ b/tools/python/xen/xm/resources.py	Wed Dec 05 09:44:20 2007 +0000
    22.3 @@ -19,8 +19,6 @@
    22.4  """List the resource label information from the global resource label file
    22.5  """
    22.6  import sys
    22.7 -from xen.util import dictio
    22.8 -import xen.util.xsm.xsm as security
    22.9  from xen.util import xsconstants
   22.10  from xen.xm.opts import OptionError
   22.11  from xen.xm import main as xm_main
   22.12 @@ -55,11 +53,7 @@ def main (argv):
   22.13          for key, value in access_control.items():
   22.14              access_control[key] = tuple(value.split(':'))
   22.15      else:
   22.16 -        try:
   22.17 -            filename = security.res_label_filename
   22.18 -            access_control = dictio.dict_read("resources", filename)
   22.19 -        except:
   22.20 -            raise OptionError("Resource file not found")
   22.21 +        access_control = server.xend.security.get_labeled_resources()
   22.22  
   22.23      print_resource_data(access_control)
   22.24  
    23.1 --- a/tools/python/xen/xm/rmlabel.py	Tue Dec 04 22:54:58 2007 +0000
    23.2 +++ b/tools/python/xen/xm/rmlabel.py	Wed Dec 05 09:44:20 2007 +0000
    23.3 @@ -18,9 +18,12 @@
    23.4  
    23.5  """Remove a label from a domain configuration file or a resoruce.
    23.6  """
    23.7 -import sys, os, re
    23.8 -from xen.util import dictio
    23.9 +import os
   23.10 +import re
   23.11 +import sys
   23.12  import xen.util.xsm.xsm as security
   23.13 +from xen.util import xsconstants
   23.14 +from xen.util.acmpolicy import ACM_LABEL_UNLABELED
   23.15  from xen.xm.opts import OptionError
   23.16  from xen.xm import main as xm_main
   23.17  from xen.xm.main import server
   23.18 @@ -33,10 +36,11 @@ def help():
   23.19               xm rmlabel vif-<idx> <domain name>
   23.20  
   23.21      This program removes an acm_label entry from the 'configfile'
   23.22 -    for a domain, from a Xend-managed domain, from the global resource label
   23.23 -    file for a resource or from the virtual network interface of a Xend-managed
   23.24 -    domain. If the label does not exist for the given domain or resource, then
   23.25 -    rmlabel fails."""
   23.26 +    for a domain, the label from a Xend-managed domain or a resources
   23.27 +    or from the network interface of a Xend-managed domain (requires
   23.28 +    xm to be used in Xen-API mode). If the label does not exist for
   23.29 +    the given domain or resource, then rmlabel fails and reports an error.
   23.30 +    """
   23.31  
   23.32  
   23.33  def rm_resource_label(resource):
   23.34 @@ -55,24 +59,19 @@ def rm_resource_label(resource):
   23.35              raise security.XSMError("Could not remove label "
   23.36                                      "from resource: %s" % e)
   23.37          return
   23.38 -
   23.39 -    #build canonical resource name
   23.40 -    resource = security.unify_resname(resource)
   23.41 -
   23.42 -    # read in the resource file
   23.43 -    fil = security.res_label_filename
   23.44 -    try:
   23.45 -        access_control = dictio.dict_read("resources", fil)
   23.46 -    except:
   23.47 -        raise security.ACMError("Resource file not found, cannot remove label!")
   23.48 -
   23.49 -    # remove the entry and update file
   23.50 -    if access_control.has_key(resource):
   23.51 -        del access_control[resource]
   23.52 -        dictio.dict_write(access_control, "resources", fil)
   23.53      else:
   23.54 -        raise security.ACMError("Resource not labeled")
   23.55 -
   23.56 +        oldlabel = server.xend.security.get_resource_label(resource)
   23.57 +        if len(oldlabel) != 0:
   23.58 +            rc = server.xend.security.set_resource_label(resource,
   23.59 +                                                         "",
   23.60 +                                                         "",
   23.61 +                                                         "")
   23.62 +            if rc != xsconstants.XSERR_SUCCESS:
   23.63 +                raise security.XSMError("An error occurred removing the "
   23.64 +                                        "label: %s" % \
   23.65 +                                        xsconstants.xserr2string(-rc))
   23.66 +        else:
   23.67 +            raise security.XSMError("Resource not labeled")
   23.68  
   23.69  def rm_domain_label(configfile):
   23.70      # open the domain config file
   23.71 @@ -116,20 +115,43 @@ def rm_domain_label(configfile):
   23.72      fd.writelines(file_contents)
   23.73      fd.close()
   23.74  
   23.75 -def rm_domain_label_xapi(domainname):
   23.76 +def rm_domain_label_xapi(domain):
   23.77      if xm_main.serverType != xm_main.SERVER_XEN_API:
   23.78 -        raise OptionError('Need to be configure for using xen-api.')
   23.79 -    uuids = server.xenapi.VM.get_by_name_label(domainname)
   23.80 -    if len(uuids) == 0:
   23.81 -        raise OptionError('A VM with that name does not exist.')
   23.82 -    if len(uuids) != 1:
   23.83 -        raise OptionError('Too many domains with the same name.')
   23.84 -    uuid = uuids[0]
   23.85 -    try:
   23.86 -        old_lab = server.xenapi.VM.get_security_label(uuid)
   23.87 -        server.xenapi.VM.set_security_label(uuid, "", old_lab)
   23.88 -    except Exception, e:
   23.89 -        raise security.XSMError('Could not remove label from domain: %s' % e)
   23.90 +        old_lab = server.xend.security.get_domain_label(domain)
   23.91 +
   23.92 +        vmlabel = ""
   23.93 +        if old_lab != "":
   23.94 +            tmp = old_lab.split(":")
   23.95 +            if len(tmp) == 3:
   23.96 +                vmlabel = tmp[2]
   23.97 +
   23.98 +        if old_lab != "" and  vmlabel != ACM_LABEL_UNLABELED:
   23.99 +            server.xend.security.set_domain_label(domain, "", old_lab)
  23.100 +            print "Successfully removed label from domain %s." % domain
  23.101 +        else:
  23.102 +            raise security.XSMError("Domain was not labeled.")
  23.103 +    else:
  23.104 +        uuids = server.xenapi.VM.get_by_name_label(domain)
  23.105 +        if len(uuids) == 0:
  23.106 +            raise OptionError('A VM with that name does not exist.')
  23.107 +        if len(uuids) != 1:
  23.108 +            raise OptionError('Too many domains with the same name.')
  23.109 +        uuid = uuids[0]
  23.110 +        try:
  23.111 +            old_lab = server.xenapi.VM.get_security_label(uuid)
  23.112 +
  23.113 +            vmlabel = ""
  23.114 +            if old_lab != "":
  23.115 +                tmp = old_lab.split(":")
  23.116 +                if len(tmp) == 3:
  23.117 +                    vmlabel = tmp[2]
  23.118 +
  23.119 +            if old_lab != "":
  23.120 +                server.xenapi.VM.set_security_label(uuid, "", old_lab)
  23.121 +            else:
  23.122 +                raise security.XSMError("Domain was not labeled.")
  23.123 +        except Exception, e:
  23.124 +            raise security.XSMError('Could not remove label from domain: %s' % e)
  23.125  
  23.126  def rm_vif_label(vmname, idx):
  23.127      if xm_main.serverType != xm_main.SERVER_XEN_API:
    24.1 --- a/tools/python/xen/xm/setpolicy.py	Tue Dec 04 22:54:58 2007 +0000
    24.2 +++ b/tools/python/xen/xm/setpolicy.py	Wed Dec 05 09:44:20 2007 +0000
    24.3 @@ -19,106 +19,128 @@
    24.4  """Get the managed policy of the system.
    24.5  """
    24.6  
    24.7 +import os
    24.8 +import sys
    24.9  import base64
   24.10  import struct
   24.11 -import sys
   24.12 -import string
   24.13  import xen.util.xsm.xsm as security
   24.14  from xen.util import xsconstants
   24.15 -from xen.util.acmpolicy import ACMPolicy
   24.16 +from xen.util.acmpolicy import ACMPolicy, \
   24.17 +   ACM_EVTCHN_SHARING_VIOLATION,\
   24.18 +   ACM_GNTTAB_SHARING_VIOLATION, \
   24.19 +   ACM_DOMAIN_LOOKUP,   \
   24.20 +   ACM_CHWALL_CONFLICT, \
   24.21 +   ACM_SSIDREF_IN_USE
   24.22  from xen.xm.opts import OptionError
   24.23  from xen.util.xsm.acm.acm import policy_dir_prefix
   24.24  from xen.xm import main as xm_main
   24.25 +from xen.xm.getpolicy import getpolicy
   24.26  from xen.xm.main import server
   24.27  
   24.28  def help():
   24.29      return """
   24.30 -    Usage: xm setpolicy <policytype> <policy> [options]
   24.31 +    Usage: xm setpolicy <policytype> <policyname>
   24.32  
   24.33      Set the policy managed by xend.
   24.34  
   24.35      The only policytype that is currently supported is 'ACM'.
   24.36  
   24.37 -    The following options are defined
   24.38 -      --load     Load the policy immediately
   24.39 -      --boot     Have the system load the policy during boot
   24.40 -      --update   Automatically adapt the policy so that it will be
   24.41 -                 treated as an update to the current policy
   24.42 +    The filename of the policy is the policy name plus the suffic
   24.43 +    '-security_policy.xml'. The location of the policy file is either
   24.44 +    the the current directory or '/etc/xen/acm-security/policies'.
   24.45 +
   24.46      """
   24.47  
   24.48 -def create_update_xml(xml):
   24.49 -    """
   24.50 -        Adapt the new policy's xml header to be a simple type of an
   24.51 -        update to the currently enforce policy on the remote system.
   24.52 -        Increases the minor number by '1'.
   24.53 +def build_hv_error_message(errors):
   24.54      """
   24.55 -    policystate = server.xenapi.XSPolicy.get_xspolicy()
   24.56 -    if int(policystate['type']) == 0:
   24.57 -        return xml
   24.58 -    curpol = ACMPolicy(xml = policystate['repr'])
   24.59 -    curpol_version = curpol.get_version()
   24.60 -    tmp = curpol_version.split('.')
   24.61 -    if len(tmp) == 2:
   24.62 -        maj = int(tmp[0])
   24.63 -        min = int(tmp[1])
   24.64 -    else:
   24.65 -        maj = int(tmp)
   24.66 -        min = 0
   24.67 -    min += 1
   24.68 -    newpol_version = ""+str(maj)+"."+str(min)
   24.69 +       Build a message from the error codes return by the hypervisor.
   24.70 +    """
   24.71 +    txt = "Hypervisor reported errors:"
   24.72 +    i = 0
   24.73 +    while i + 7 < len(errors):
   24.74 +        code, data = struct.unpack("!ii", errors[i:i+8])
   24.75 +        err_msgs  = {
   24.76 +            ACM_EVTCHN_SHARING_VIOLATION : \
   24.77 +                    ["event channel sharing violation between domains",2],
   24.78 +            ACM_GNTTAB_SHARING_VIOLATION : \
   24.79 +                    ["grant table sharing violation between domains",2],
   24.80 +            ACM_DOMAIN_LOOKUP : \
   24.81 +                    ["domain lookup",1],
   24.82 +            ACM_CHWALL_CONFLICT : \
   24.83 +                    ["Chinese Wall conflict between domains",2],
   24.84 +            ACM_SSIDREF_IN_USE : \
   24.85 +                    ["A domain used SSIDREF",1],
   24.86 +        }
   24.87 +        num = err_msgs[code][1]
   24.88 +        if num == 1:
   24.89 +            txt += "%s %d" % (err_msgs[code][0], data)
   24.90 +        else:
   24.91 +            txt += "%s %d and %d" % (err_msgs[code][0],
   24.92 +                                     data >> 16 , data & 0xffff)
   24.93 +        i += 8
   24.94 +    return txt
   24.95  
   24.96 -    newpol = ACMPolicy(xml = xml)
   24.97 -    newpol.set_frompolicy_name(curpol.get_name())
   24.98 -    newpol.set_frompolicy_version(curpol.get_version())
   24.99 -    newpol.set_policy_version(newpol_version)
  24.100 -    return newpol.toxml()
  24.101  
  24.102 -def setpolicy(policytype, policy_name, flags, overwrite, is_update=False):
  24.103 -    if xm_main.serverType != xm_main.SERVER_XEN_API:
  24.104 -        raise OptionError('xm needs to be configured to use the xen-api.')
  24.105 -    if policytype != xsconstants.ACM_POLICY_ID:
  24.106 -        raise OptionError("Unsupported policytype '%s'." % policytype)
  24.107 -    else:
  24.108 +def setpolicy(policytype, policy_name, flags, overwrite):
  24.109 +
  24.110 +    if policytype.upper() == xsconstants.ACM_POLICY_ID:
  24.111          xs_type = xsconstants.XS_POLICY_ACM
  24.112  
  24.113 -        policy_file = policy_dir_prefix + "/" + \
  24.114 -                      string.join(string.split(policy_name, "."), "/")
  24.115 -        policy_file += "-security_policy.xml"
  24.116 +        for prefix in [ './', policy_dir_prefix+"/" ]:
  24.117 +            policy_file = prefix + "/".join(policy_name.split(".")) + \
  24.118 +                          "-security_policy.xml"
  24.119 +
  24.120 +            if os.path.exists(policy_file):
  24.121 +                break
  24.122  
  24.123          try:
  24.124              f = open(policy_file,"r")
  24.125 -            xml = f.read(-1)
  24.126 +            xml = f.read()
  24.127              f.close()
  24.128          except:
  24.129 -            raise OptionError("Not a valid policy file")
  24.130 -
  24.131 -        if is_update:
  24.132 -            xml = create_update_xml(xml)
  24.133 +            raise OptionError("Could not read policy file from current"
  24.134 +                              " directory or '%s'." % policy_dir_prefix)
  24.135  
  24.136 -        try:
  24.137 -            policystate = server.xenapi.XSPolicy.set_xspolicy(xs_type,
  24.138 -                                                              xml,
  24.139 -                                                              flags,
  24.140 -                                                              overwrite)
  24.141 -        except Exception, e:
  24.142 -            raise security.XSMError("An error occurred setting the "
  24.143 -                                    "policy: %s" % str(e))
  24.144 -        xserr = int(policystate['xserr'])
  24.145 -        if xserr != 0:
  24.146 -            txt = "An error occurred trying to set the policy: %s." % \
  24.147 -                  xsconstants.xserr2string(abs(xserr))
  24.148 -            errors = policystate['errors']
  24.149 -            if len(errors) > 0:
  24.150 -                txt += "Hypervisor reported errors:"
  24.151 -                err = base64.b64decode(errors)
  24.152 -                i = 0
  24.153 -                while i + 7 < len(err):
  24.154 -                    code, data = struct.unpack("!ii", errors[i:i+8])
  24.155 -                    txt += "(0x%08x, 0x%08x)" % (code, data)
  24.156 -                    i += 8
  24.157 -            raise security.XSMError(txt)
  24.158 +        if xm_main.serverType == xm_main.SERVER_XEN_API:
  24.159 +
  24.160 +            try:
  24.161 +                policystate = server.xenapi.XSPolicy.set_xspolicy(xs_type,
  24.162 +                                                                  xml,
  24.163 +                                                                  flags,
  24.164 +                                                                  overwrite)
  24.165 +            except Exception, e:
  24.166 +                raise security.XSMError("An error occurred setting the "
  24.167 +                                        "policy: %s" % str(e))
  24.168 +            xserr = int(policystate['xserr'])
  24.169 +            if xserr != xsconstants.XSERR_SUCCESS:
  24.170 +                txt = "An error occurred trying to set the policy: %s." % \
  24.171 +                      xsconstants.xserr2string(abs(xserr))
  24.172 +                errors = policystate['errors']
  24.173 +                if len(errors) > 0:
  24.174 +                    txt += " " + build_hv_error_message(base64.b64decode(errors))
  24.175 +                raise security.XSMError(txt)
  24.176 +            else:
  24.177 +                print "Successfully set the new policy."
  24.178 +                getpolicy(False)
  24.179          else:
  24.180 -            print "Successfully set the new policy."
  24.181 +            # Non-Xen-API call.
  24.182 +
  24.183 +            rc, errors = server.xend.security.set_policy(xs_type,
  24.184 +                                                         xml,
  24.185 +                                                         flags,
  24.186 +                                                         overwrite)
  24.187 +            if rc != xsconstants.XSERR_SUCCESS:
  24.188 +                txt = "An error occurred trying to set the policy: %s." % \
  24.189 +                      xsconstants.xserr2string(abs(rc))
  24.190 +                if len(errors) > 0:
  24.191 +                    txt += " " + build_hv_error_message(
  24.192 +                                       base64.b64decode(errors))
  24.193 +                raise security.XSMError(txt)
  24.194 +            else:
  24.195 +                print "Successfully set the new policy."
  24.196 +                getpolicy(False)
  24.197 +    else:
  24.198 +        raise OptionError("Unsupported policytype '%s'." % policytype)
  24.199  
  24.200  
  24.201  def main(argv):
  24.202 @@ -131,21 +153,11 @@ def main(argv):
  24.203  
  24.204      policytype  = argv[1]
  24.205      policy_name = argv[2]
  24.206 -    is_update = False
  24.207  
  24.208 -    flags = 0
  24.209 -    if '--load' in argv:
  24.210 -        flags |= xsconstants.XS_INST_LOAD
  24.211 -    if '--boot' in argv:
  24.212 -        flags |= xsconstants.XS_INST_BOOT
  24.213 -    if '--update' in argv:
  24.214 -        is_update = True
  24.215 +    flags = xsconstants.XS_INST_LOAD | xsconstants.XS_INST_BOOT
  24.216 +    overwrite = True
  24.217  
  24.218 -    overwrite = True
  24.219 -    if '--nooverwrite' in argv:
  24.220 -        overwrite = False
  24.221 -
  24.222 -    setpolicy(policytype, policy_name, flags, overwrite, is_update)
  24.223 +    setpolicy(policytype, policy_name, flags, overwrite)
  24.224  
  24.225  if __name__ == '__main__':
  24.226      try:
    25.1 --- a/tools/security/Makefile	Tue Dec 04 22:54:58 2007 +0000
    25.2 +++ b/tools/security/Makefile	Wed Dec 05 09:44:20 2007 +0000
    25.3 @@ -15,12 +15,10 @@ LDFLAGS    += $(shell xml2-config --libs
    25.4  
    25.5  SRCS_TOOL     = secpol_tool.c
    25.6  OBJS_TOOL    := $(patsubst %.c,%.o,$(filter %.c,$(SRCS_TOOL)))
    25.7 -SRCS_XML2BIN  = secpol_xml2bin.c secpol_xml2bin.h
    25.8 -OBJS_XML2BIN := $(patsubst %.c,%.o,$(filter %.c,$(SRCS_XML2BIN)))
    25.9  
   25.10 -ACM_INST_TOOLS    = xensec_tool xensec_xml2bin xensec_gen
   25.11 +ACM_INST_TOOLS    = xensec_tool xensec_gen
   25.12  ACM_EZPOLICY      = xensec_ezpolicy
   25.13 -ACM_OBJS          = $(OBJS_TOOL) $(OBJS_XML2BIN) $(OBJS_GETD)
   25.14 +ACM_OBJS          = $(OBJS_TOOL) $(OBJS_GETD)
   25.15  ACM_SCRIPTS       = python/xensec_tools/acm_getlabel
   25.16  
   25.17  ACM_CONFIG_DIR    = /etc/xen/acm-security
   25.18 @@ -86,9 +84,6 @@ build: $(ACM_INST_TOOLS) $(ACM_NOINST_TO
   25.19  xensec_tool: $(OBJS_TOOL)
   25.20  	$(CC) -g $(CFLAGS) $(LDFLAGS) -O0 -o $@ $^ -L$(XEN_LIBXC) -lxenctrl
   25.21  
   25.22 -xensec_xml2bin: $(OBJS_XML2BIN)
   25.23 -	$(CC) -g $(CFLAGS) $(LDFLAGS) -O0 -o $@ $^
   25.24 -
   25.25  xensec_gen: xensec_gen.py
   25.26  	cp -f $^ $@
   25.27  
    26.1 --- a/tools/security/policies/example/client_v1-security_policy.xml	Tue Dec 04 22:54:58 2007 +0000
    26.2 +++ b/tools/security/policies/example/client_v1-security_policy.xml	Wed Dec 05 09:44:20 2007 +0000
    26.3 @@ -46,7 +46,7 @@
    26.4  		</ConflictSets>
    26.5  	</ChineseWall>
    26.6  	<SecurityLabelTemplate>
    26.7 -		<SubjectLabels bootstrap="dom_SystemManagement">
    26.8 +		<SubjectLabels bootstrap="SystemManagement">
    26.9  			<!-- single ste typed domains            -->
   26.10  			<!-- ACM enforces that only domains with -->
   26.11  			<!-- the same type can share information -->
   26.12 @@ -89,7 +89,7 @@
   26.13  			<!-- Domains with multiple ste types services; such domains   -->
   26.14  			<!-- must keep the types inside their domain safely confined. -->
   26.15  			<VirtualMachineLabel>
   26.16 -				<Name>dom_SystemManagement</Name>
   26.17 +				<Name>SystemManagement</Name>
   26.18  				<SimpleTypeEnforcementTypes>
   26.19  					<!-- since dom0 needs access to every domain and -->
   26.20  					<!-- resource right now ... -->
    27.1 --- a/tools/security/policies/example/ste/client_v1-security_policy.xml	Tue Dec 04 22:54:58 2007 +0000
    27.2 +++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
    27.3 @@ -1,149 +0,0 @@
    27.4 -<?xml version="1.0" encoding="UTF-8"?>
    27.5 -<!-- Author: Reiner Sailer, Ray Valdez {sailer,rvaldez}@us.ibm.com  -->
    27.6 -<!--             This file defines the security policies, which     -->
    27.7 -<!--             can be enforced by the Xen Access Control Module.  -->
    27.8 -<!--             Currently: Chinese Wall and Simple Type Enforcement-->
    27.9 -<SecurityPolicyDefinition xmlns="http://www.ibm.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.ibm.com ../../security_policy.xsd ">
   27.10 -	<PolicyHeader>
   27.11 -		<PolicyName>example.ste.client_v1</PolicyName>
   27.12 -		<PolicyUrl>www.ibm.com/example/ste/client_v1</PolicyUrl>
   27.13 -		<Date>2006-03-31</Date>
   27.14 -	</PolicyHeader>
   27.15 -	<!--                                                        -->
   27.16 -	<!-- example of a simple type enforcement policy definition -->
   27.17 -	<!--                                                        -->
   27.18 -	<SimpleTypeEnforcement>
   27.19 -		<SimpleTypeEnforcementTypes>
   27.20 -			<Type>ste_SystemManagement</Type><!-- machine/security management -->
   27.21 -			<Type>ste_PersonalFinances</Type><!-- personal finances -->
   27.22 -			<Type>ste_InternetInsecure</Type><!-- games, active X, etc. -->
   27.23 -			<Type>ste_DonatedCycles</Type><!-- donation to BOINC/seti@home -->
   27.24 -			<Type>ste_PersistentStorageA</Type><!-- domain managing the harddrive A-->
   27.25 -			<Type>ste_NetworkAdapter0</Type><!-- type of the domain managing ethernet adapter 0-->
   27.26 -		</SimpleTypeEnforcementTypes>
   27.27 -	</SimpleTypeEnforcement>
   27.28 -	<SecurityLabelTemplate>
   27.29 -		<SubjectLabels bootstrap="dom_SystemManagement">
   27.30 -			<!-- single ste typed domains            -->
   27.31 -			<!-- ACM enforces that only domains with -->
   27.32 -			<!-- the same type can share information -->
   27.33 -			<!--                                     -->
   27.34 -			<!-- Bootstrap label is assigned to Dom0 -->
   27.35 -			<VirtualMachineLabel>
   27.36 -				<Name>dom_HomeBanking</Name>
   27.37 -				<SimpleTypeEnforcementTypes>
   27.38 -					<Type>ste_PersonalFinances</Type>
   27.39 -				</SimpleTypeEnforcementTypes>
   27.40 -			</VirtualMachineLabel>
   27.41 -
   27.42 -			<VirtualMachineLabel>
   27.43 -				<Name>dom_Fun</Name>
   27.44 -				<SimpleTypeEnforcementTypes>
   27.45 -					<Type>ste_InternetInsecure</Type>
   27.46 -				</SimpleTypeEnforcementTypes>
   27.47 -			</VirtualMachineLabel>
   27.48 -
   27.49 -			<VirtualMachineLabel>
   27.50 -				<!-- donating some cycles to seti@home -->
   27.51 -				<Name>dom_BoincClient</Name>
   27.52 -				<SimpleTypeEnforcementTypes>
   27.53 -					<Type>ste_DonatedCycles</Type>
   27.54 -				</SimpleTypeEnforcementTypes>
   27.55 -			</VirtualMachineLabel>
   27.56 -
   27.57 -			<!-- Domains with multiple ste types services; such domains   -->
   27.58 -			<!-- must keep the types inside their domain safely confined. -->
   27.59 -			<VirtualMachineLabel>
   27.60 -				<Name>dom_SystemManagement</Name>
   27.61 -				<SimpleTypeEnforcementTypes>
   27.62 -					<!-- since dom0 needs access to every domain and -->
   27.63 -					<!-- resource right now ... -->
   27.64 -					<Type>ste_SystemManagement</Type>
   27.65 -					<Type>ste_PersonalFinances</Type>
   27.66 -					<Type>ste_InternetInsecure</Type>
   27.67 -					<Type>ste_DonatedCycles</Type>
   27.68 -					<Type>ste_PersistentStorageA</Type>
   27.69 -					<Type>ste_NetworkAdapter0</Type>
   27.70 -				</SimpleTypeEnforcementTypes>
   27.71 -			</VirtualMachineLabel>
   27.72 -
   27.73 -			<VirtualMachineLabel>
   27.74 -				<!-- serves persistent storage to other domains -->
   27.75 -				<Name>dom_StorageDomain</Name>
   27.76 -				<SimpleTypeEnforcementTypes>
   27.77 -					<!-- access right to the resource (hard drive a) -->
   27.78 -					<Type>ste_PersistentStorageA</Type>
   27.79 -					<!-- can serve following types -->
   27.80 -					<Type>ste_PersonalFinances</Type>
   27.81 -					<Type>ste_InternetInsecure</Type>
   27.82 -				</SimpleTypeEnforcementTypes>
   27.83 -			</VirtualMachineLabel>
   27.84 -
   27.85 -			<VirtualMachineLabel>
   27.86 -				<!-- serves network access to other domains -->
   27.87 -				<Name>dom_NetworkDomain</Name>
   27.88 -				<SimpleTypeEnforcementTypes>
   27.89 -					<!-- access right to the resource (ethernet card) -->
   27.90 -					<Type>ste_NetworkAdapter0</Type>
   27.91 -					<!-- can serve following types -->
   27.92 -					<Type>ste_PersonalFinances</Type>
   27.93 -					<Type>ste_InternetInsecure</Type>
   27.94 -					<Type>ste_DonatedCycles</Type>
   27.95 -				</SimpleTypeEnforcementTypes>
   27.96 -			</VirtualMachineLabel>
   27.97 -		</SubjectLabels>
   27.98 -
   27.99 -		<ObjectLabels>
  27.100 -			<ResourceLabel>
  27.101 -				<Name>res_ManagementResource</Name>
  27.102 -				<SimpleTypeEnforcementTypes>
  27.103 -					<Type>ste_SystemManagement</Type>
  27.104 -				</SimpleTypeEnforcementTypes>
  27.105 -			</ResourceLabel>
  27.106 -
  27.107 -			<ResourceLabel>
  27.108 -				<Name>res_HardDrive(hda)</Name>
  27.109 -				<SimpleTypeEnforcementTypes>
  27.110 -					<Type>ste_PersistentStorageA</Type>
  27.111 -				</SimpleTypeEnforcementTypes>
  27.112 -			</ResourceLabel>
  27.113 -
  27.114 -			<ResourceLabel>
  27.115 -				<Name>res_LogicalDiskPartition1(hda1)</Name>
  27.116 -				<SimpleTypeEnforcementTypes>
  27.117 -					<Type>ste_PersonalFinances</Type>
  27.118 -				</SimpleTypeEnforcementTypes>
  27.119 -			</ResourceLabel>
  27.120 -
  27.121 -			<ResourceLabel>
  27.122 -				<Name>res_LogicalDiskPartition2(hda2)</Name>
  27.123 -				<SimpleTypeEnforcementTypes>
  27.124 -					<Type>ste_InternetInsecure</Type>
  27.125 -				</SimpleTypeEnforcementTypes>
  27.126 -			</ResourceLabel>
  27.127 -
  27.128 -			<ResourceLabel>
  27.129 -				<Name>res_EthernetCard</Name>
  27.130 -				<SimpleTypeEnforcementTypes>
  27.131 -					<Type>ste_NetworkAdapter0</Type>
  27.132 -				</SimpleTypeEnforcementTypes>
  27.133 -			</ResourceLabel>
  27.134 -
  27.135 -			<ResourceLabel>
  27.136 -				<Name>res_SecurityToken</Name>
  27.137 -				<SimpleTypeEnforcementTypes>
  27.138 -					<Type>ste_PersonalFinances</Type>
  27.139 -				</SimpleTypeEnforcementTypes>
  27.140 -			</ResourceLabel>
  27.141 -
  27.142 -			<ResourceLabel>
  27.143 -				<Name>res_GraphicsAdapter</Name>
  27.144 -				<SimpleTypeEnforcementTypes>
  27.145 -					<Type>ste_SystemManagement</Type>
  27.146 -				</SimpleTypeEnforcementTypes>
  27.147 -			</ResourceLabel>
  27.148 -		</ObjectLabels>
  27.149 -	</SecurityLabelTemplate>
  27.150 -
  27.151 -</SecurityPolicyDefinition>
  27.152 -
    28.1 --- a/tools/security/secpol_xml2bin.c	Tue Dec 04 22:54:58 2007 +0000
    28.2 +++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
    28.3 @@ -1,1457 +0,0 @@
    28.4 -/****************************************************************
    28.5 - * secpol_xml2bin.c
    28.6 - *
    28.7 - * Copyright (C) 2005 IBM Corporation
    28.8 - *
    28.9 - * Author: Reiner Sailer <sailer@us.ibm.com>
   28.10 - *
   28.11 - * Maintained:
   28.12 - * Reiner Sailer <sailer@us.ibm.com>
   28.13 - * Ray Valdez <rvaldez@us.ibm.com>
   28.14 - *
   28.15 - * This program is free software; you can redistribute it and/or
   28.16 - * modify it under the terms of the GNU General Public License as
   28.17 - * published by the Free Software Foundation, version 2 of the
   28.18 - * License.
   28.19 - *
   28.20 - * sHype policy translation tool. This tool takes an XML
   28.21 - * policy specification as input and produces a binary
   28.22 - * policy file that can be loaded into Xen through the
   28.23 - * ACM operations (xensec_tool loadpolicy) interface or at
   28.24 - * boot time (grub module parameter)
   28.25 - *
   28.26 - * indent -i4 -kr -nut
   28.27 - */
   28.28 -
   28.29 -#include <stdio.h>
   28.30 -#include <stdlib.h>
   28.31 -#include <string.h>
   28.32 -#include <errno.h>
   28.33 -#include <libgen.h>
   28.34 -#include <fcntl.h>
   28.35 -#include <unistd.h>
   28.36 -#include <sys/types.h>
   28.37 -#include <sys/stat.h>
   28.38 -#include <sys/queue.h>
   28.39 -#include <netinet/in.h>
   28.40 -#include <libxml/xmlschemas.h>
   28.41 -#include <libxml/parser.h>
   28.42 -#include <libxml/tree.h>
   28.43 -#include <libxml/xmlreader.h>
   28.44 -#include <stdint.h>
   28.45 -#include <xen/xsm/acm.h>
   28.46 -
   28.47 -#include "secpol_xml2bin.h"
   28.48 -
   28.49 -#define DEBUG    0
   28.50 -
   28.51 -#define NULL_LABEL_NAME "__NULL_LABEL__"
   28.52 -
   28.53 -#define ROUND8(x)   ((x + 7) & ~7)
   28.54 -
   28.55 -/* primary / secondary policy component setting */
   28.56 -enum policycomponent { CHWALL, STE, NULLPOLICY }
   28.57 -    primary = NULLPOLICY, secondary = NULLPOLICY;
   28.58 -
   28.59 -/* general list element for ste and chwall type queues */
   28.60 -struct type_entry {
   28.61 -    TAILQ_ENTRY(type_entry) entries;
   28.62 -    char *name;                 /* name of type from xml file */
   28.63 -    type_t mapping;             /* type mapping into 16bit */
   28.64 -};
   28.65 -
   28.66 -TAILQ_HEAD(tailhead, type_entry) ste_head, chwall_head;
   28.67 -
   28.68 -/* general list element for all label queues */
   28.69 -enum label_type { VM, RES, ANY };
   28.70 -struct ssid_entry {
   28.71 -    TAILQ_ENTRY(ssid_entry) entries;
   28.72 -    char *name;                 /* label name */
   28.73 -    enum label_type type;       /* type: VM / RESOURCE LABEL */
   28.74 -    u_int32_t num;              /* ssid or referenced ssid */
   28.75 -    int is_ref;                 /* if this entry references earlier ssid number */
   28.76 -    unsigned char *row;         /* index of types (if not a reference) */
   28.77 -};
   28.78 -
   28.79 -TAILQ_HEAD(tailhead_ssid, ssid_entry) ste_ssid_head, chwall_ssid_head,
   28.80 -    conflictsets_head;
   28.81 -struct ssid_entry *current_chwall_ssid_p = NULL;
   28.82 -struct ssid_entry *current_ste_ssid_p = NULL;
   28.83 -struct ssid_entry *current_conflictset_p = NULL;
   28.84 -
   28.85 -/* which label to assign to dom0 during boot */
   28.86 -char *bootstrap_label;
   28.87 -
   28.88 -u_int32_t max_ste_ssids = 0;
   28.89 -u_int32_t max_chwall_ssids = 0;
   28.90 -u_int32_t max_chwall_labels = 0;
   28.91 -u_int32_t max_ste_labels = 0;
   28.92 -u_int32_t max_conflictsets = 0;
   28.93 -
   28.94 -char *current_ssid_name;        /* store name until structure is allocated */
   28.95 -char *current_conflictset_name; /* store name until structure is allocated */
   28.96 -
   28.97 -/* dynamic list of type mappings for STE */
   28.98 -u_int32_t max_ste_types = 0;
   28.99 -
  28.100 -/* dynamic list of type mappings for CHWALL */
  28.101 -u_int32_t max_chwall_types = 0;
  28.102 -
  28.103 -/* dynamic list of conflict sets */
  28.104 -int max_conflict_set = 0;
  28.105 -
  28.106 -/* which policies are defined */
  28.107 -int have_ste = 0;
  28.108 -int have_chwall = 0;
  28.109 -
  28.110 -/* input/output file names */
  28.111 -char *policy_filename = NULL,
  28.112 -    *binary_filename = NULL,
  28.113 -    *mapping_filename = NULL, *schema_filename = NULL;
  28.114 -
  28.115 -char *policy_reference_name = NULL;
  28.116 -
  28.117 -char *policy_version_string = NULL;
  28.118 -
  28.119 -void walk_labels(xmlNode * start, xmlDocPtr doc, unsigned long state);
  28.120 -
  28.121 -void usage(char *prg)
  28.122 -{
  28.123 -    printf(
  28.124 -    "Usage: %s [OPTIONS] POLICYNAME\n"
  28.125 -    "POLICYNAME is the directory name within the policy directory\n"
  28.126 -    "that contains the policy files.  The default policy directory\n"
  28.127 -    "is '%s' (see the '-d' option below to change it)\n"
  28.128 -    "The policy files contained in the POLICYNAME directory must be named:\n"
  28.129 -    "\tPOLICYNAME-security_policy.xml\n"
  28.130 -    "\tPOLICYNAME-security_label_template.xml\n\n"
  28.131 -    "OPTIONS:\n"
  28.132 -    "\t-d POLICYDIR\n"
  28.133 -    "\t\tUse POLICYDIR as the policy directory. This directory must \n"
  28.134 -    "\t\tcontain the policy schema file 'security_policy.xsd'\n",
  28.135 -    prg, POLICY_DIR);
  28.136 -    exit(EXIT_FAILURE);
  28.137 -}
  28.138 -
  28.139 -
  28.140 -/***************** policy-related parsing *********************/
  28.141 -
  28.142 -char *type_by_mapping(struct tailhead *head, u_int32_t mapping)
  28.143 -{
  28.144 -    struct type_entry *np;
  28.145 -    for (np = head->tqh_first; np != NULL; np = np->entries.tqe_next)
  28.146 -        if (np->mapping == mapping)
  28.147 -            return np->name;
  28.148 -    return NULL;
  28.149 -}
  28.150 -
  28.151 -
  28.152 -struct type_entry *lookup(struct tailhead *head, char *name)
  28.153 -{
  28.154 -    struct type_entry *np;
  28.155 -    for (np = head->tqh_first; np != NULL; np = np->entries.tqe_next)
  28.156 -        if (!(strcmp(np->name, name)))
  28.157 -            return np;
  28.158 -    return NULL;
  28.159 -}
  28.160 -
  28.161 -/* enforces single-entry lists */
  28.162 -int add_entry(struct tailhead *head, char *name, type_t mapping)
  28.163 -{
  28.164 -    struct type_entry *e;
  28.165 -    if (lookup(head, name)) {
  28.166 -        printf("Error: Type >%s< defined more than once.\n", name);
  28.167 -        return -EFAULT;         /* already in the list */
  28.168 -    }
  28.169 -    if (!(e = malloc(sizeof(struct type_entry))))
  28.170 -        return -ENOMEM;
  28.171 -
  28.172 -    e->name = name;
  28.173 -    e->mapping = mapping;
  28.174 -    TAILQ_INSERT_TAIL(head, e, entries);
  28.175 -    return 0;
  28.176 -}
  28.177 -
  28.178 -int totoken(char *tok)
  28.179 -{
  28.180 -    int i;
  28.181 -    for (i = 0; token[i] != NULL; i++)
  28.182 -        if (!strcmp(token[i], tok))
  28.183 -            return i;
  28.184 -    return -EFAULT;
  28.185 -}
  28.186 -
  28.187 -/* conflictsets use the same data structure as ssids; since
  28.188 - * they are similar in structure (set of types)
  28.189 - */
  28.190 -int init_next_conflictset(void)
  28.191 -{
  28.192 -    struct ssid_entry *conflictset = malloc(sizeof(struct ssid_entry));
  28.193 -
  28.194 -    if (!conflictset)
  28.195 -        return -ENOMEM;
  28.196 -
  28.197 -    conflictset->name = current_conflictset_name;
  28.198 -    conflictset->num = max_conflictsets++;
  28.199 -    conflictset->is_ref = 0;    /* n/a for conflictsets */
  28.200 -        /**
  28.201 -         *  row: allocate one byte per type;
  28.202 -         *  [i] != 0 --> mapped type >i< is part of the conflictset
  28.203 -         */
  28.204 -    conflictset->row = malloc(max_chwall_types);
  28.205 -    if (!conflictset->row)
  28.206 -        return -ENOMEM;
  28.207 -
  28.208 -    memset(conflictset->row, 0, max_chwall_types);
  28.209 -    TAILQ_INSERT_TAIL(&conflictsets_head, conflictset, entries);
  28.210 -    current_conflictset_p = conflictset;
  28.211 -    return 0;
  28.212 -}
  28.213 -
  28.214 -int register_type(xmlNode * cur_node, xmlDocPtr doc, unsigned long state)
  28.215 -{
  28.216 -    xmlChar *text;
  28.217 -    struct type_entry *e;
  28.218 -
  28.219 -
  28.220 -    text = xmlNodeListGetString(doc, cur_node->xmlChildrenNode, 1);
  28.221 -    if (!text) {
  28.222 -        printf("Error reading type name!\n");
  28.223 -        return -EFAULT;
  28.224 -    }
  28.225 -
  28.226 -    switch (state) {
  28.227 -    case XML2BIN_stetype_S:
  28.228 -        if (add_entry(&ste_head, (char *) text, max_ste_types)) {
  28.229 -            xmlFree(text);
  28.230 -            return -EFAULT;
  28.231 -        }
  28.232 -        max_ste_types++;
  28.233 -        break;
  28.234 -
  28.235 -    case XML2BIN_chwalltype_S:
  28.236 -        if (add_entry(&chwall_head, (char *) text, max_chwall_types)) {
  28.237 -            xmlFree(text);
  28.238 -            return -EFAULT;
  28.239 -        }
  28.240 -        max_chwall_types++;
  28.241 -        break;
  28.242 -
  28.243 -    case XML2BIN_conflictsettype_S:
  28.244 -        /* a) search the type in the chwall_type list */
  28.245 -        e = lookup(&chwall_head, (char *) text);
  28.246 -        if (e == NULL) {
  28.247 -            printf("CS type >%s< not a CHWALL type.\n", text);
  28.248 -            xmlFree(text);
  28.249 -            return -EFAULT;
  28.250 -        }
  28.251 -        /* b) add type entry to the current cs set */
  28.252 -        if (current_conflictset_p->row[e->mapping]) {
  28.253 -            printf
  28.254 -                ("ERROR: Double entry of type >%s< in conflict set %d.\n",
  28.255 -                 text, current_conflictset_p->num);
  28.256 -            xmlFree(text);
  28.257 -            return -EFAULT;
  28.258 -        }
  28.259 -        current_conflictset_p->row[e->mapping] = 1;
  28.260 -        break;
  28.261 -
  28.262 -    default:
  28.263 -        printf("Incorrect type environment (state = %lx, text = %s).\n",
  28.264 -               state, text);
  28.265 -        xmlFree(text);
  28.266 -        return -EFAULT;
  28.267 -    }
  28.268 -    return 0;
  28.269 -}
  28.270 -
  28.271 -void set_component_type(xmlNode * cur_node, enum policycomponent pc)
  28.272 -{
  28.273 -    xmlChar *order;
  28.274 -
  28.275 -    if ((order =
  28.276 -         xmlGetProp(cur_node, (xmlChar *) PRIMARY_COMPONENT_ATTR_NAME))) {
  28.277 -        if (strcmp((char *) order, PRIMARY_COMPONENT)) {
  28.278 -            printf("ERROR: Illegal attribut value >order=%s<.\n",
  28.279 -                   (char *) order);
  28.280 -            xmlFree(order);
  28.281 -            exit(EXIT_FAILURE);
  28.282 -        }
  28.283 -        if (primary != NULLPOLICY) {
  28.284 -            printf("ERROR: Primary Policy Component set twice!\n");
  28.285 -            exit(EXIT_FAILURE);
  28.286 -        }
  28.287 -        primary = pc;
  28.288 -        xmlFree(order);
  28.289 -    }
  28.290 -}
  28.291 -
  28.292 -void walk_policy(xmlNode * start, xmlDocPtr doc, unsigned long state)
  28.293 -{
  28.294 -    xmlNode *cur_node = NULL;
  28.295 -    int code;
  28.296 -
  28.297 -    for (cur_node = start; cur_node; cur_node = cur_node->next) {
  28.298 -        if ((code = totoken((char *) cur_node->name)) < 0) {
  28.299 -            printf("Unknown token: >%s<. Aborting.\n", cur_node->name);
  28.300 -            exit(EXIT_FAILURE);
  28.301 -        }
  28.302 -        switch (code) {         /* adjust state to new state */
  28.303 -        case XML2BIN_SECPOL:
  28.304 -        case XML2BIN_STETYPES:
  28.305 -        case XML2BIN_CHWALLTYPES:
  28.306 -        case XML2BIN_CONFLICTSETS:
  28.307 -        case XML2BIN_POLICYHEADER:
  28.308 -        case XML2BIN_FROMPOLICY:
  28.309 -            walk_policy(cur_node->children, doc, state | (1 << code));
  28.310 -            break;
  28.311 -
  28.312 -        case XML2BIN_POLICYNAME:       /* get policy reference name .... */
  28.313 -            if (state != XML2BIN_PN_S &&
  28.314 -                state != XML2BIN_PN_frompolicy_S) {
  28.315 -                printf("ERROR: >Url< >%s< out of context.\n",
  28.316 -                       (char *) xmlNodeListGetString(doc,
  28.317 -                                                     cur_node->
  28.318 -                                                     xmlChildrenNode, 1));
  28.319 -                exit(EXIT_FAILURE);
  28.320 -            }
  28.321 -            if (state == XML2BIN_PN_S) {
  28.322 -                policy_reference_name = (char *)
  28.323 -                    xmlNodeListGetString(doc, cur_node->xmlChildrenNode, 1);
  28.324 -                if (!policy_reference_name) {
  28.325 -                    printf("ERROR: empty >policy reference name (Url)<!\n");
  28.326 -                    exit(EXIT_FAILURE);
  28.327 -                } else
  28.328 -                    printf("Policy Reference name (Url): %s\n",
  28.329 -                           policy_reference_name);
  28.330 -            }
  28.331 -            break;
  28.332 -
  28.333 -        case XML2BIN_VERSION:         /* get policy version number .... */
  28.334 -            if (state != XML2BIN_PN_S &&
  28.335 -                state != XML2BIN_PN_frompolicy_S) {
  28.336 -                printf("ERROR: >Url< >%s< out of context.\n",
  28.337 -                       (char *) xmlNodeListGetString(doc,
  28.338 -                                                     cur_node->
  28.339 -                                                     xmlChildrenNode, 1));
  28.340 -                exit(EXIT_FAILURE);
  28.341 -            }
  28.342 -            if (state == XML2BIN_PN_S) {
  28.343 -                policy_version_string = (char *)
  28.344 -                    xmlNodeListGetString(doc, cur_node->xmlChildrenNode, 1);
  28.345 -                if (!policy_version_string) {
  28.346 -                    printf("ERROR: empty >policy version string <!\n");
  28.347 -                    exit(EXIT_FAILURE);
  28.348 -                } else
  28.349 -                    printf("Policy version string: %s\n",
  28.350 -                           policy_version_string);
  28.351 -            }
  28.352 -            break;
  28.353 -
  28.354 -        case XML2BIN_STE:
  28.355 -            if (WRITTEN_AGAINST_ACM_STE_VERSION != ACM_STE_VERSION) {
  28.356 -                printf
  28.357 -                    ("ERROR: This program was written against another STE version.\n");
  28.358 -                exit(EXIT_FAILURE);
  28.359 -            }
  28.360 -            have_ste = 1;
  28.361 -            set_component_type(cur_node, STE);
  28.362 -            walk_policy(cur_node->children, doc, state | (1 << code));
  28.363 -            break;
  28.364 -
  28.365 -        case XML2BIN_CHWALL:
  28.366 -            if (WRITTEN_AGAINST_ACM_CHWALL_VERSION != ACM_CHWALL_VERSION) {
  28.367 -                printf
  28.368 -                    ("ERROR: This program was written against another CHWALL version.\n");
  28.369 -                exit(EXIT_FAILURE);
  28.370 -            }
  28.371 -            have_chwall = 1;
  28.372 -            set_component_type(cur_node, CHWALL);
  28.373 -            walk_policy(cur_node->children, doc, state | (1 << code));
  28.374 -            break;
  28.375 -
  28.376 -        case XML2BIN_CSTYPE:
  28.377 -            current_conflictset_name =
  28.378 -                (char *) xmlGetProp(cur_node, (xmlChar *) "name");
  28.379 -            if (!current_conflictset_name)
  28.380 -                current_conflictset_name = "";
  28.381 -
  28.382 -            if (init_next_conflictset()) {
  28.383 -                printf
  28.384 -                    ("ERROR: creating new conflictset structure failed.\n");
  28.385 -                exit(EXIT_FAILURE);
  28.386 -            }
  28.387 -            walk_policy(cur_node->children, doc, state | (1 << code));
  28.388 -            break;
  28.389 -
  28.390 -        case XML2BIN_TYPE:
  28.391 -            if (register_type(cur_node, doc, state))
  28.392 -                exit(EXIT_FAILURE);
  28.393 -            /* type leaf */
  28.394 -            break;
  28.395 -
  28.396 -        case XML2BIN_LABELTEMPLATE:    /* handle in second pass */
  28.397 -        case XML2BIN_TEXT:
  28.398 -        case XML2BIN_COMMENT:
  28.399 -        case XML2BIN_DATE:
  28.400 -        case XML2BIN_REFERENCE:
  28.401 -        case XML2BIN_NSURL:    /* for future use: where to find global label / type name mappings */
  28.402 -        case XML2BIN_URL:      /* for future use: where to find policy */
  28.403 -            /* leaf - nothing to do */
  28.404 -            break;
  28.405 -
  28.406 -        default:
  28.407 -            printf("Unkonwn token Error (%d) in Policy\n", code);
  28.408 -            exit(EXIT_FAILURE);
  28.409 -        }
  28.410 -
  28.411 -    }
  28.412 -    return;
  28.413 -}
  28.414 -
  28.415 -void init_type_mapping(void)
  28.416 -{
  28.417 -    printf("Creating ssid mappings ...\n");
  28.418 -
  28.419 -    /* initialize the ste and chwall type lists */
  28.420 -    TAILQ_INIT(&ste_head);
  28.421 -    TAILQ_INIT(&chwall_head);
  28.422 -    TAILQ_INIT(&conflictsets_head);
  28.423 -}
  28.424 -
  28.425 -void post_type_mapping(void)
  28.426 -{
  28.427 -    struct type_entry *te;
  28.428 -    struct ssid_entry *se;
  28.429 -    int i;
  28.430 -
  28.431 -    /* determine primary/secondary policy component orders */
  28.432 -    if ((primary == NULLPOLICY) && have_chwall)
  28.433 -        primary = CHWALL;       /* default if not set */
  28.434 -    else if ((primary == NULLPOLICY) && have_ste)
  28.435 -        primary = STE;
  28.436 -
  28.437 -    switch (primary) {
  28.438 -
  28.439 -    case CHWALL:
  28.440 -        if (have_ste)
  28.441 -            secondary = STE;
  28.442 -        /* else default = NULLPOLICY */
  28.443 -        break;
  28.444 -
  28.445 -    case STE:
  28.446 -        if (have_chwall)
  28.447 -            secondary = CHWALL;
  28.448 -        /* else default = NULLPOLICY */
  28.449 -        break;
  28.450 -
  28.451 -    default:
  28.452 -        /* NULL/NULL policy */
  28.453 -        break;
  28.454 -    }
  28.455 -
  28.456 -    if (!DEBUG)
  28.457 -        return;
  28.458 -
  28.459 -    /* print queues */
  28.460 -    if (have_ste) {
  28.461 -        printf("STE-Type queue (%s):\n",
  28.462 -               (primary == STE) ? "PRIMARY" : "SECONDARY");
  28.463 -        for (te = ste_head.tqh_first; te != NULL;
  28.464 -             te = te->entries.tqe_next)
  28.465 -            printf("name=%22s, map=%x\n", te->name, te->mapping);
  28.466 -    }
  28.467 -    if (have_chwall) {
  28.468 -        printf("CHWALL-Type queue (%s):\n",
  28.469 -               (primary == CHWALL) ? "PRIMARY" : "SECONDARY");
  28.470 -        for (te = chwall_head.tqh_first; te != NULL;
  28.471 -             te = te->entries.tqe_next)
  28.472 -            printf("name=%s, map=%x\n", te->name, te->mapping);
  28.473 -
  28.474 -        printf("Conflictset queue (max=%d):\n", max_conflictsets);
  28.475 -        for (se = conflictsets_head.tqh_first; se != NULL;
  28.476 -             se = se->entries.tqe_next) {
  28.477 -            printf("conflictset name >%s<\n",
  28.478 -                   se->name ? se->name : "NONAME");
  28.479 -            for (i = 0; i < max_chwall_types; i++)
  28.480 -                if (se->row[i])
  28.481 -                    printf("#%x ", i);
  28.482 -            printf("\n");
  28.483 -        }
  28.484 -    }
  28.485 -}
  28.486 -
  28.487 -
  28.488 -/***************** template-related parsing *********************/
  28.489 -
  28.490 -/* add default ssid at head of ssid queues */
  28.491 -int init_ssid_queues(void)
  28.492 -{
  28.493 -    struct ssid_entry *default_ssid_chwall, *default_ssid_ste;
  28.494 -
  28.495 -    default_ssid_chwall = malloc(sizeof(struct ssid_entry));
  28.496 -    default_ssid_ste = malloc(sizeof(struct ssid_entry));
  28.497 -
  28.498 -    if ((!default_ssid_chwall) || (!default_ssid_ste))
  28.499 -        return -ENOMEM;
  28.500 -
  28.501 -    /* default chwall ssid */
  28.502 -    default_ssid_chwall->name = NULL_LABEL_NAME;
  28.503 -    default_ssid_chwall->num = max_chwall_ssids++;
  28.504 -    default_ssid_chwall->is_ref = 0;
  28.505 -    default_ssid_chwall->type = ANY;
  28.506 -
  28.507 -    default_ssid_chwall->row = malloc(max_chwall_types);
  28.508 -
  28.509 -    if (!default_ssid_chwall->row)
  28.510 -        return -ENOMEM;
  28.511 -
  28.512 -    memset(default_ssid_chwall->row, 0, max_chwall_types);
  28.513 -
  28.514 -    TAILQ_INSERT_TAIL(&chwall_ssid_head, default_ssid_chwall, entries);
  28.515 -    current_chwall_ssid_p = default_ssid_chwall;
  28.516 -    max_chwall_labels++;
  28.517 -
  28.518 -    /* default ste ssid */
  28.519 -    default_ssid_ste->name = NULL_LABEL_NAME;
  28.520 -    default_ssid_ste->num = max_ste_ssids++;
  28.521 -    default_ssid_ste->is_ref = 0;
  28.522 -    default_ssid_ste->type = ANY;
  28.523 -
  28.524 -    default_ssid_ste->row = malloc(max_ste_types);
  28.525 -
  28.526 -    if (!default_ssid_ste->row)
  28.527 -        return -ENOMEM;
  28.528 -
  28.529 -    memset(default_ssid_ste->row, 0, max_ste_types);
  28.530 -
  28.531 -    TAILQ_INSERT_TAIL(&ste_ssid_head, default_ssid_ste, entries);
  28.532 -    current_ste_ssid_p = default_ssid_ste;
  28.533 -    max_ste_labels++;
  28.534 -    return 0;
  28.535 -}
  28.536 -
  28.537 -int init_next_chwall_ssid(unsigned long state)
  28.538 -{
  28.539 -    struct ssid_entry *ssid = malloc(sizeof(struct ssid_entry));
  28.540 -
  28.541 -    if (!ssid)
  28.542 -        return -ENOMEM;
  28.543 -
  28.544 -    ssid->name = current_ssid_name;
  28.545 -    ssid->num = max_chwall_ssids++;
  28.546 -    ssid->is_ref = 0;
  28.547 -
  28.548 -    if (state & (1 << XML2BIN_VM))
  28.549 -        ssid->type = VM;
  28.550 -    else
  28.551 -        ssid->type = RES;
  28.552 -        /**
  28.553 -         *  row: allocate one byte per type;
  28.554 -         *  [i] != 0 --> mapped type >i< is part of the ssid
  28.555 -         */
  28.556 -    ssid->row = malloc(max_chwall_types);
  28.557 -    if (!ssid->row)
  28.558 -        return -ENOMEM;
  28.559 -
  28.560 -    memset(ssid->row, 0, max_chwall_types);
  28.561 -    TAILQ_INSERT_TAIL(&chwall_ssid_head, ssid, entries);
  28.562 -    current_chwall_ssid_p = ssid;
  28.563 -    max_chwall_labels++;
  28.564 -    return 0;
  28.565 -}
  28.566 -
  28.567 -int init_next_ste_ssid(unsigned long state)
  28.568 -{
  28.569 -    struct ssid_entry *ssid = malloc(sizeof(struct ssid_entry));
  28.570 -
  28.571 -    if (!ssid)
  28.572 -        return -ENOMEM;
  28.573 -
  28.574 -    ssid->name = current_ssid_name;
  28.575 -    ssid->num = max_ste_ssids++;
  28.576 -    ssid->is_ref = 0;
  28.577 -
  28.578 -    if (state & (1 << XML2BIN_VM))
  28.579 -        ssid->type = VM;
  28.580 -    else
  28.581 -        ssid->type = RES;
  28.582 -
  28.583 -        /**
  28.584 -         *  row: allocate one byte per type;
  28.585 -         *  [i] != 0 --> mapped type >i< is part of the ssid
  28.586 -         */
  28.587 -    ssid->row = malloc(max_ste_types);
  28.588 -    if (!ssid->row)
  28.589 -        return -ENOMEM;
  28.590 -
  28.591 -    memset(ssid->row, 0, max_ste_types);
  28.592 -    TAILQ_INSERT_TAIL(&ste_ssid_head, ssid, entries);
  28.593 -    current_ste_ssid_p = ssid;
  28.594 -    max_ste_labels++;
  28.595 -
  28.596 -    return 0;
  28.597 -}
  28.598 -
  28.599 -
  28.600 -/* adds a type to the current ssid */
  28.601 -int add_type(xmlNode * cur_node, xmlDocPtr doc, unsigned long state)
  28.602 -{
  28.603 -    xmlChar *text;
  28.604 -    struct type_entry *e;
  28.605 -
  28.606 -    text = xmlNodeListGetString(doc, cur_node->xmlChildrenNode, 1);
  28.607 -    if (!text) {
  28.608 -        printf("Error reading type name!\n");
  28.609 -        return -EFAULT;
  28.610 -    }
  28.611 -    /* same for all: 1. lookup type mapping, 2. mark type in ssid */
  28.612 -    switch (state) {
  28.613 -    case XML2BIN_VM_STE_S:
  28.614 -    case XML2BIN_RES_STE_S:
  28.615 -        /* lookup the type mapping and include the type mapping into the array */
  28.616 -        if (!(e = lookup(&ste_head, (char *) text))) {
  28.617 -            printf("ERROR: unknown VM STE type >%s<.\n", text);
  28.618 -            exit(EXIT_FAILURE);
  28.619 -        }
  28.620 -        if (current_ste_ssid_p->row[e->mapping])
  28.621 -            printf("Warning: double entry of VM STE type >%s<.\n", text);
  28.622 -
  28.623 -        current_ste_ssid_p->row[e->mapping] = 1;
  28.624 -        break;
  28.625 -
  28.626 -    case XML2BIN_VM_CHWALL_S:
  28.627 -        /* lookup the type mapping and include the type mapping into the array */
  28.628 -        if (!(e = lookup(&chwall_head, (char *) text))) {
  28.629 -            printf("ERROR: unknown VM CHWALL type >%s<.\n", text);
  28.630 -            exit(EXIT_FAILURE);
  28.631 -        }
  28.632 -        if (current_chwall_ssid_p->row[e->mapping])
  28.633 -            printf("Warning: double entry of VM CHWALL type >%s<.\n",
  28.634 -                   text);
  28.635 -
  28.636 -        current_chwall_ssid_p->row[e->mapping] = 1;
  28.637 -        break;
  28.638 -
  28.639 -    default:
  28.640 -        printf("Incorrect type environment (state = %lx, text = %s).\n",
  28.641 -               state, text);
  28.642 -        xmlFree(text);
  28.643 -        return -EFAULT;
  28.644 -    }
  28.645 -    return 0;
  28.646 -}
  28.647 -
  28.648 -void set_bootstrap_label(xmlNode * cur_node)
  28.649 -{
  28.650 -    xmlChar *order;
  28.651 -
  28.652 -    if ((order =
  28.653 -         xmlGetProp(cur_node, (xmlChar *) BOOTSTRAP_LABEL_ATTR_NAME)))
  28.654 -        bootstrap_label = (char *) order;
  28.655 -    else {
  28.656 -        printf("ERROR: No bootstrap label defined!\n");
  28.657 -        exit(EXIT_FAILURE);
  28.658 -    }
  28.659 -}
  28.660 -
  28.661 -void walk_labels(xmlNode * start, xmlDocPtr doc, unsigned long state)
  28.662 -{
  28.663 -    xmlNode *cur_node = NULL;
  28.664 -    int code;
  28.665 -
  28.666 -    for (cur_node = start; cur_node; cur_node = cur_node->next) {
  28.667 -        if ((code = totoken((char *) cur_node->name)) < 0) {
  28.668 -            printf("Unkonwn token: >%s<. Aborting.\n", cur_node->name);
  28.669 -            exit(EXIT_FAILURE);
  28.670 -        }
  28.671 -        switch (code) {         /* adjust state to new state */
  28.672 -        case XML2BIN_SUBJECTS:
  28.673 -            set_bootstrap_label(cur_node);
  28.674 -            /* fall through */
  28.675 -        case XML2BIN_SECPOL:
  28.676 -        case XML2BIN_LABELTEMPLATE:
  28.677 -        case XML2BIN_VM:
  28.678 -        case XML2BIN_RES:
  28.679 -        case XML2BIN_OBJECTS:
  28.680 -            walk_labels(cur_node->children, doc, state | (1 << code));
  28.681 -            break;
  28.682 -
  28.683 -        case XML2BIN_STETYPES:
  28.684 -            /* create new ssid entry to use and point current to it */
  28.685 -            if (init_next_ste_ssid(state)) {
  28.686 -                printf("ERROR: creating new ste ssid structure failed.\n");
  28.687 -                exit(EXIT_FAILURE);
  28.688 -            }
  28.689 -            walk_labels(cur_node->children, doc, state | (1 << code));
  28.690 -            break;
  28.691 -
  28.692 -        case XML2BIN_CHWALLTYPES:
  28.693 -            /* create new ssid entry to use and point current to it */
  28.694 -            if (init_next_chwall_ssid(state)) {
  28.695 -                printf
  28.696 -                    ("ERROR: creating new chwall ssid structure failed.\n");
  28.697 -                exit(EXIT_FAILURE);
  28.698 -            }
  28.699 -            walk_labels(cur_node->children, doc, state | (1 << code));
  28.700 -            break;
  28.701 -
  28.702 -        case XML2BIN_TYPE:
  28.703 -            /* add type to current ssid */
  28.704 -            if (add_type(cur_node, doc, state))
  28.705 -                exit(EXIT_FAILURE);
  28.706 -            break;
  28.707 -
  28.708 -        case XML2BIN_NAME:
  28.709 -            if ((state == XML2BIN_VM_S) || (state == XML2BIN_RES_S)) {
  28.710 -                current_ssid_name = (char *)
  28.711 -                    xmlNodeListGetString(doc, cur_node->xmlChildrenNode,
  28.712 -                                         1);
  28.713 -                if (!current_ssid_name) {
  28.714 -                    printf("ERROR: empty >vm/res name<!\n");
  28.715 -                    exit(EXIT_FAILURE);
  28.716 -                }
  28.717 -            } else {
  28.718 -                printf
  28.719 -                    ("ERROR: >name< >%s< out of context (state = 0x%lx.\n",
  28.720 -                     (char *) xmlNodeListGetString(doc,
  28.721 -                                                   cur_node->
  28.722 -                                                   xmlChildrenNode, 1),
  28.723 -                     state);
  28.724 -                exit(EXIT_FAILURE);
  28.725 -            }
  28.726 -            break;
  28.727 -
  28.728 -        case XML2BIN_TEXT:
  28.729 -        case XML2BIN_COMMENT:
  28.730 -        case XML2BIN_POLICYHEADER:
  28.731 -        case XML2BIN_STE:
  28.732 -        case XML2BIN_CHWALL:
  28.733 -            break;
  28.734 -
  28.735 -        default:
  28.736 -            printf("Unkonwn token Error (%d) in Label Template\n", code);
  28.737 -            exit(EXIT_FAILURE);
  28.738 -        }
  28.739 -    }
  28.740 -    return;
  28.741 -}
  28.742 -
  28.743 -/*
  28.744 - * will go away as soon as we have non-static bootstrap ssidref for dom0
  28.745 - */
  28.746 -void fixup_bootstrap_label(struct tailhead_ssid *head,
  28.747 -                           u_int32_t max_types, u_int32_t * max_ssids)
  28.748 -{
  28.749 -    struct ssid_entry *np;
  28.750 -    int i;
  28.751 -
  28.752 -    /* should not happen if xml / xsd checks work */
  28.753 -    if (!bootstrap_label) {
  28.754 -        printf("ERROR: No bootstrap label defined.\n");
  28.755 -        exit(EXIT_FAILURE);
  28.756 -    }
  28.757 -
  28.758 -    /* search bootstrap_label */
  28.759 -    for (np = head->tqh_first; np != NULL; np = np->entries.tqe_next) {
  28.760 -        if (!strcmp(np->name, bootstrap_label)) {
  28.761 -            break;
  28.762 -        }
  28.763 -    }
  28.764 -
  28.765 -    if (!np) {
  28.766 -        /* bootstrap label not found */
  28.767 -        printf("ERROR: Bootstrap label >%s< not found.\n",
  28.768 -               bootstrap_label);
  28.769 -        exit(EXIT_FAILURE);
  28.770 -    }
  28.771 -
  28.772 -    /* move this entry ahead in the list right after the default entry so it
  28.773 -     * receives ssidref 1/1 */
  28.774 -    TAILQ_REMOVE(head, np, entries);
  28.775 -    TAILQ_INSERT_AFTER(head, head->tqh_first, np, entries);
  28.776 -
  28.777 -    /* renumber the ssids (we could also just switch places with 1st element) */
  28.778 -    for (np = head->tqh_first, i = 0; np != NULL;
  28.779 -         np = np->entries.tqe_next, i++)
  28.780 -        np->num = i;
  28.781 -
  28.782 -}
  28.783 -
  28.784 -void init_label_mapping(void)
  28.785 -{
  28.786 -
  28.787 -    printf("Creating label mappings ...\n");
  28.788 -    /* initialize the ste and chwall type lists */
  28.789 -    TAILQ_INIT(&chwall_ssid_head);
  28.790 -    TAILQ_INIT(&ste_ssid_head);
  28.791 -
  28.792 -    /* init with default ssids */
  28.793 -    if (init_ssid_queues()) {
  28.794 -        printf("ERROR adding default ssids.\n");
  28.795 -        exit(EXIT_FAILURE);
  28.796 -    }
  28.797 -}
  28.798 -
  28.799 -void post_label_mapping(void)
  28.800 -{
  28.801 -    struct ssid_entry *np;
  28.802 -    int i;
  28.803 -
  28.804 -    /*
  28.805 -     * now sort bootstrap label to the head of the list
  28.806 -     * (for now), dom0 assumes its label in the first
  28.807 -     * defined ssidref (1/1). 0/0 is the default non-Label
  28.808 -     */
  28.809 -    if (have_chwall)
  28.810 -        fixup_bootstrap_label(&chwall_ssid_head, max_chwall_types,
  28.811 -                              &max_chwall_ssids);
  28.812 -    if (have_ste)
  28.813 -        fixup_bootstrap_label(&ste_ssid_head, max_ste_types,
  28.814 -                              &max_ste_ssids);
  28.815 -
  28.816 -    if (!DEBUG)
  28.817 -        return;
  28.818 -
  28.819 -    /* print queues */
  28.820 -    if (have_chwall) {
  28.821 -        printf("CHWALL SSID queue (max ssidrefs=%d):\n", max_chwall_ssids);
  28.822 -        np = NULL;
  28.823 -        for (np = chwall_ssid_head.tqh_first; np != NULL;
  28.824 -             np = np->entries.tqe_next) {
  28.825 -            printf("SSID #%02u (Label=%s)\n", np->num, np->name);
  28.826 -            if (np->is_ref)
  28.827 -                printf("REFERENCE");
  28.828 -            else
  28.829 -                for (i = 0; i < max_chwall_types; i++)
  28.830 -                    if (np->row[i])
  28.831 -                        printf("#%02d ", i);
  28.832 -            printf("\n\n");
  28.833 -        }
  28.834 -    }
  28.835 -    if (have_ste) {
  28.836 -        printf("STE SSID queue (max ssidrefs=%d):\n", max_ste_ssids);
  28.837 -        np = NULL;
  28.838 -        for (np = ste_ssid_head.tqh_first; np != NULL;
  28.839 -             np = np->entries.tqe_next) {
  28.840 -            printf("SSID #%02u (Label=%s)\n", np->num, np->name);
  28.841 -            if (np->is_ref)
  28.842 -                printf("REFERENCE");
  28.843 -            else
  28.844 -                for (i = 0; i < max_ste_types; i++)
  28.845 -                    if (np->row[i])
  28.846 -                        printf("#%02d ", i);
  28.847 -            printf("\n\n");
  28.848 -        }
  28.849 -    }
  28.850 -}
  28.851 -
  28.852 -void create_mappings(xmlDocPtr doc)
  28.853 -{
  28.854 -    xmlNode *doc_root_node = xmlDocGetRootElement(doc);
  28.855 -
  28.856 -    /* walk the XML policy tree and fill in types and labels */
  28.857 -    init_type_mapping();
  28.858 -    walk_policy(doc_root_node, doc, XML2BIN_NULL);      /* first pass: types */
  28.859 -    post_type_mapping();
  28.860 -    init_label_mapping();
  28.861 -    walk_labels(doc_root_node, doc, XML2BIN_NULL);      /* second pass: labels */
  28.862 -    post_label_mapping();
  28.863 -}
  28.864 -
  28.865 -/***************** writing the binary policy *********************/
  28.866 -
  28.867 -/*
  28.868 - * the mapping file is ascii-based since it will likely be used from
  28.869 - * within scripts (using awk, grep, etc.);
  28.870 - *
  28.871 - * We print from high-level to low-level information so that with one
  28.872 - * pass, any symbol can be resolved (e.g. Label -> types)
  28.873 - */
  28.874 -int write_mapping(char *filename)
  28.875 -{
  28.876 -
  28.877 -    struct ssid_entry *e;
  28.878 -    struct type_entry *t;
  28.879 -    int i;
  28.880 -    FILE *file;
  28.881 -
  28.882 -    if ((file = fopen(filename, "w")) == NULL)
  28.883 -        return -EIO;
  28.884 -
  28.885 -    fprintf(file, "POLICYREFERENCENAME    %s\n", policy_reference_name);
  28.886 -    fprintf(file, "MAGIC                  %08x\n", ACM_MAGIC);
  28.887 -    fprintf(file, "POLICY FILE            %s\n", policy_filename);
  28.888 -    fprintf(file, "BINARY FILE            %s\n", binary_filename);
  28.889 -    if (have_chwall) {
  28.890 -        fprintf(file, "MAX-CHWALL-TYPES       %08x\n", max_chwall_types);
  28.891 -        fprintf(file, "MAX-CHWALL-SSIDS       %08x\n", max_chwall_ssids);
  28.892 -        fprintf(file, "MAX-CHWALL-LABELS      %08x\n", max_chwall_labels);
  28.893 -    }
  28.894 -    if (have_ste) {
  28.895 -        fprintf(file, "MAX-STE-TYPES          %08x\n", max_ste_types);
  28.896 -        fprintf(file, "MAX-STE-SSIDS          %08x\n", max_ste_ssids);
  28.897 -        fprintf(file, "MAX-STE-LABELS         %08x\n", max_ste_labels);
  28.898 -    }
  28.899 -    fprintf(file, "\n");
  28.900 -
  28.901 -    /* primary / secondary order for combined ssid synthesis/analysis
  28.902 -     * if no primary is named, then chwall is primary */
  28.903 -    switch (primary) {
  28.904 -    case CHWALL:
  28.905 -        fprintf(file, "PRIMARY                CHWALL\n");
  28.906 -        break;
  28.907 -
  28.908 -    case STE:
  28.909 -        fprintf(file, "PRIMARY                STE\n");
  28.910 -        break;
  28.911 -
  28.912 -    default:
  28.913 -        fprintf(file, "PRIMARY                NULL\n");
  28.914 -        break;
  28.915 -    }
  28.916 -
  28.917 -    switch (secondary) {
  28.918 -    case CHWALL:
  28.919 -        fprintf(file, "SECONDARY              CHWALL\n");
  28.920 -        break;
  28.921 -
  28.922 -    case STE:
  28.923 -        fprintf(file, "SECONDARY              STE\n");
  28.924 -        break;
  28.925 -
  28.926 -    default:
  28.927 -        fprintf(file, "SECONDARY              NULL\n");
  28.928 -        break;
  28.929 -    }
  28.930 -    fprintf(file, "\n");
  28.931 -
  28.932 -    /* first labels to ssid mappings */
  28.933 -    if (have_chwall) {
  28.934 -        for (e = chwall_ssid_head.tqh_first; e != NULL;
  28.935 -             e = e->entries.tqe_next) {
  28.936 -            fprintf(file, "LABEL->SSID %s CHWALL %-25s %8x\n",
  28.937 -                    (e->type ==
  28.938 -                     VM) ? "VM " : ((e->type == RES) ? "RES" : "ANY"),
  28.939 -                    e->name, e->num);
  28.940 -        }
  28.941 -        fprintf(file, "\n");
  28.942 -    }
  28.943 -    if (have_ste) {
  28.944 -        for (e = ste_ssid_head.tqh_first; e != NULL;
  28.945 -             e = e->entries.tqe_next) {
  28.946 -            fprintf(file, "LABEL->SSID %s STE    %-25s %8x\n",
  28.947 -                    (e->type ==
  28.948 -                     VM) ? "VM " : ((e->type == RES) ? "RES" : "ANY"),
  28.949 -                    e->name, e->num);
  28.950 -        }
  28.951 -        fprintf(file, "\n");
  28.952 -    }
  28.953 -
  28.954 -    /* second ssid to type mappings */
  28.955 -    if (have_chwall) {
  28.956 -        for (e = chwall_ssid_head.tqh_first; e != NULL;
  28.957 -             e = e->entries.tqe_next) {
  28.958 -            if (e->is_ref)
  28.959 -                continue;
  28.960 -
  28.961 -            fprintf(file, "SSID->TYPE CHWALL      %08x", e->num);
  28.962 -
  28.963 -            for (i = 0; i < max_chwall_types; i++)
  28.964 -                if (e->row[i])
  28.965 -                    fprintf(file, " %s", type_by_mapping(&chwall_head, i));
  28.966 -
  28.967 -            fprintf(file, "\n");
  28.968 -        }
  28.969 -        fprintf(file, "\n");
  28.970 -    }
  28.971 -    if (have_ste) {
  28.972 -        for (e = ste_ssid_head.tqh_first; e != NULL;
  28.973 -             e = e->entries.tqe_next) {
  28.974 -            if (e->is_ref)
  28.975 -                continue;
  28.976 -
  28.977 -            fprintf(file, "SSID->TYPE STE         %08x", e->num);
  28.978 -
  28.979 -            for (i = 0; i < max_ste_types; i++)
  28.980 -                if (e->row[i])
  28.981 -                    fprintf(file, " %s", type_by_mapping(&ste_head, i));
  28.982 -
  28.983 -            fprintf(file, "\n");
  28.984 -        }
  28.985 -        fprintf(file, "\n");
  28.986 -    }
  28.987 -    /* third type mappings */
  28.988 -    if (have_chwall) {
  28.989 -        for (t = chwall_head.tqh_first; t != NULL; t = t->entries.tqe_next) {
  28.990 -            fprintf(file, "TYPE CHWALL            %-25s %8x\n",
  28.991 -                    t->name, t->mapping);
  28.992 -        }
  28.993 -        fprintf(file, "\n");
  28.994 -    }
  28.995 -    if (have_ste) {
  28.996 -        for (t = ste_head.tqh_first; t != NULL; t = t->entries.tqe_next) {
  28.997 -            fprintf(file, "TYPE STE               %-25s %8x\n",
  28.998 -                    t->name, t->mapping);
  28.999 -        }
 28.1000 -        fprintf(file, "\n");
 28.1001 -    }
 28.1002 -    fclose(file);
 28.1003 -    return 0;
 28.1004 -}
 28.1005 -
 28.1006 -
 28.1007 -unsigned char *write_policy_reference_binary(u_int32_t * len_pr)
 28.1008 -{
 28.1009 -    unsigned char *buf, *ptr;
 28.1010 -    struct acm_policy_reference_buffer *pr_header;
 28.1011 -    u_int32_t len;
 28.1012 -    u_int32_t name_len;
 28.1013 -
 28.1014 -    if (policy_reference_name == NULL) {
 28.1015 -        printf("ERROR: No policy reference name found.\n");
 28.1016 -        exit(EXIT_FAILURE);
 28.1017 -    }
 28.1018 -    name_len = strlen(policy_reference_name) + 1; /* strend '\0' */
 28.1019 -    len = sizeof(struct acm_policy_reference_buffer) + name_len;
 28.1020 -    len = (len + 7) & ~7; /* Alignment.  */
 28.1021 -    buf = malloc(len);
 28.1022 -    ptr = buf;
 28.1023 -
 28.1024 -    if (!buf) {
 28.1025 -        printf
 28.1026 -            ("ERROR: out of memory allocating label reference buffer.\n");
 28.1027 -        exit(EXIT_FAILURE);
 28.1028 -    }
 28.1029 -    memset (buf, 0, len);
 28.1030 -    pr_header = (struct acm_policy_reference_buffer *) buf;
 28.1031 -    pr_header->len = htonl(name_len);
 28.1032 -    ptr += sizeof(struct acm_policy_reference_buffer);
 28.1033 -    strcpy((char *) ptr, policy_reference_name);
 28.1034 -
 28.1035 -    (*len_pr) = len;
 28.1036 -    return buf;
 28.1037 -}
 28.1038 -
 28.1039 -
 28.1040 -unsigned char *write_chwall_binary(u_int32_t * len_chwall)
 28.1041 -{
 28.1042 -    unsigned char *buf, *ptr;
 28.1043 -    struct acm_chwall_policy_buffer *chwall_header;
 28.1044 -    u_int32_t len;
 28.1045 -    struct ssid_entry *e;
 28.1046 -    int i;
 28.1047 -
 28.1048 -    if (!have_chwall)
 28.1049 -        return NULL;
 28.1050 -
 28.1051 -    len = sizeof(struct acm_chwall_policy_buffer) +
 28.1052 -        sizeof(type_t) * max_chwall_types * max_chwall_ssids +
 28.1053 -        sizeof(type_t) * max_chwall_types * max_conflictsets;
 28.1054 -
 28.1055 -    buf = malloc(len);
 28.1056 -    ptr = buf;
 28.1057 -
 28.1058 -    if (!buf) {
 28.1059 -        printf("ERROR: out of memory allocating chwall buffer.\n");
 28.1060 -        exit(EXIT_FAILURE);
 28.1061 -    }
 28.1062 -    /* chwall has 3 parts : header, types, conflictsets */
 28.1063 -
 28.1064 -    chwall_header = (struct acm_chwall_policy_buffer *) buf;
 28.1065 -    chwall_header->chwall_max_types = htonl(max_chwall_types);
 28.1066 -    chwall_header->chwall_max_ssidrefs = htonl(max_chwall_ssids);
 28.1067 -    chwall_header->policy_code = htonl(ACM_CHINESE_WALL_POLICY);
 28.1068 -    chwall_header->policy_version = htonl(ACM_CHWALL_VERSION);
 28.1069 -    chwall_header->chwall_ssid_offset =
 28.1070 -        htonl(sizeof(struct acm_chwall_policy_buffer));
 28.1071 -    chwall_header->chwall_max_conflictsets = htonl(max_conflictsets);
 28.1072 -    chwall_header->chwall_conflict_sets_offset =
 28.1073 -        htonl(ntohl(chwall_header->chwall_ssid_offset) +
 28.1074 -              sizeof(domaintype_t) * max_chwall_ssids * max_chwall_types);
 28.1075 -    chwall_header->chwall_running_types_offset = 0;
 28.1076 -    chwall_header->chwall_conflict_aggregate_offset = 0;
 28.1077 -    ptr += sizeof(struct acm_chwall_policy_buffer);
 28.1078 -
 28.1079 -    /* types */
 28.1080 -    for (e = chwall_ssid_head.tqh_first; e != NULL;
 28.1081 -         e = e->entries.tqe_next) {
 28.1082 -        if (e->is_ref)
 28.1083 -            continue;
 28.1084 -
 28.1085 -        for (i = 0; i < max_chwall_types; i++)
 28.1086 -            ((type_t *) ptr)[i] = htons((type_t) e->row[i]);
 28.1087 -
 28.1088 -        ptr += sizeof(type_t) * max_chwall_types;
 28.1089 -    }
 28.1090 -
 28.1091 -    /* conflictsets */
 28.1092 -    for (e = conflictsets_head.tqh_first; e != NULL;
 28.1093 -         e = e->entries.tqe_next) {
 28.1094 -        for (i = 0; i < max_chwall_types; i++)
 28.1095 -            ((type_t *) ptr)[i] = htons((type_t) e->row[i]);
 28.1096 -
 28.1097 -        ptr += sizeof(type_t) * max_chwall_types;
 28.1098 -    }
 28.1099 -
 28.1100 -    if ((ptr - buf) != len) {
 28.1101 -        printf("ERROR: wrong lengths in %s.\n", __func__);
 28.1102 -        exit(EXIT_FAILURE);
 28.1103 -    }
 28.1104 -
 28.1105 -    (*len_chwall) = len;
 28.1106 -    return buf;
 28.1107 -}
 28.1108 -
 28.1109 -unsigned char *write_ste_binary(u_int32_t * len_ste)
 28.1110 -{
 28.1111 -    unsigned char *buf, *ptr;
 28.1112 -    struct acm_ste_policy_buffer *ste_header;
 28.1113 -    struct ssid_entry *e;
 28.1114 -    u_int32_t len;
 28.1115 -    int i;
 28.1116 -
 28.1117 -    if (!have_ste)
 28.1118 -        return NULL;
 28.1119 -
 28.1120 -    len = sizeof(struct acm_ste_policy_buffer) +
 28.1121 -        sizeof(type_t) * max_ste_types * max_ste_ssids;
 28.1122 -
 28.1123 -    buf = malloc(len);
 28.1124 -    ptr = buf;
 28.1125 -
 28.1126 -    if (!buf) {
 28.1127 -        printf("ERROR: out of memory allocating chwall buffer.\n");
 28.1128 -        exit(EXIT_FAILURE);
 28.1129 -    }
 28.1130 -
 28.1131 -    /* fill buffer */
 28.1132 -    ste_header = (struct acm_ste_policy_buffer *) buf;
 28.1133 -    ste_header->policy_version = htonl(ACM_STE_VERSION);
 28.1134 -    ste_header->policy_code = htonl(ACM_SIMPLE_TYPE_ENFORCEMENT_POLICY);
 28.1135 -    ste_header->ste_max_types = htonl(max_ste_types);
 28.1136 -    ste_header->ste_max_ssidrefs = htonl(max_ste_ssids);
 28.1137 -    ste_header->ste_ssid_offset =
 28.1138 -        htonl(sizeof(struct acm_ste_policy_buffer));
 28.1139 -
 28.1140 -    ptr += sizeof(struct acm_ste_policy_buffer);
 28.1141 -
 28.1142 -    /* types */
 28.1143 -    for (e = ste_ssid_head.tqh_first; e != NULL; e = e->entries.tqe_next) {
 28.1144 -        if (e->is_ref)
 28.1145 -            continue;
 28.1146 -
 28.1147 -        for (i = 0; i < max_ste_types; i++)
 28.1148 -            ((type_t *) ptr)[i] = htons((type_t) e->row[i]);
 28.1149 -
 28.1150 -        ptr += sizeof(type_t) * max_ste_types;
 28.1151 -    }
 28.1152 -
 28.1153 -    if ((ptr - buf) != len) {
 28.1154 -        printf("ERROR: wrong lengths in %s.\n", __func__);
 28.1155 -        exit(EXIT_FAILURE);
 28.1156 -    }
 28.1157 -    (*len_ste) = len;
 28.1158 -    return buf;                 /* for now */
 28.1159 -}
 28.1160 -
 28.1161 -static ssize_t write_padded(int fd, const void *buf, size_t count)
 28.1162 -{
 28.1163 -    int rc;
 28.1164 -    static const char padding[7] = {0,0,0,0,0,0,0};
 28.1165 -    unsigned int len = ROUND8(count) - count;
 28.1166 -
 28.1167 -    rc = write(fd, buf, count);
 28.1168 -    if (rc == count && len > 0) {
 28.1169 -        write(fd, padding, len);
 28.1170 -    }
 28.1171 -    return rc;
 28.1172 -}
 28.1173 -
 28.1174 -int write_binary(char *filename)
 28.1175 -{
 28.1176 -    struct acm_policy_buffer header;
 28.1177 -    unsigned char *ste_buffer = NULL, *chwall_buffer =
 28.1178 -        NULL, *policy_reference_buffer = NULL;
 28.1179 -    u_int32_t len;
 28.1180 -    int fd, ret = 0;
 28.1181 -    uint32_t major = 0, minor = 0;
 28.1182 -
 28.1183 -    u_int32_t len_ste = 0, len_chwall = 0, len_pr = 0;  /* length of policy components */
 28.1184 -
 28.1185 -    if (policy_version_string)
 28.1186 -        sscanf(policy_version_string,"%d.%d", &major, &minor);
 28.1187 -
 28.1188 -    /* open binary file */
 28.1189 -    if ((fd =
 28.1190 -         open(filename, O_WRONLY | O_CREAT | O_TRUNC,
 28.1191 -              S_IRUSR | S_IWUSR)) <= 0) {
 28.1192 -        ret = -EIO;
 28.1193 -        goto out1;
 28.1194 -    }
 28.1195 -    policy_reference_buffer = write_policy_reference_binary(&len_pr);
 28.1196 -    ste_buffer = write_ste_binary(&len_ste);
 28.1197 -    chwall_buffer = write_chwall_binary(&len_chwall);
 28.1198 -
 28.1199 -    /* determine primary component (default chwall) */
 28.1200 -    header.policy_version = htonl(ACM_POLICY_VERSION);
 28.1201 -    header.magic = htonl(ACM_MAGIC);
 28.1202 -    header.xml_pol_version.major = htonl(major);
 28.1203 -    header.xml_pol_version.minor = htonl(minor);
 28.1204 -
 28.1205 -    len = ROUND8(sizeof(struct acm_policy_buffer));
 28.1206 -    if (have_chwall)
 28.1207 -        len += ROUND8(len_chwall);
 28.1208 -    if (have_ste)
 28.1209 -        len += ROUND8(len_ste);
 28.1210 -    len += ROUND8(len_pr);           /* policy reference is mandatory */
 28.1211 -    header.len = htonl(len);
 28.1212 -
 28.1213 -    header.policy_reference_offset =
 28.1214 -        htonl(ROUND8(sizeof(struct acm_policy_buffer)));
 28.1215 -
 28.1216 -    header.primary_buffer_offset =
 28.1217 -        htonl(ROUND8(sizeof(struct acm_policy_buffer)) +
 28.1218 -              ROUND8(len_pr));
 28.1219 -    if (primary == CHWALL) {
 28.1220 -        header.primary_policy_code = htonl(ACM_CHINESE_WALL_POLICY);
 28.1221 -        header.secondary_buffer_offset =
 28.1222 -            htonl(ROUND8(sizeof(struct acm_policy_buffer)) +
 28.1223 -                  ROUND8(len_pr) +
 28.1224 -                  ROUND8(len_chwall));
 28.1225 -    } else if (primary == STE) {
 28.1226 -        header.primary_policy_code =
 28.1227 -            htonl(ACM_SIMPLE_TYPE_ENFORCEMENT_POLICY);
 28.1228 -        header.secondary_buffer_offset =
 28.1229 -            htonl(ROUND8(sizeof(struct acm_policy_buffer)) +
 28.1230 -                  ROUND8(len_pr) +
 28.1231 -                  ROUND8(len_ste));
 28.1232 -    } else {
 28.1233 -        /* null policy */
 28.1234 -        header.primary_policy_code = htonl(ACM_NULL_POLICY);
 28.1235 -        header.secondary_buffer_offset = header.primary_buffer_offset;
 28.1236 -    }
 28.1237 -
 28.1238 -    if (secondary == CHWALL)
 28.1239 -        header.secondary_policy_code = htonl(ACM_CHINESE_WALL_POLICY);
 28.1240 -    else if (secondary == STE)
 28.1241 -        header.secondary_policy_code =
 28.1242 -            htonl(ACM_SIMPLE_TYPE_ENFORCEMENT_POLICY);
 28.1243 -    else
 28.1244 -        header.secondary_policy_code = htonl(ACM_NULL_POLICY);
 28.1245 -
 28.1246 -    if (write_padded(fd, (void *) &header, sizeof(struct acm_policy_buffer))
 28.1247 -        != sizeof(struct acm_policy_buffer)) {
 28.1248 -        ret = -EIO;
 28.1249 -        goto out1;
 28.1250 -    }
 28.1251 -
 28.1252 -    /* write label reference name */
 28.1253 -    if (write_padded(fd, policy_reference_buffer, len_pr) != len_pr) {
 28.1254 -        ret = -EIO;
 28.1255 -        goto out1;
 28.1256 -    }
 28.1257 -    /* write primary policy component */
 28.1258 -    if (primary == CHWALL) {
 28.1259 -        if (write_padded(fd, chwall_buffer, len_chwall) != len_chwall) {
 28.1260 -            ret = -EIO;
 28.1261 -            goto out1;
 28.1262 -        }
 28.1263 -    } else if (primary == STE) {
 28.1264 -        if (write_padded(fd, ste_buffer, len_ste) != len_ste) {
 28.1265 -            ret = -EIO;
 28.1266 -            goto out1;
 28.1267 -        }
 28.1268 -    } else;                     /* NULL POLICY has no policy data */
 28.1269 -
 28.1270 -    /* write secondary policy component */
 28.1271 -    if (secondary == CHWALL) {
 28.1272 -        if (write_padded(fd, chwall_buffer, len_chwall) != len_chwall) {
 28.1273 -            ret = -EIO;
 28.1274 -            goto out1;
 28.1275 -        }
 28.1276 -    } else if (secondary == STE) {
 28.1277 -        if (write_padded(fd, ste_buffer, len_ste) != len_ste) {
 28.1278 -            ret = -EIO;
 28.1279 -            goto out1;
 28.1280 -        }
 28.1281 -    } else;                     /* NULL POLICY has no policy data */
 28.1282 -
 28.1283 -  out1:
 28.1284 -    /* cleanup */
 28.1285 -    if (policy_reference_buffer)
 28.1286 -        free(policy_reference_buffer);
 28.1287 -    if (chwall_buffer)
 28.1288 -        free(chwall_buffer);
 28.1289 -    if (ste_buffer)
 28.1290 -        free(ste_buffer);
 28.1291 -    close(fd);
 28.1292 -    return ret;
 28.1293 -}
 28.1294 -
 28.1295 -int is_valid(xmlDocPtr doc)
 28.1296 -{
 28.1297 -    int err = 0;
 28.1298 -    xmlSchemaPtr schema_ctxt = NULL;
 28.1299 -    xmlSchemaParserCtxtPtr schemaparser_ctxt = NULL;
 28.1300 -    xmlSchemaValidCtxtPtr schemavalid_ctxt = NULL;
 28.1301 -
 28.1302 -    schemaparser_ctxt = xmlSchemaNewParserCtxt(schema_filename);
 28.1303 -    schema_ctxt = xmlSchemaParse(schemaparser_ctxt);
 28.1304 -    schemavalid_ctxt = xmlSchemaNewValidCtxt(schema_ctxt);
 28.1305 -
 28.1306 -#ifdef VALIDATE_SCHEMA
 28.1307 -    /* only tested to be available from libxml2-2.6.20 upwards */
 28.1308 -    if ((err = xmlSchemaIsValid(schemavalid_ctxt)) != 1) {
 28.1309 -        printf("ERROR: Invalid schema file %s (err=%d)\n",
 28.1310 -               schema_filename, err);
 28.1311 -        err = -EIO;
 28.1312 -        goto out;
 28.1313 -    } else
 28.1314 -        printf("XML Schema %s valid.\n", schema_filename);
 28.1315 -#endif
 28.1316 -    if ((err = xmlSchemaValidateDoc(schemavalid_ctxt, doc))) {
 28.1317 -        err = -EIO;
 28.1318 -        goto out;
 28.1319 -    }
 28.1320 -  out:
 28.1321 -    xmlSchemaFreeValidCtxt(schemavalid_ctxt);
 28.1322 -    xmlSchemaFreeParserCtxt(schemaparser_ctxt);
 28.1323 -    xmlSchemaFree(schema_ctxt);
 28.1324 -    return (err != 0) ? 0 : 1;
 28.1325 -}
 28.1326 -
 28.1327 -int main(int argc, char **argv)
 28.1328 -{
 28.1329 -    xmlDocPtr policydoc = NULL;
 28.1330 -
 28.1331 -    int err = EXIT_FAILURE;
 28.1332 -
 28.1333 -    char *file_prefix;
 28.1334 -    int prefix_len;
 28.1335 -
 28.1336 -    int opt_char;
 28.1337 -    char *policy_dir = POLICY_DIR;
 28.1338 -
 28.1339 -    if (ACM_POLICY_VERSION != WRITTEN_AGAINST_ACM_POLICY_VERSION) {
 28.1340 -        printf
 28.1341 -            ("ERROR: This program was written against an older ACM version.\n");
 28.1342 -        printf("ERROR: ACM_POLICY_VERSION=%d, WRITTEN AGAINST= %d.\n",
 28.1343 -               ACM_POLICY_VERSION, WRITTEN_AGAINST_ACM_POLICY_VERSION);
 28.1344 -        exit(EXIT_FAILURE);
 28.1345 -    }
 28.1346 -
 28.1347 -    while ((opt_char = getopt(argc, argv, "d:")) != -1) {
 28.1348 -        switch (opt_char) {
 28.1349 -        case 'd':
 28.1350 -            policy_dir = malloc(strlen(optarg) + 2);    /* null terminator and possibly "/" */
 28.1351 -            if (!policy_dir) {
 28.1352 -                printf("ERROR allocating directory name memory.\n");
 28.1353 -                exit(EXIT_FAILURE);
 28.1354 -            }
 28.1355 -            strcpy(policy_dir, optarg);
 28.1356 -            if (policy_dir[strlen(policy_dir) - 1] != '/')
 28.1357 -                strcat(policy_dir, "/");
 28.1358 -            break;
 28.1359 -
 28.1360 -        default:
 28.1361 -            usage(basename(argv[0]));
 28.1362 -        }
 28.1363 -    }
 28.1364 -
 28.1365 -    if ((argc - optind) != 1)
 28.1366 -        usage(basename(argv[0]));
 28.1367 -
 28.1368 -    printf("arg=%s\n", argv[optind]);
 28.1369 -
 28.1370 -    prefix_len =
 28.1371 -        strlen(policy_dir) + strlen(argv[optind]) +
 28.1372 -        1 /* null terminator */ ;
 28.1373 -
 28.1374 -    file_prefix = malloc(prefix_len);
 28.1375 -    policy_filename = malloc(prefix_len + strlen(POLICY_EXTENSION));
 28.1376 -    binary_filename = malloc(prefix_len + strlen(BINARY_EXTENSION));
 28.1377 -    mapping_filename = malloc(prefix_len + strlen(MAPPING_EXTENSION));
 28.1378 -    schema_filename =
 28.1379 -        malloc(strlen(policy_dir) + strlen(SCHEMA_FILENAME) + 1);
 28.1380 -
 28.1381 -    if (!file_prefix || !policy_filename ||
 28.1382 -        !binary_filename || !mapping_filename || !schema_filename) {
 28.1383 -        printf("ERROR allocating file name memory.\n");
 28.1384 -        goto out2;
 28.1385 -    }
 28.1386 -
 28.1387 -    /* create input/output filenames out of prefix */
 28.1388 -    strcpy(file_prefix, policy_dir);
 28.1389 -    strcat(file_prefix, argv[optind]);
 28.1390 -
 28.1391 -    strcpy(policy_filename, file_prefix);
 28.1392 -    strcpy(binary_filename, file_prefix);
 28.1393 -    strcpy(mapping_filename, file_prefix);
 28.1394 -
 28.1395 -    strcat(policy_filename, POLICY_EXTENSION);
 28.1396 -    strcat(binary_filename, BINARY_EXTENSION);
 28.1397 -    strcat(mapping_filename, MAPPING_EXTENSION);
 28.1398 -
 28.1399 -    strcpy(schema_filename, policy_dir);
 28.1400 -    strcat(schema_filename, SCHEMA_FILENAME);
 28.1401 -
 28.1402 -    policydoc = xmlParseFile(policy_filename);
 28.1403 -
 28.1404 -    if (policydoc == NULL) {
 28.1405 -        printf("Error: could not parse file %s.\n", argv[optind]);
 28.1406 -        goto out;
 28.1407 -    }
 28.1408 -
 28.1409 -    printf("Validating policy file %s...\n", policy_filename);
 28.1410 -
 28.1411 -    if (!is_valid(policydoc)) {
 28.1412 -        printf("ERROR: Failed schema-validation for file %s (err=%d)\n",
 28.1413 -               policy_filename, err);
 28.1414 -        goto out;
 28.1415 -    }
 28.1416 -
 28.1417 -    /* create mappings */
 28.1418 -    create_mappings(policydoc);
 28.1419 -
 28.1420 -    /* write label mapping file */
 28.1421 -    if (write_mapping(mapping_filename)) {
 28.1422 -        printf("ERROR: writing mapping file %s.\n", mapping_filename);
 28.1423 -        goto out;
 28.1424 -    }
 28.1425 -
 28.1426 -    /* write binary file */
 28.1427 -    if (write_binary(binary_filename)) {
 28.1428 -        printf("ERROR: writing binary file %s.\n", binary_filename);
 28.1429 -        goto out;
 28.1430 -    }
 28.1431 -    err = EXIT_SUCCESS;
 28.1432 -    /* write stats */
 28.1433 -    if (have_chwall) {
 28.1434 -        printf("Max chwall labels:  %u\n", max_chwall_labels);
 28.1435 -        printf("Max chwall-types:   %u\n", max_chwall_types);
 28.1436 -        printf("Max chwall-ssids:   %u\n", max_chwall_ssids);
 28.1437 -    }
 28.1438 -
 28.1439 -    if (have_ste) {
 28.1440 -        printf("Max ste labels:     %u\n", max_ste_labels);
 28.1441 -        printf("Max ste-types:      %u\n", max_ste_types);
 28.1442 -        printf("Max ste-ssids:      %u\n", max_ste_ssids);
 28.1443 -    }
 28.1444 -    /* cleanup */
 28.1445 -  out:
 28.1446 -    xmlFreeDoc(policydoc);
 28.1447 -  out2:
 28.1448 -    xmlCleanupParser();
 28.1449 -    return err;
 28.1450 -}
 28.1451 -
 28.1452 -/*
 28.1453 - * Local variables:
 28.1454 - * mode: C
 28.1455 - * c-set-style: "BSD"
 28.1456 - * c-basic-offset: 4
 28.1457 - * tab-width: 4
 28.1458 - * indent-tabs-mode: nil
 28.1459 - * End:
 28.1460 - */
    29.1 --- a/tools/security/secpol_xml2bin.h	Tue Dec 04 22:54:58 2007 +0000
    29.2 +++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
    29.3 @@ -1,166 +0,0 @@
    29.4 -/****************************************************************
    29.5 - * secpol_xml2bin.h
    29.6 - *
    29.7 - * Copyright (C) 2005 IBM Corporation
    29.8 - *
    29.9 - * Authors:
   29.10 - * Reiner Sailer <sailer@watson.ibm.com>
   29.11 - *
   29.12 - * This program is free software; you can redistribute it and/or
   29.13 - * modify it under the terms of the GNU General Public License as
   29.14 - * published by the Free Software Foundation, version 2 of the
   29.15 - * License.
   29.16 - *
   29.17 - */
   29.18 -#define POLICY_DIR          			"/etc/xen/acm-security/policies/"
   29.19 -#define POLICY_EXTENSION    			"-security_policy.xml"
   29.20 -#define BINARY_EXTENSION    			".bin"
   29.21 -#define MAPPING_EXTENSION   			".map"
   29.22 -#define PRIMARY_COMPONENT_ATTR_NAME 	"order"
   29.23 -#define BOOTSTRAP_LABEL_ATTR_NAME   	"bootstrap"
   29.24 -#define PRIMARY_COMPONENT   			"PrimaryPolicyComponent"
   29.25 -#define SCHEMA_FILENAME     			"security_policy.xsd"
   29.26 -
   29.27 -/* basic states (used as 1 << X) */
   29.28 -enum {
   29.29 -    XML2BIN_SECPOL = 0,   /* policy tokens */
   29.30 -    XML2BIN_STE,
   29.31 -    XML2BIN_CHWALL,
   29.32 -    XML2BIN_CONFLICTSETS,
   29.33 -    XML2BIN_CSTYPE,
   29.34 -    XML2BIN_POLICYHEADER,
   29.35 -    XML2BIN_NSURL,
   29.36 -    XML2BIN_POLICYNAME,
   29.37 -    XML2BIN_URL,
   29.38 -    XML2BIN_REFERENCE,
   29.39 -    XML2BIN_DATE,
   29.40 -    XML2BIN_VERSION,
   29.41 -    XML2BIN_FROMPOLICY,
   29.42 -
   29.43 -    XML2BIN_LABELTEMPLATE,  /* label tokens */
   29.44 -    XML2BIN_SUBJECTS,
   29.45 -    XML2BIN_OBJECTS,
   29.46 -    XML2BIN_VM,
   29.47 -    XML2BIN_RES,
   29.48 -    XML2BIN_NAME,
   29.49 -
   29.50 -    XML2BIN_STETYPES,
   29.51 -    XML2BIN_CHWALLTYPES,
   29.52 -    XML2BIN_TYPE,
   29.53 -    XML2BIN_TEXT,
   29.54 -    XML2BIN_COMMENT,
   29.55 -    ENDOFLIST_POS /* keep last ! */
   29.56 -};
   29.57 -
   29.58 -/* type "data type" (currently 16bit) */
   29.59 -typedef u_int16_t type_t;
   29.60 -
   29.61 -/* list of known elements and token equivalent  *
   29.62 - * state constants and token positions must be  *
   29.63 - * in sync for correct state recognition        */
   29.64 -
   29.65 -char *token[32] =                       /* parser triggers */
   29.66 -{
   29.67 -    [XML2BIN_SECPOL]        = "SecurityPolicyDefinition", /* policy xml */
   29.68 -    [XML2BIN_STE]           = "SimpleTypeEnforcement",
   29.69 -    [XML2BIN_CHWALL]        = "ChineseWall",
   29.70 -    [XML2BIN_CONFLICTSETS]  = "ConflictSets",
   29.71 -    [XML2BIN_CSTYPE]        = "Conflict",
   29.72 -    [XML2BIN_POLICYHEADER]  = "PolicyHeader",
   29.73 -    [XML2BIN_NSURL]         = "NameSpaceUrl",
   29.74 -    [XML2BIN_POLICYNAME]    = "PolicyName",
   29.75 -    [XML2BIN_URL]           = "PolicyUrl",
   29.76 -    [XML2BIN_REFERENCE]     = "Reference",
   29.77 -    [XML2BIN_DATE]          = "Date",
   29.78 -    [XML2BIN_VERSION]       = "Version",
   29.79 -    [XML2BIN_FROMPOLICY]    = "FromPolicy",
   29.80 -
   29.81 -    [XML2BIN_LABELTEMPLATE] = "SecurityLabelTemplate", /* label-template xml */
   29.82 -    [XML2BIN_SUBJECTS]      = "SubjectLabels",
   29.83 -    [XML2BIN_OBJECTS]       = "ObjectLabels",
   29.84 -    [XML2BIN_VM]            = "VirtualMachineLabel",
   29.85 -    [XML2BIN_RES]           = "ResourceLabel",
   29.86 -    [XML2BIN_NAME]          = "Name",
   29.87 -
   29.88 -    [XML2BIN_STETYPES]      = "SimpleTypeEnforcementTypes", /* common tags */
   29.89 -    [XML2BIN_CHWALLTYPES]   = "ChineseWallTypes",
   29.90 -    [XML2BIN_TYPE]          = "Type",
   29.91 -    [XML2BIN_TEXT]          = "text",
   29.92 -    [XML2BIN_COMMENT]       = "comment",
   29.93 -    [ENDOFLIST_POS]         = NULL  /* End of LIST, adapt ENDOFLIST_POS
   29.94 -                                       when adding entries */
   29.95 -};
   29.96 -
   29.97 -/* important combined states */
   29.98 -#define XML2BIN_NULL 		0
   29.99 -
  29.100 -/* policy xml parsing states _S */
  29.101 -
  29.102 -/* e.g., here we are in a <secpol,ste,stetypes> environment,  *
  29.103 - * so when finding a type element, we know where to put it    */
  29.104 -#define XML2BIN_stetype_S ((1 << XML2BIN_SECPOL) | \
  29.105 -                 (1 << XML2BIN_STE) | \
  29.106 -                 (1 << XML2BIN_STETYPES))
  29.107 -
  29.108 -#define XML2BIN_chwalltype_S ((1 << XML2BIN_SECPOL) | \
  29.109 -                 (1 << XML2BIN_CHWALL) | \
  29.110 -                 (1 << XML2BIN_CHWALLTYPES))
  29.111 -
  29.112 -#define XML2BIN_conflictset_S ((1 << XML2BIN_SECPOL) | \
  29.113 -                 (1 << XML2BIN_CHWALL) | \
  29.114 -                 (1 << XML2BIN_CONFLICTSETS))
  29.115 -
  29.116 -#define XML2BIN_conflictsettype_S ((1 << XML2BIN_SECPOL) | \
  29.117 -                 (1 << XML2BIN_CHWALL) | \
  29.118 -                 (1 << XML2BIN_CONFLICTSETS) | \
  29.119 -                 (1 << XML2BIN_CSTYPE))
  29.120 -
  29.121 -#define XML2BIN_PN_S ((1 << XML2BIN_SECPOL) | \
  29.122 -                 (1 << XML2BIN_POLICYHEADER))
  29.123 -
  29.124 -#define XML2BIN_PN_frompolicy_S ((1 << XML2BIN_SECPOL) | \
  29.125 -                 (1 << XML2BIN_POLICYHEADER) | \
  29.126 -                 (1 << XML2BIN_FROMPOLICY))
  29.127 -
  29.128 -/* label xml states */
  29.129 -#define XML2BIN_VM_S ((1 << XML2BIN_SECPOL) | \
  29.130 -                 (1 << XML2BIN_LABELTEMPLATE) |	\
  29.131 -                 (1 << XML2BIN_SUBJECTS) | \
  29.132 -                 (1 << XML2BIN_VM))
  29.133 -
  29.134 -#define XML2BIN_RES_S ((1 << XML2BIN_SECPOL) | \
  29.135 -                 (1 << XML2BIN_LABELTEMPLATE) |	\
  29.136 -                 (1 << XML2BIN_OBJECTS) | \
  29.137 -                 (1 << XML2BIN_RES))
  29.138 -
  29.139 -#define XML2BIN_VM_STE_S ((1 << XML2BIN_SECPOL) | \
  29.140 -                 (1 << XML2BIN_LABELTEMPLATE) |	\
  29.141 -                 (1 << XML2BIN_SUBJECTS) | \
  29.142 -                 (1 << XML2BIN_VM) | \
  29.143 -                 (1 << XML2BIN_STETYPES))
  29.144 -
  29.145 -#define XML2BIN_VM_CHWALL_S ((1 << XML2BIN_SECPOL) | \
  29.146 -                 (1 << XML2BIN_LABELTEMPLATE) | \
  29.147 -                 (1 << XML2BIN_SUBJECTS) | \
  29.148 -                 (1 << XML2BIN_VM) | \
  29.149 -                 (1 << XML2BIN_CHWALLTYPES))
  29.150 -
  29.151 -#define XML2BIN_RES_STE_S ((1 << XML2BIN_SECPOL) | \
  29.152 -                 (1 << XML2BIN_LABELTEMPLATE) | \
  29.153 -                 (1 << XML2BIN_OBJECTS) | \
  29.154 -                 (1 << XML2BIN_RES) | \
  29.155 -                 (1 << XML2BIN_STETYPES))
  29.156 -
  29.157 -
  29.158 -/* check versions of headers against which the
  29.159 - * xml2bin translation tool was written
  29.160 - */
  29.161 -
  29.162 -/* protects from unnoticed changes in struct acm_policy_buffer */
  29.163 -#define WRITTEN_AGAINST_ACM_POLICY_VERSION  3
  29.164 -
  29.165 -/* protects from unnoticed changes in struct acm_chwall_policy_buffer */
  29.166 -#define WRITTEN_AGAINST_ACM_CHWALL_VERSION  1
  29.167 -
  29.168 -/* protects from unnoticed changes in struct acm_ste_policy_buffer */
  29.169 -#define WRITTEN_AGAINST_ACM_STE_VERSION     1
    30.1 --- a/tools/xm-test/lib/XmTestLib/acm.py	Tue Dec 04 22:54:58 2007 +0000
    30.2 +++ b/tools/xm-test/lib/XmTestLib/acm.py	Wed Dec 05 09:44:20 2007 +0000
    30.3 @@ -34,56 +34,20 @@ acm_verbose = False
    30.4  def isACMEnabled():
    30.5      return security.on()
    30.6  
    30.7 -
    30.8 -def getSystemPolicyName():
    30.9 -    s,o = traceCommand("xm getpolicy")
   30.10 -    m = re.compile("Policy name[\s]*: ([A-z\-]+)").search(o)
   30.11 -    if m:
   30.12 -        polname = m.group(1)
   30.13 -        return polname
   30.14 -    return ""
   30.15 -
   30.16 -
   30.17 -def ACMLoadPolicy_XenAPI(policy='xm-test'):
   30.18 -    polname = getSystemPolicyName()
   30.19 -    if polname != policy:
   30.20 -        # Try it, maybe it's not activated
   30.21 -        traceCommand("xm setpolicy %s %s" %
   30.22 -                     (xsconstants.ACM_POLICY_ID, policy))
   30.23 -        polname = getSystemPolicyName()
   30.24 -        if polname != policy:
   30.25 -            FAIL("Need to have a system with no or policy '%s' active, "
   30.26 -                 "not %s" % (policy,polname))
   30.27 -        else:
   30.28 -            s, o = traceCommand("xm activatepolicy --load")
   30.29 -    else:
   30.30 -        s, o = traceCommand("xm activatepolicy --load")
   30.31 -        if not re.search("Successfully", o):
   30.32 -            FAIL("Could not set the policy '%s'." % policy)
   30.33 -
   30.34 -
   30.35 -def ACMLoadPolicy(policy='xm-test'):
   30.36 -    from xen.xm import main
   30.37 -    if main.serverType == main.SERVER_XEN_API:
   30.38 -        ACMLoadPolicy_XenAPI()
   30.39 -    else:
   30.40 -        cmd='xm dumppolicy | grep -E "^POLICY REFERENCE = ' + policy + '.$"'
   30.41 -        s, o = traceCommand(cmd)
   30.42 -        if o != "":
   30.43 -            return
   30.44 -        s, o = traceCommand("xm makepolicy %s" % (policy))
   30.45 -        if s != 0:
   30.46 -            FAIL("Need to be able to do 'xm makepolicy %s' but could not" %
   30.47 -                 (policy))
   30.48 -        s, o = traceCommand("xm loadpolicy %s" % (policy))
   30.49 -        if s != 0:
   30.50 -            FAIL("Could not load the required policy '%s'.\n"
   30.51 -                 "Start the system without any policy.\n%s" %
   30.52 -                 (policy, o))
   30.53 +def ACMSetPolicy(policy='xm-test'):
   30.54 +    cmd='xm dumppolicy | grep -E "^POLICY REFERENCE = ' + policy + '.$"'
   30.55 +    s, o = traceCommand(cmd)
   30.56 +    if o != "":
   30.57 +        return
   30.58 +    s, o = traceCommand("xm setpolicy ACM %s" % (policy))
   30.59 +    if s != 0:
   30.60 +        FAIL("Could not load the required policy '%s'.\n"
   30.61 +             "Start the system without any policy.\n%s" % \
   30.62 +             (policy, o))
   30.63  
   30.64  def ACMPrepareSystem(resources):
   30.65      if isACMEnabled():
   30.66 -        ACMLoadPolicy()
   30.67 +        ACMSetPolicy()
   30.68          ACMLabelResources(resources)
   30.69  
   30.70  def ACMLabelResources(resources):
    31.1 --- a/tools/xm-test/tests/security-acm/01_security-acm_basic.py	Tue Dec 04 22:54:58 2007 +0000
    31.2 +++ b/tools/xm-test/tests/security-acm/01_security-acm_basic.py	Wed Dec 05 09:44:20 2007 +0000
    31.3 @@ -6,7 +6,6 @@
    31.4  # A couple of simple tests that test ACM security extensions
    31.5  # for the xm tool. The following xm subcommands are tested:
    31.6  #
    31.7 -# - makepolicy
    31.8  # - labels
    31.9  # - rmlabel
   31.10  # - addlabel
   31.11 @@ -28,11 +27,6 @@ testresource = "phy:ram0"
   31.12  if not isACMEnabled():
   31.13      SKIP("Not running this test since ACM not enabled.")
   31.14  
   31.15 -status, output = traceCommand("xm makepolicy %s" % (testpolicy))
   31.16 -if status != 0:
   31.17 -    FAIL("'xm makepolicy' failed with status %d and output\n%s" %
   31.18 -         (status,output));
   31.19 -
   31.20  status, output = traceCommand("xm labels %s" % (testpolicy))
   31.21  if status != 0:
   31.22      FAIL("'xm labels' failed with status %d.\n" % status)
    32.1 --- a/tools/xm-test/tests/security-acm/acm_utils.py	Tue Dec 04 22:54:58 2007 +0000
    32.2 +++ b/tools/xm-test/tests/security-acm/acm_utils.py	Wed Dec 05 09:44:20 2007 +0000
    32.3 @@ -12,4 +12,4 @@ vmconfigfile = "/tmp/xm-test.conf"
    32.4  if not isACMEnabled():
    32.5      SKIP("Not running this test since ACM not enabled.")
    32.6  
    32.7 -ACMLoadPolicy(testpolicy)
    32.8 +ACMSetPolicy(testpolicy)