Skip to contentSkip to conversation

Tools support for extensions of the Xen-API for managing security policies

PATCH New Stefan Berger 1 participant 1 message Jul 10, 2007

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 Tools support for extensions of the Xen-API for managing security policies

This patch adds a couple of new commands for using the Xen-API extensions for security policies. Older tools are converted to support going through the Xen-API for their operations rather than doing the operations directly in their own code.

---
 xen-unstable.hg/tools/python/xen/xm/activatepolicy.py |   86 ++++++++++++
 xen-unstable.hg/tools/python/xen/xm/addlabel.py       |  125 +++++++++++++-----
 xen-unstable.hg/tools/python/xen/xm/cfgbootpolicy.py  |   72 ++++++++--
 xen-unstable.hg/tools/python/xen/xm/create.dtd        |    7 -
 xen-unstable.hg/tools/python/xen/xm/create.py         |   22 ---
 xen-unstable.hg/tools/python/xen/xm/getlabel.py       |   45 +++++-
 xen-unstable.hg/tools/python/xen/xm/getpolicy.py      |   94 +++++++++++++
 xen-unstable.hg/tools/python/xen/xm/labels.py         |   37 +++++
 xen-unstable.hg/tools/python/xen/xm/loadpolicy.py     |   32 ++++
 xen-unstable.hg/tools/python/xen/xm/main.py           |   70 ++++++----
 xen-unstable.hg/tools/python/xen/xm/makepolicy.py     |   14 +-
 xen-unstable.hg/tools/python/xen/xm/resources.py      |   33 +++-
 xen-unstable.hg/tools/python/xen/xm/rmlabel.py        |   65 +++++++--
 xen-unstable.hg/tools/python/xen/xm/setpolicy.py      |  117 ++++++++++++++++
 xen-unstable.hg/tools/python/xen/xm/xenapi_create.py  |   55 +++++++
 15 files changed, 746 insertions(+), 128 deletions(-)
xen-unstable.hg/tools/python/xen/xm/addlabel.py +96 -29
Index: root/xen-unstable.hg/tools/python/xen/xm/addlabel.py
===================================================================
@@ -25,17 +25,29 @@ import sys
 from xen.util import dictio
 from xen.util import security
 from xen.xm.opts import OptionError
+from xen.util import xsconstants
+from xen.xm import main as xm_main
+from xen.xm.main import server
 
 def help():
     return """
     Format: xm addlabel <label> dom <configfile> [<policy>]
-            xm addlabel <label> res <resource> [<policy>]
+            xm addlabel <label> mgt <domain name> [<policy type>:<policy>]
+            xm addlabel <label> res <resource> [[<policy type>:]<policy>]
     
     This program adds an acm_label entry into the 'configfile'
-    for a domain or to the global resource label file for a
-    resource. It derives the policy from the running hypervisor
+    for a domain or allows to label a xend-managed domain.
+    The global resource label file for is extended with labels for
+    resources. It derives the policy from the running hypervisor
     if it is not given (optional parameter). If a label already
-    exists for the given domain or resource, then addlabel fails."""
+    exists for the given domain or resource, then addlabel fails.
+
+    For xend-managed domains, the 'mgt' parameter should be used and
+    the 'xm' tool must have been configured to use the xen-api for
+    communication with xen. If a policy is provided as last parameter,
+    its type must also be given. Currently only one type of policy is
+    supported and identified as 'ACM'. An example for a valid string
+    is 'ACM:xm-test'. """
 
 
 def validate_config_file(configfile):
@@ -66,32 +78,47 @@ def validate_config_file(configfile):
         return 1
 
 
-def add_resource_label(label, resource, policyref):
+def add_resource_label(label, resource, policyref, policy_type):
     """Adds a resource label to the global resource label file.
     """
-    # sanity check: make sure this label can be instantiated later on
-    ssidref = security.label2ssidref(label, policyref, 'res')
-
-    #build canonical resource name
-    resource = security.unify_resname(resource)
 
-    # see if this resource is already in the file
-    access_control = {}
-    file = security.res_label_filename
-    try:
-        access_control = dictio.dict_read("resources", file)
-    except:
-        print "Resource file not found, creating new file at:"
-        print "%s" % (file)
+    if xm_main.serverType != xm_main.SERVER_XEN_API:
 
-    if access_control.has_key(resource):
-        security.err("This resource is already labeled.")
+        # sanity check: make sure this label can be instantiated later on
+        ssidref = security.label2ssidref(label, policyref, 'res')
 
-    # write the data to file
-    new_entry = { resource : tuple([policyref, label]) }
-    access_control.update(new_entry)
-    dictio.dict_write(access_control, "resources", file)
+        #build canonical resource name
+        resource = security.unify_resname(resource,mustexist=False)
 
+        # see if this resource is already in the file
+        access_control = {}
+        fil = security.res_label_filename
+        try:
+            access_control = dictio.dict_read("resources", fil)
+        except:
+            print "Resource file not found, creating new file at:"
+            print "%s" % (fil)
+
+        if access_control.has_key(resource):
+            security.err("This resource is already labeled.")
+
+        # write the data to file
+        new_entry = { resource : tuple([policy_type, policyref, label]) }
+        access_control.update(new_entry)
+        dictio.dict_write(access_control, "resources", fil)
+    else:
+        res = [ policy_type, policyref, label ]
+        res_xapi = security.format_resource_label(res)
+        old = server.xenapi.XSPolicy.get_resource_label(resource)
+        if old == "":
+            try:
+                server.xenapi.XSPolicy.set_resource_label(resource,
+                                                          res_xapi,
+                                                          "")
+            except Exception, e:
+                security.err("Could not label this resource: %s" % e)
+        else:
+            security.err("'%s' is already labeled with '%s'" % (resource,old))
 
 def add_domain_label(label, configfile, policyref):
     # sanity checks: make sure this label can be instantiated later on
@@ -109,9 +136,35 @@ def add_domain_label(label, configfile, 
     config_fd.write(new_label)
     config_fd.close()
 
+def add_domain_label_xapi(label, domainname, policyref, policy_type):
+    if xm_main.serverType != xm_main.SERVER_XEN_API:
+        raise OptionError('Xm must be configured to use the xen-api.')
+    uuids = server.xenapi.VM.get_by_name_label(domainname)
+    if len(uuids) == 0:
+        raise OptionError('A VM with that name does not exist.')
+    if len(uuids) != 1:
+        raise OptionError('There are multiple domains with the same name.')
+    uuid = uuids[0]
+    sec_lab = "%s:%s:%s" % (policy_type, policyref, label)
+    try:
+        old_lab = server.xenapi.VM.get_security_label(uuid)
+        rc = server.xenapi.VM.set_security_label(uuid, sec_lab, old_lab)
+    except:
+        rc = -1
+    if int(rc) < 0:
+        raise OptionError('Could not label domain.')
+    else:
+        ssidref = int(rc)
+        if ssidref != 0:
+            print "Set the label of domain '%s' to '%s'. New ssidref = %08x" % \
+                  (domainname,label,ssidref)
+        else:
+            print "Set the label of dormant domain '%s' to '%s'." % \
+                  (domainname,label)
 
 def main(argv):
     policyref = None
+    policy_type = ""
     if len(argv) not in (4, 5):
         raise OptionError('Needs either 2 or 3 arguments')
     
@@ -121,6 +174,7 @@ def main(argv):
         policyref = argv[4]
     elif security.on():
         policyref = security.active_policy
+        policy_type = xsconstants.ACM_POLICY_ID
     else:
         raise OptionError("No active policy. Must specify policy on the "
                           "command line.")
@@ -136,11 +190,27 @@ def main(argv):
             raise OptionError('Invalid config file')
         else:
             add_domain_label(label, configfile, policyref)
+    elif argv[2].lower() == "mgt":
+        domain = argv[3]
+        if policy_type == "":
+            tmp = policyref.split(":")
+            if len(tmp) != 2:
+                raise OptionError("Policy name in wrong format.")
+            policy_type, policyref = tmp
+        add_domain_label_xapi(label, domain, policyref, policy_type)
     elif argv[2].lower() == "res":
         resource = argv[3]
-        add_resource_label(label, resource, policyref)
+        if policy_type == "":
+            tmp = policyref.split(":")
+            if len(tmp) == 1:
+                policy_type = xsconstants.ACM_POLICY_ID
+            elif len(tmp) == 2:
+                policy_type, policyref = tmp
+            else:
+                raise OptionError("Policy name in wrong format.")
+        add_resource_label(label, resource, policyref, policy_type)
     else:
-        raise OptionError('Need to specify either "dom" or "res" as '
+        raise OptionError('Need to specify either "dom", "mgt" or "res" as '
                           'object to add label to.')
             
 if __name__ == '__main__':
@@ -149,6 +219,3 @@ if __name__ == '__main__':
     except Exception, e:
         sys.stderr.write('Error: %s\n' % str(e))
         sys.exit(-1)
-    
-
-
xen-unstable.hg/tools/python/xen/xm/getlabel.py +35 -10

91 lines not on this page · raw message

xen-unstable.hg/tools/python/xen/xm/rmlabel.py +49 -16

126 lines not on this page · raw message

xen-unstable.hg/tools/python/xen/xm/create.py +6 -16
Index: root/xen-unstable.hg/tools/python/xen/xm/create.py
===================================================================
@@ -643,22 +643,12 @@ def configure_security(config, vals):
                                  ['policy', policy],
                                  ['label', label] ]
 
-        #ssidref cannot be specified together with access_control
-        if sxp.child_value(config, 'ssidref'):
-            err("ERROR: SSIDREF and access_control are mutually exclusive but both specified!")
-        #else calculate ssidre from label
+        #calculate ssidref from label
         ssidref = security.label2ssidref(label, policy, 'dom')
         if not ssidref :
             err("ERROR calculating ssidref from access_control.")
         security_label = ['security', [ config_access_control, ['ssidref' , ssidref ] ] ]
         config.append(security_label)
-    elif num == 0:
-        if hasattr(vals, 'ssidref'):
-            if not security.on():
-                err("ERROR: Security ssidref specified but no policy active.")
-            ssidref = getattr(vals, 'ssidref')
-            security_label = ['security', [ [ 'ssidref' , int(ssidref) ] ] ]
-            config.append(security_label)
     elif num > 1:
         err("VM config error: Multiple access_control definitions!")
 
@@ -1231,13 +1221,13 @@ def config_security_check(config, verbos
 
         except security.ACMError:
             print "   %s: DENIED" % (resource)
-            (res_label, res_policy) = security.get_res_label(resource)
+            (poltype, res_label, res_policy) = security.get_res_label(resource)
             if not res_label:
                 res_label = ""
-            print "   --> res: %s (%s)" % (str(res_label),
-                                           str(res_policy))
-            print "   --> dom: %s (%s)" % (str(domain_label),
-                                           str(domain_policy))
+            print "   --> res: %s (%s:%s)" % (str(res_label),
+                                           str(poltype), str(res_policy))
+            print "   --> dom: %s (%s:%s)" % (str(domain_label),
+                                           str(poltype), str(domain_policy))
 
             answer = 0
 
xen-unstable.hg/tools/python/xen/xm/resources.py +24 -9
Index: root/xen-unstable.hg/tools/python/xen/xm/resources.py
===================================================================
@@ -21,7 +21,10 @@
 import sys
 from xen.util import dictio
 from xen.util import security
+from xen.util import xsconstants
 from xen.xm.opts import OptionError
+from xen.xm import main as xm_main
+from xen.xm.main import server
 
 def help():
     return """
@@ -32,20 +35,32 @@ def print_resource_data(access_control):
     """Prints out a resource dictionary to stdout
     """
     for resource in access_control:
-        (policy, label) = access_control[resource]
+        tmp = access_control[resource]
+        if len(tmp) == 2:
+            policytype = xsconstants.ACM_POLICY_ID
+            (policy, label) = access_control[resource]
+        elif len(tmp) == 3:
+            policytype, policy, label = access_control[resource]
         print resource
-        print "    policy: "+policy
-        print "    label:  "+label
+        print "      type: "+ policytype
+        print "    policy: "+ policy
+        print "    label:  "+ label
 
 def main (argv):
     if len(argv) > 1:
         raise OptionError("No arguments required")
-    
-    try:
-        filename = security.res_label_filename
-        access_control = dictio.dict_read("resources", filename)
-    except:
-        raise OptionError("Resource file not found")
+
+    if xm_main.serverType == xm_main.SERVER_XEN_API:
+        access_control = server.xenapi.XSPolicy.get_labeled_resources()
+        for key, value in access_control.items():
+            access_control[key] = tuple(value.split(':'))
+    else:
+        try:
+            filename = security.res_label_filename
+            access_control = dictio.dict_read("resources", filename)
+            print access_control
+        except:
+            raise OptionError("Resource file not found")
 
     print_resource_data(access_control)
 
xen-unstable.hg/tools/python/xen/xm/getpolicy.py new file +94 -0

94 lines not on this page · raw message

xen-unstable.hg/tools/python/xen/xm/setpolicy.py new file +117 -0

117 lines not on this page · raw message

xen-unstable.hg/tools/python/xen/xm/activatepolicy.py new file +86 -0

86 lines not on this page · raw message

xen-unstable.hg/tools/python/xen/xm/labels.py +35 -2
Index: root/xen-unstable.hg/tools/python/xen/xm/labels.py
===================================================================
@@ -24,6 +24,10 @@ import string
 from xen.util.security import ACMError, err, list_labels, active_policy
 from xen.util.security import vm_label_re, res_label_re, all_label_re
 from xen.xm.opts import OptionError
+from xen.util.acmpolicy import ACMPolicy
+from xen.util import xsconstants
+from xen.xm.main import server
+from xen.xm import main as xm_main
 
 
 def help():
@@ -48,6 +52,12 @@ def main(argv):
         else:
             raise OptionError('Unrecognised option: %s' % arg)
 
+    if xm_main.serverType != xm_main.SERVER_XEN_API:
+        labels(policy, ptype)
+    else:
+        labels_xapi(policy, ptype)
+
+def labels(policy, ptype):
     if not policy:
         policy = active_policy
         if active_policy in ['NULL', 'INACTIVE', 'DEFAULT']:
@@ -73,7 +83,30 @@ def main(argv):
     except:
         traceback.print_exc(limit = 1)
 
+def labels_xapi(policy, ptype):
+    policystate = server.xenapi.XSPolicy.get_xspolicy()
+    if int(policystate['type']) == xsconstants.XS_POLICY_ACM:
+        acmpol = ACMPolicy(xml=policystate['repr'])
+        if policy and policy != acmpol.get_name():
+            print "Warning: '%s' is not the currently loaded policy." % policy
+            return labels(policy, ptype)
+        names1 = []
+        names2 = []
+        if not ptype or ptype == 'dom' or ptype == 'any':
+            names1 = acmpol.policy_get_virtualmachinelabel_names()
+        if ptype == 'res' or ptype == 'any':
+            names2 = acmpol.policy_get_resourcelabel_names()
+        if len(names1) > 0:
+            names = set(names1)
+            names.union(names2)
+        else:
+            names = set(names2)
+        for n in names:
+            print n
+    elif int(policystate['type']) == 0:
+        print "No policy installed on the system."
+    else:
+        print "Unsupported type of policy installed on the system."
+
 if __name__ == '__main__':
     main(sys.argv)
-
-
xen-unstable.hg/tools/python/xen/xm/loadpolicy.py +30 -2
Index: root/xen-unstable.hg/tools/python/xen/xm/loadpolicy.py
===================================================================
@@ -22,6 +22,11 @@ import sys
 import traceback
 from xen.util.security import ACMError, err, load_policy
 from xen.xm.opts import OptionError
+from xen.xm import main as xm_main
+from xen.util import xsconstants
+from xen.xm.activatepolicy import activate_policy
+from xen.xm.main import server
+from xen.util.acmpolicy import ACMPolicy
 
 def help():
     return """Load the compiled binary (.bin) policy into the running
@@ -30,8 +35,31 @@ def help():
 def main(argv):
     if len(argv) != 2:
         raise OptionError('No policy defined')
-    
-    load_policy(argv[1])
+    if xm_main.serverType == xm_main.SERVER_XEN_API:
+        policy = argv[1]
+        print "This command is deprecated for use with Xen-API " \
+              "configuration. Consider using\n'xm activatepolicy'."
+        policystate = server.xenapi.XSPolicy.get_xspolicy()
+        if int(policystate['type']) == 0:
+            print "No policy is installed."
+            return
+
+        if int(policystate['type']) != xsconstants.XS_POLICY_ACM:
+            print "Unknown policy type '%s'." % policystate['type']
+            return
+        else:
+            xml = policystate['repr']
+            xs_ref = policystate['xs_ref']
+            if not xml:
+                OptionError("No policy installed on system?")
+            acmpol = ACMPolicy(xml=xml)
+            if acmpol.get_name() != policy:
+                OptionError("Policy installed on system '%s' does not match"\
+                            " the request policy '%s'" % \
+                            (acmpol.get_name(), policy))
+            activate_policy(xsconstants.XS_INST_LOAD)
+    else:
+        load_policy(argv[1])
 
 if __name__ == '__main__':
     try:
xen-unstable.hg/tools/python/xen/xm/main.py +47 -23

145 lines not on this page · raw message

xen-unstable.hg/tools/python/xen/xm/xenapi_create.py +55 -0

103 lines not on this page · raw message

xen-unstable.hg/tools/python/xen/xm/create.dtd +6 -1
Index: root/xen-unstable.hg/tools/python/xen/xm/create.dtd
===================================================================
@@ -38,6 +38,7 @@
                  memory,
                  vbd*,
                  vif*,
+                 vtpm*,
                  console*,
                  platform*,
                  vcpu_param*,
@@ -49,7 +50,8 @@
                  actions_after_shutdown %NORMAL_EXIT; #REQUIRED 
                  actions_after_reboot   %NORMAL_EXIT; #REQUIRED
                  actions_after_crash    %CRASH_BEHAVIOUR; #REQUIRED
-                 PCI_bus                CDATA #REQUIRED> 
+                 PCI_bus                CDATA #REQUIRED
+                 security_label         CDATA #IMPLIED>
 
 <!ELEMENT memory EMPTY> 
 <!ATTLIST memory static_min      CDATA #REQUIRED
@@ -74,6 +76,9 @@
                  qos_algorithm_type CDATA    #REQUIRED
                  network         CDATA       #IMPLIED> 
 
+<!ELEMENT vtpm   (name*)>
+<!ATTLIST vtpm   backend         CDATA #REQUIRED>
+
 <!ELEMENT console (other_config*)>
 <!ATTLIST console protocol       (vt100|rfb|rdp) #REQUIRED>
 
xen-unstable.hg/tools/python/xen/xm/cfgbootpolicy.py +56 -16

93 lines not on this page · raw message

xen-unstable.hg/tools/python/xen/xm/makepolicy.py +10 -4
Index: root/xen-unstable.hg/tools/python/xen/xm/makepolicy.py
===================================================================
@@ -20,7 +20,10 @@
 import sys
 import traceback
 from xen.util.security import ACMError, err, make_policy
+from xen.util import xsconstants
 from xen.xm.opts import OptionError
+from xen.xm import main as xm_main
+from xen.xm.setpolicy import setpolicy
 
 def usage():
     print "\nUsage: xm makepolicy <policy>\n"
@@ -32,8 +35,13 @@ def usage():
 def main(argv):
     if len(argv) != 2:
         raise OptionError('No XML policy file specified')
-
-    make_policy(argv[1])
+    if xm_main.serverType == xm_main.SERVER_XEN_API:
+        print "This command is deprecated for use with Xen-API " \
+              "configuration. Consider using\n'xm setpolicy'."
+        setpolicy(xsconstants.ACM_POLICY_ID, argv[1],
+                  xsconstants.XS_INST_LOAD, True)
+    else:
+        make_policy(argv[1])
 
 if __name__ == '__main__':
     try:
@@ -41,5 +49,3 @@ if __name__ == '__main__':
     except Exception, e:
         sys.stderr.write('Error: %s\n' % str(e))
         sys.exit(-1)
-
-

_______________________________________________
Xen-devel mailing list
[email protected]
http://lists.xensource.com/xen-devel