ia64/xen-unstable

changeset 9835:cf20dbbf5c2b

This patch adds new python access control management scripts, which
integrate into Xen Management and which support the new access control
labels (labels replace the ssidref numbers at the management user
interface).

Signed-off by: Reiner Sailer <sailer@us.ibm.com>
author smh22@firebug.cl.cam.ac.uk
date Mon Apr 24 10:58:25 2006 +0100 (2006-04-24)
parents 37da8dd5d43e
children 681a18bf049e
files tools/python/setup.py tools/python/xen/lowlevel/acm/acm.c tools/python/xen/util/security.py tools/python/xen/xm/addlabel.py tools/python/xen/xm/cfgbootpolicy.py tools/python/xen/xm/dumppolicy.py tools/python/xen/xm/labels.py tools/python/xen/xm/loadpolicy.py tools/python/xen/xm/makepolicy.py tools/security/python/xensec_tools/acm_getdecision tools/security/python/xensec_tools/acm_getlabel
line diff
     1.1 --- a/tools/python/setup.py	Mon Apr 24 10:54:47 2006 +0100
     1.2 +++ b/tools/python/setup.py	Mon Apr 24 10:58:25 2006 +0100
     1.3 @@ -31,6 +31,13 @@ xs = Extension("xs",
     1.4                 libraries          = libraries,
     1.5                 sources            = [ "xen/lowlevel/xs/xs.c" ])
     1.6  
     1.7 +acm = Extension("acm",
     1.8 +               extra_compile_args = extra_compile_args,
     1.9 +               include_dirs       = include_dirs + [ "xen/lowlevel/acm" ],
    1.10 +               library_dirs       = library_dirs,
    1.11 +               libraries          = libraries,
    1.12 +               sources            = [ "xen/lowlevel/acm/acm.c" ])
    1.13 +
    1.14  setup(name            = 'xen',
    1.15        version         = '3.0',
    1.16        description     = 'Xen',
    1.17 @@ -50,7 +57,7 @@ setup(name            = 'xen',
    1.18                           'xen.xm.tests'
    1.19                           ],
    1.20        ext_package = "xen.lowlevel",
    1.21 -      ext_modules = [ xc, xs ]
    1.22 +      ext_modules = [ xc, xs, acm ]
    1.23        )
    1.24  
    1.25  os.chdir('logging')
     2.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     2.2 +++ b/tools/python/xen/lowlevel/acm/acm.c	Mon Apr 24 10:58:25 2006 +0100
     2.3 @@ -0,0 +1,237 @@
     2.4 +/****************************************************************
     2.5 + * acm.c
     2.6 + *
     2.7 + * Copyright (C) 2006 IBM Corporation
     2.8 + *
     2.9 + * Authors:
    2.10 + * Reiner Sailer <sailer@watson.ibm.com>
    2.11 + *
    2.12 + * This program is free software; you can redistribute it and/or
    2.13 + * modify it under the terms of the GNU General Public License as
    2.14 + * published by the Free Software Foundation, version 2 of the
    2.15 + * License.
    2.16 + *
    2.17 + * ACM low-level code that allows Python control code to leverage
    2.18 + * the ACM hypercall interface to retrieve real-time information
    2.19 + * from the Xen hypervisor security module.
    2.20 + *
    2.21 + * indent -i4 -kr -nut
    2.22 + */
    2.23 +#include <Python.h>
    2.24 +
    2.25 +#include <stdio.h>
    2.26 +#include <fcntl.h>
    2.27 +#include <sys/mman.h>
    2.28 +#include <sys/types.h>
    2.29 +#include <stdlib.h>
    2.30 +#include <sys/ioctl.h>
    2.31 +#include <netinet/in.h>
    2.32 +#include <xen/acm.h>
    2.33 +#include <xen/acm_ops.h>
    2.34 +#include <xen/linux/privcmd.h>
    2.35 +
    2.36 +#define PERROR(_m, _a...) \
    2.37 +fprintf(stderr, "ERROR: " _m " (%d = %s)\n" , ## _a ,    \
    2.38 +    errno, strerror(errno))
    2.39 +
    2.40 +
    2.41 +
    2.42 +static inline int do_acm_op(int xc_handle, struct acm_op *op)
    2.43 +{
    2.44 +    int ret = -1;
    2.45 +    privcmd_hypercall_t hypercall;
    2.46 +
    2.47 +    op->interface_version = ACM_INTERFACE_VERSION;
    2.48 +
    2.49 +    hypercall.op = __HYPERVISOR_acm_op;
    2.50 +    hypercall.arg[0] = (unsigned long) op;
    2.51 +
    2.52 +    if (mlock(op, sizeof(*op)) != 0) {
    2.53 +        PERROR("Could not lock memory for Xen policy hypercall");
    2.54 +        goto out1;
    2.55 +    }
    2.56 +    ret = ioctl(xc_handle, IOCTL_PRIVCMD_HYPERCALL, &hypercall);
    2.57 +    if (ret < 0) {
    2.58 +        if (errno == EACCES)
    2.59 +            PERROR("ACM operation failed.");
    2.60 +        goto out2;
    2.61 +    }
    2.62 + out2:
    2.63 +    munlock(op, sizeof(*op));
    2.64 + out1:
    2.65 +    return ret;
    2.66 +}
    2.67 +
    2.68 +
    2.69 +
    2.70 +/* generic shared function */
    2.71 +void * __getssid(int domid, uint32_t *buflen)
    2.72 +{
    2.73 +    struct acm_op op;
    2.74 +    int acm_cmd_fd;
    2.75 +    #define SSID_BUFFER_SIZE    4096
    2.76 +    void *buf = NULL;
    2.77 +
    2.78 +    if ((acm_cmd_fd = open("/proc/xen/privcmd", O_RDONLY)) < 0) {
    2.79 +        goto out1;
    2.80 +    }
    2.81 +    if ((buf = malloc(SSID_BUFFER_SIZE)) == NULL) {
    2.82 +        PERROR("acm.policytype: Could not allocate ssid buffer!\n");
    2.83 +        goto out2;
    2.84 +    }
    2.85 +    memset(buf, 0, SSID_BUFFER_SIZE);
    2.86 +    op.cmd = ACM_GETSSID;
    2.87 +    op.interface_version = ACM_INTERFACE_VERSION;
    2.88 +    op.u.getssid.ssidbuf = buf;
    2.89 +    op.u.getssid.ssidbuf_size = SSID_BUFFER_SIZE;
    2.90 +    op.u.getssid.get_ssid_by = DOMAINID;
    2.91 +    op.u.getssid.id.domainid = domid;
    2.92 +
    2.93 +    if (do_acm_op(acm_cmd_fd, &op) < 0) {
    2.94 +        free(buf);
    2.95 +        buf = NULL;
    2.96 +        goto out2;
    2.97 +    } else {
    2.98 +        *buflen = SSID_BUFFER_SIZE;
    2.99 +        goto out2;
   2.100 +    }
   2.101 + out2:
   2.102 +    close(acm_cmd_fd);
   2.103 + out1:
   2.104 +    return buf;
   2.105 +}
   2.106 +
   2.107 +
   2.108 +/* retrieve the policytype indirectly by retrieving the
   2.109 + * ssidref for domain 0 (always exists) */
   2.110 +static PyObject *policy(PyObject * self, PyObject * args)
   2.111 +{
   2.112 +    /* out */
   2.113 +    char *policyreference;
   2.114 +    PyObject *ret = NULL;
   2.115 +    void *ssid_buffer;
   2.116 +    uint32_t buf_len;
   2.117 +
   2.118 +    if (!PyArg_ParseTuple(args, "", NULL)) {
   2.119 +    goto out1;
   2.120 +    }
   2.121 +    ssid_buffer =  __getssid(0, &buf_len);
   2.122 +    if (ssid_buffer == NULL) {
   2.123 +        goto out1;
   2.124 +    } else if (buf_len < sizeof(struct acm_ssid_buffer)) {
   2.125 +        goto out2;
   2.126 +    } else {
   2.127 +        struct acm_ssid_buffer *ssid = (struct acm_ssid_buffer *)ssid_buffer;
   2.128 +        policyreference = (char *)(ssid_buffer + ssid->policy_reference_offset
   2.129 +                       + sizeof (struct acm_policy_reference_buffer));
   2.130 +    }
   2.131 +    ret = Py_BuildValue("s", policyreference);
   2.132 + out2:
   2.133 +    free(ssid_buffer);
   2.134 + out1:
   2.135 +    return ret;
   2.136 +}
   2.137 +
   2.138 +
   2.139 +/* retrieve ssid info for a domain domid*/
   2.140 +static PyObject *getssid(PyObject * self, PyObject * args)
   2.141 +{
   2.142 +    /* in */
   2.143 +    uint32_t    domid;
   2.144 +    /* out */
   2.145 +    char *policytype, *policyreference;
   2.146 +    uint32_t    ssidref;
   2.147 +
   2.148 +    void *ssid_buffer;
   2.149 +    uint32_t buf_len;
   2.150 +
   2.151 +    if (!PyArg_ParseTuple(args, "i", &domid)) {
   2.152 +        return NULL;
   2.153 +    }
   2.154 +    ssid_buffer =  __getssid(domid, &buf_len);
   2.155 +    if (ssid_buffer == NULL) {
   2.156 +        return NULL;
   2.157 +    } else if (buf_len < sizeof(struct acm_ssid_buffer)) {
   2.158 +        free(ssid_buffer);
   2.159 +        return NULL;
   2.160 +    } else {
   2.161 +        struct acm_ssid_buffer *ssid = (struct acm_ssid_buffer *) ssid_buffer;
   2.162 +        policytype = ACM_POLICY_NAME(ssid->secondary_policy_code << 4 |
   2.163 +                     ssid->primary_policy_code);
   2.164 +        ssidref = ssid->ssidref;
   2.165 +        policyreference = (char *)(ssid_buffer + ssid->policy_reference_offset
   2.166 +                       + sizeof (struct acm_policy_reference_buffer));
   2.167 +    }
   2.168 +    free(ssid_buffer);
   2.169 +    return Py_BuildValue("{s:s,s:s,s:i}",
   2.170 +             "policyreference",   policyreference,
   2.171 +             "policytype",        policytype,
   2.172 +             "ssidref",           ssidref);
   2.173 +}
   2.174 +
   2.175 +
   2.176 +/* retrieve access decision based on domain ids or ssidrefs */
   2.177 +static PyObject *getdecision(PyObject * self, PyObject * args)
   2.178 +{
   2.179 +    char *arg1_name, *arg1, *arg2_name, *arg2, *decision = NULL;
   2.180 +    struct acm_op op;
   2.181 +    int acm_cmd_fd, ret;
   2.182 +
   2.183 +    if (!PyArg_ParseTuple(args, "ssss", &arg1_name, &arg1, &arg2_name, &arg2)) {
   2.184 +        return NULL;
   2.185 +    }
   2.186 +
   2.187 +    if ((acm_cmd_fd = open("/proc/xen/privcmd", O_RDONLY)) <= 0) {
   2.188 +        PERROR("Could not open xen privcmd device!\n");
   2.189 +        return NULL;
   2.190 +    }
   2.191 +
   2.192 +    if ((strcmp(arg1_name, "domid") && strcmp(arg1_name, "ssidref")) ||
   2.193 +    (strcmp(arg2_name, "domid") && strcmp(arg2_name, "ssidref")))
   2.194 +        return NULL;
   2.195 +
   2.196 +    op.cmd = ACM_GETDECISION;
   2.197 +    op.interface_version = ACM_INTERFACE_VERSION;
   2.198 +    op.u.getdecision.hook = SHARING;
   2.199 +    if (!strcmp(arg1_name, "domid")) {
   2.200 +        op.u.getdecision.get_decision_by1 = DOMAINID;
   2.201 +        op.u.getdecision.id1.domainid = atoi(arg1);
   2.202 +    } else {
   2.203 +        op.u.getdecision.get_decision_by1 = SSIDREF;
   2.204 +        op.u.getdecision.id1.ssidref = atol(arg1);
   2.205 +    }
   2.206 +    if (!strcmp(arg2_name, "domid")) {
   2.207 +        op.u.getdecision.get_decision_by2 = DOMAINID;
   2.208 +        op.u.getdecision.id2.domainid = atoi(arg2);
   2.209 +    } else {
   2.210 +        op.u.getdecision.get_decision_by2 = SSIDREF;
   2.211 +        op.u.getdecision.id2.ssidref = atol(arg2);
   2.212 +    }
   2.213 +
   2.214 +    ret = do_acm_op(acm_cmd_fd, &op);
   2.215 +    close(acm_cmd_fd);
   2.216 +
   2.217 +    if (op.u.getdecision.acm_decision == ACM_ACCESS_PERMITTED)
   2.218 +        decision = "PERMITTED";
   2.219 +    else if (op.u.getdecision.acm_decision == ACM_ACCESS_DENIED)
   2.220 +        decision = "DENIED";
   2.221 +
   2.222 +    return Py_BuildValue("s", decision);
   2.223 +}
   2.224 +
   2.225 +/*=================General Python Extension Declarations=================*/
   2.226 +
   2.227 +/* methods */
   2.228 +static PyMethodDef acmMethods[] = {
   2.229 +    {"policy", policy, METH_VARARGS, "Retrieve Active ACM Policy Reference Name"},
   2.230 +    {"getssid", getssid, METH_VARARGS, "Retrieve label information and ssidref for a domain"},
   2.231 +    {"getdecision", getdecision, METH_VARARGS, "Retrieve ACM access control decision"},
   2.232 +    /* end of list (extend list above this line) */
   2.233 +    {NULL, NULL, 0, NULL}
   2.234 +};
   2.235 +
   2.236 +/* inits */
   2.237 +PyMODINIT_FUNC initacm(void)
   2.238 +{
   2.239 +    Py_InitModule("acm", acmMethods);
   2.240 +}
     3.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     3.2 +++ b/tools/python/xen/util/security.py	Mon Apr 24 10:58:25 2006 +0100
     3.3 @@ -0,0 +1,504 @@
     3.4 +#===========================================================================
     3.5 +# This library is free software; you can redistribute it and/or
     3.6 +# modify it under the terms of version 2.1 of the GNU Lesser General Public
     3.7 +# License as published by the Free Software Foundation.
     3.8 +#
     3.9 +# This library is distributed in the hope that it will be useful,
    3.10 +# but WITHOUT ANY WARRANTY; without even the implied warranty of
    3.11 +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    3.12 +# Lesser General Public License for more details.
    3.13 +#
    3.14 +# You should have received a copy of the GNU Lesser General Public
    3.15 +# License along with this library; if not, write to the Free Software
    3.16 +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
    3.17 +#============================================================================
    3.18 +# Copyright (C) 2006 International Business Machines Corp.
    3.19 +# Author: Reiner Sailer
    3.20 +#============================================================================
    3.21 +
    3.22 +import commands
    3.23 +import logging
    3.24 +import sys, os, string, re
    3.25 +import traceback
    3.26 +import shutil
    3.27 +from xen.lowlevel import acm
    3.28 +from xen.xend import sxp
    3.29 +
    3.30 +#global directories and tools for security management
    3.31 +policy_dir_prefix = "/etc/xen/acm-security/policies"
    3.32 +boot_filename = "/boot/grub/menu.lst"
    3.33 +xensec_xml2bin = "/usr/sbin/xensec_xml2bin"
    3.34 +xensec_tool = "/usr/sbin/xensec_tool"
    3.35 +
    3.36 +#global patterns for map file
    3.37 +#police_reference_tagname = "POLICYREFERENCENAME"
    3.38 +primary_entry_re = re.compile("\s*PRIMARY\s+.*", re.IGNORECASE)
    3.39 +secondary_entry_re = re.compile("\s*SECONDARY\s+.*", re.IGNORECASE)
    3.40 +label_template_re =  re.compile(".*security_label_template.xml", re.IGNORECASE)
    3.41 +mapping_filename_re = re.compile(".*\.map", re.IGNORECASE)
    3.42 +policy_reference_entry_re = re.compile("\s*POLICYREFERENCENAME\s+.*", re.IGNORECASE)
    3.43 +vm_label_re = re.compile("\s*LABEL->SSID\s+VM\s+.*", re.IGNORECASE)
    3.44 +res_label_re = re.compile("\s*LABEL->SSID\s+RES\s+.*", re.IGNORECASE)
    3.45 +all_label_re = re.compile("\s*LABEL->SSID\s+.*", re.IGNORECASE)
    3.46 +access_control_re = re.compile("\s*access_control\s*=", re.IGNORECASE)
    3.47 +
    3.48 +#global patterns for boot configuration file
    3.49 +xen_title_re = re.compile("\s*title\s+XEN", re.IGNORECASE)
    3.50 +any_title_re = re.compile("\s*title\s", re.IGNORECASE)
    3.51 +xen_kernel_re = re.compile("\s*kernel.*xen.*\.gz", re.IGNORECASE)
    3.52 +kernel_ver_re = re.compile("\s*module.*vmlinuz", re.IGNORECASE)
    3.53 +any_module_re = re.compile("\s*module\s", re.IGNORECASE)
    3.54 +empty_line_re = re.compile("^\s*$")
    3.55 +binary_name_re = re.compile(".*[chwall|ste|chwall_ste].*\.bin", re.IGNORECASE)
    3.56 +policy_name_re = re.compile(".*[chwall|ste|chwall_ste].*", re.IGNORECASE)
    3.57 +
    3.58 +
    3.59 +
    3.60 +log = logging.getLogger("xend.util.security")
    3.61 +
    3.62 +# Our own exception definition. It is masked (pass) if raised and
    3.63 +# whoever raises this exception must provide error information.
    3.64 +class ACMError(Exception):
    3.65 +    def __init__(self,value):
    3.66 +        self.value = value
    3.67 +    def __str__(self):
    3.68 +        return repr(self.value)
    3.69 +
    3.70 +
    3.71 +
    3.72 +def err(msg):
    3.73 +    """Raise ACM exception.
    3.74 +    """
    3.75 +    sys.stderr.write("ACMError: " + msg + "\n")
    3.76 +    raise ACMError(msg)
    3.77 +
    3.78 +
    3.79 +
    3.80 +active_policy = None
    3.81 +
    3.82 +
    3.83 +def refresh_security_policy():
    3.84 +    """
    3.85 +    retrieves security policy
    3.86 +    """
    3.87 +    global active_policy
    3.88 +
    3.89 +    try:
    3.90 +        active_policy = acm.policy()
    3.91 +    except:
    3.92 +        active_policy = "INACTIVE"
    3.93 +
    3.94 +# now set active_policy
    3.95 +refresh_security_policy()
    3.96 +
    3.97 +def on():
    3.98 +    """
    3.99 +    returns none if security policy is off (not compiled),
   3.100 +    any string otherwise, use it: if not security.on() ...
   3.101 +    """
   3.102 +    refresh_security_policy()
   3.103 +    return (active_policy not in ['INACTIVE', 'NULL'])
   3.104 +
   3.105 +
   3.106 +
   3.107 +# Assumes a 'security' info  [security access_control ...] [ssidref ...]
   3.108 +def get_security_info(info, field):
   3.109 +    """retrieves security field from self.info['security'])
   3.110 +    allowed search fields: ssidref, label, policy
   3.111 +    """
   3.112 +    if isinstance(info, dict):
   3.113 +        security = info['security']
   3.114 +    elif isinstance(info, list):
   3.115 +        security = sxp.child_value(info, 'security', )
   3.116 +    if not security:
   3.117 +        if field == 'ssidref':
   3.118 +            #return default ssid
   3.119 +            return 0
   3.120 +        else:
   3.121 +            err("Security information not found in info struct.")
   3.122 +
   3.123 +    if field == 'ssidref':
   3.124 +        search = 'ssidref'
   3.125 +    elif field in ['policy', 'label']:
   3.126 +            search = 'access_control'
   3.127 +    else:
   3.128 +        err("Illegal field in get_security_info.")
   3.129 +
   3.130 +    for idx in range(0, len(security)):
   3.131 +        if search != security[idx][0]:
   3.132 +            continue
   3.133 +        if search == 'ssidref':
   3.134 +            return int(security[idx][1])
   3.135 +        else:
   3.136 +            for aidx in range(0, len(security[idx])):
   3.137 +                if security[idx][aidx][0] == field:
   3.138 +                    return str(security[idx][aidx][1])
   3.139 +
   3.140 +    if search == 'ssidref':
   3.141 +        return 0
   3.142 +    else:
   3.143 +        return None
   3.144 +
   3.145 +
   3.146 +
   3.147 +def get_security_printlabel(info):
   3.148 +    """retrieves printable security label from self.info['security']),
   3.149 +    preferably the label name and otherwise (if label is not specified
   3.150 +    in config and cannot be found in mapping file) a hex string of the
   3.151 +    ssidref or none if both not available
   3.152 +    """
   3.153 +    try:
   3.154 +        if not on():
   3.155 +            return "INACTIVE"
   3.156 +        if active_policy in ["DEFAULT"]:
   3.157 +            return "DEFAULT"
   3.158 +
   3.159 +        printlabel = get_security_info(info, 'label')
   3.160 +        if printlabel:
   3.161 +            return printlabel
   3.162 +        ssidref = get_security_info(info, 'ssidref')
   3.163 +        if not ssidref:
   3.164 +            return None
   3.165 +        #try to translate ssidref to a label
   3.166 +        result = ssidref2label(ssidref)
   3.167 +        if not result:
   3.168 +            printlabel = "0x%08x" % ssidref
   3.169 +        else:
   3.170 +            printlabel = result
   3.171 +        return printlabel
   3.172 +    except ACMError:
   3.173 +        #don't throw an exception in xm list
   3.174 +        return "ERROR"
   3.175 +
   3.176 +
   3.177 +
   3.178 +def getmapfile(policyname):
   3.179 +    """
   3.180 +    in: if policyname is None then the currently
   3.181 +    active hypervisor policy is used
   3.182 +    out: 1. primary policy, 2. secondary policy,
   3.183 +    3. open file descriptor for mapping file, and
   3.184 +    4. True if policy file is available, False otherwise
   3.185 +    """
   3.186 +    if not policyname:
   3.187 +        policyname = active_policy
   3.188 +    map_file_ok = False
   3.189 +    primary = None
   3.190 +    secondary = None
   3.191 +    #strip last part of policy as file name part
   3.192 +    policy_dir_list = string.split(policyname, ".")
   3.193 +    policy_file = policy_dir_list.pop()
   3.194 +    if len(policy_dir_list) > 0:
   3.195 +        policy_dir = string.join(policy_dir_list, "/") + "/"
   3.196 +    else:
   3.197 +        policy_dir = ""
   3.198 +
   3.199 +    map_filename = policy_dir_prefix + "/" + policy_dir + policy_file + ".map"
   3.200 +    # check if it is there, if not check if policy file is there
   3.201 +    if not os.path.isfile(map_filename):
   3.202 +        policy_filename =  policy_dir_prefix + "/" + policy_dir + policy_file + "-security_policy.xml"
   3.203 +        if not os.path.isfile(policy_filename):
   3.204 +            err("Policy file \'" + policy_filename + "\' not found.")
   3.205 +        else:
   3.206 +            err("Mapping file \'" + map_filename + "\' not found." +
   3.207 +                " Use xm makepolicy to create it.")
   3.208 +
   3.209 +    f = open(map_filename)
   3.210 +    for line in f:
   3.211 +        if policy_reference_entry_re.match(line):
   3.212 +            l = line.split()
   3.213 +            if (len(l) == 2) and (l[1] == policyname):
   3.214 +                map_file_ok = True
   3.215 +        elif primary_entry_re.match(line):
   3.216 +            l = line.split()
   3.217 +            if len(l) == 2:
   3.218 +                primary = l[1]
   3.219 +        elif secondary_entry_re.match(line):
   3.220 +            l = line.split()
   3.221 +            if len(l) == 2:
   3.222 +                secondary = l[1]
   3.223 +    f.close()
   3.224 +    f = open(map_filename)
   3.225 +    if map_file_ok and primary and secondary:
   3.226 +        return (primary, secondary, f, True)
   3.227 +    else:
   3.228 +        err("Mapping file inconsistencies found. Try makepolicy to create a new one.")
   3.229 +
   3.230 +
   3.231 +
   3.232 +def ssidref2label(ssidref_var):
   3.233 +    """
   3.234 +    returns labelname corresponding to ssidref;
   3.235 +    maps current policy to default directory
   3.236 +    to find mapping file
   3.237 +    """
   3.238 +    #1. translated permitted input formats
   3.239 +    if isinstance(ssidref_var, str):
   3.240 +        ssidref_var.strip()
   3.241 +        if ssidref_var[0:2] == "0x":
   3.242 +            ssidref = int(ssidref_var[2:], 16)
   3.243 +        else:
   3.244 +            ssidref = int(ssidref_var)
   3.245 +    elif isinstance(ssidref_var, int):
   3.246 +        ssidref = ssidref_var
   3.247 +    else:
   3.248 +        err("Instance type of ssidref not supported (must be of type 'str' or 'int')")
   3.249 +
   3.250 +    (primary, secondary, f, pol_exists) = getmapfile(None)
   3.251 +    if not f:
   3.252 +        if (pol_exists):
   3.253 +            err("Mapping file for policy \'" + policyname + "\' not found.\n" +
   3.254 +                "Please use makepolicy command to create mapping file!")
   3.255 +        else:
   3.256 +            err("Policy file for \'" + active_policy + "\' not found.")
   3.257 +
   3.258 +    #2. get labelnames for both ssidref parts
   3.259 +    pri_ssid = ssidref & 0xffff
   3.260 +    sec_ssid = ssidref >> 16
   3.261 +    pri_labels = []
   3.262 +    sec_labels = []
   3.263 +    labels = []
   3.264 +
   3.265 +    for line in f:
   3.266 +        l = line.split()
   3.267 +        if (len(l) < 5) or (l[0] != "LABEL->SSID"):
   3.268 +            continue
   3.269 +        if primary and (l[2] == primary) and (int(l[4], 16) == pri_ssid):
   3.270 +            pri_labels.append(l[3])
   3.271 +        if secondary and (l[2] == secondary) and (int(l[4], 16) == sec_ssid):
   3.272 +            sec_labels.append(l[3])
   3.273 +    f.close()
   3.274 +
   3.275 +    #3. get the label that is in both lists (combination must be a single label)
   3.276 +    if secondary == "NULL":
   3.277 +        labels = pri_labels
   3.278 +    else:
   3.279 +        for i in pri_labels:
   3.280 +            for j in sec_labels:
   3.281 +                if (i==j):
   3.282 +                    labels.append(i)
   3.283 +    if len(labels) != 1:
   3.284 +        err("Label for ssidref \'" +  str(ssidref) +
   3.285 +            "\' unknown or not unique in policy \'" + active_policy + "\'")
   3.286 +
   3.287 +    return labels[0]
   3.288 +
   3.289 +
   3.290 +
   3.291 +def label2ssidref(labelname, policyname):
   3.292 +    """
   3.293 +    returns ssidref corresponding to labelname;
   3.294 +    maps current policy to default directory
   3.295 +    to find mapping file    """
   3.296 +
   3.297 +    if policyname in ['NULL', 'INACTIVE', 'DEFAULT']:
   3.298 +        err("Cannot translate labels for \'" + policyname + "\' policy.")
   3.299 +
   3.300 +    (primary, secondary, f, pol_exists) = getmapfile(policyname)
   3.301 +
   3.302 +    #2. get labelnames for ssidref parts and find a common label
   3.303 +    pri_ssid = []
   3.304 +    sec_ssid = []
   3.305 +    for line in f:
   3.306 +        l = line.split()
   3.307 +        if (len(l) < 5) or (l[0] != "LABEL->SSID"):
   3.308 +            continue
   3.309 +        if primary and (l[2] == primary) and (l[3] == labelname):
   3.310 +            pri_ssid.append(int(l[4], 16))
   3.311 +        if secondary and (l[2] == secondary) and (l[3] == labelname):
   3.312 +            sec_ssid.append(int(l[4], 16))
   3.313 +    f.close()
   3.314 +
   3.315 +    #3. sanity check and composition of ssidref
   3.316 +    if (len(pri_ssid) == 0) or ((len(sec_ssid) == 0) and (secondary != "NULL")):
   3.317 +        err("Label \'" + labelname + "\' not found.")
   3.318 +    elif (len(pri_ssid) > 1) or (len(sec_ssid) > 1):
   3.319 +        err("Label \'" + labelname + "\' not unique in policy (policy error)")
   3.320 +    if secondary == "NULL":
   3.321 +        return pri_ssid[0]
   3.322 +    else:
   3.323 +        return (sec_ssid[0] << 16) | pri_ssid[0]
   3.324 +
   3.325 +
   3.326 +
   3.327 +def refresh_ssidref(config):
   3.328 +    """
   3.329 +    looks up ssidref from security field
   3.330 +    and refreshes the value if label exists
   3.331 +    """
   3.332 +    #called by dom0, policy could have changed after xen.utils.security was initialized
   3.333 +    refresh_security_policy()
   3.334 +
   3.335 +    security = None
   3.336 +    if isinstance(config, dict):
   3.337 +        security = config['security']
   3.338 +    elif isinstance(config, list):
   3.339 +        security = sxp.child_value(config, 'security',)
   3.340 +    else:
   3.341 +        err("Instance type of config parameter not supported.")
   3.342 +    if not security:
   3.343 +        #nothing to do (no security label attached)
   3.344 +        return config
   3.345 +
   3.346 +    policyname = None
   3.347 +    labelname = None
   3.348 +    # compose new security field
   3.349 +    for idx in range(0, len(security)):
   3.350 +        if security[idx][0] == 'ssidref':
   3.351 +            security.pop(idx)
   3.352 +            break
   3.353 +        elif security[idx][0] == 'access_control':
   3.354 +            for jdx in [1, 2]:
   3.355 +                if security[idx][jdx][0] == 'label':
   3.356 +                    labelname = security[idx][jdx][1]
   3.357 +                elif security[idx][jdx][0] == 'policy':
   3.358 +                    policyname = security[idx][jdx][1]
   3.359 +                else:
   3.360 +                    err("Illegal field in access_control")
   3.361 +    #verify policy is correct
   3.362 +    if active_policy != policyname:
   3.363 +        err("Policy \'" + policyname + "\' in label does not match active policy \'"
   3.364 +            + active_policy +"\'!")
   3.365 +
   3.366 +    new_ssidref = label2ssidref(labelname, policyname)
   3.367 +    if not new_ssidref:
   3.368 +        err("SSIDREF refresh failed!")
   3.369 +
   3.370 +    security.append([ 'ssidref',str(new_ssidref)])
   3.371 +    security = ['security', security ]
   3.372 +
   3.373 +    for idx in range(0,len(config)):
   3.374 +        if config[idx][0] == 'security':
   3.375 +            config.pop(idx)
   3.376 +            break
   3.377 +        config.append(security)
   3.378 +
   3.379 +
   3.380 +
   3.381 +def get_ssid(domain):
   3.382 +    """
   3.383 +    enables domains to retrieve the label / ssidref of a running domain
   3.384 +    """
   3.385 +    if not on():
   3.386 +        err("No policy active.")
   3.387 +
   3.388 +    if isinstance(domain, str):
   3.389 +        domain_int = int(domain)
   3.390 +    elif isinstance(domain, int):
   3.391 +        domain_int = domain
   3.392 +    else:
   3.393 +        err("Illegal parameter type.")
   3.394 +    try:
   3.395 +        ssid_info = acm.getssid(int(domain_int))
   3.396 +    except:
   3.397 +        err("Cannot determine security information.")
   3.398 +
   3.399 +    if active_policy in ["DEFAULT"]:
   3.400 +        label = "DEFAULT"
   3.401 +    else:
   3.402 +        label = ssidref2label(ssid_info["ssidref"])
   3.403 +    return(ssid_info["policyreference"],
   3.404 +           label,
   3.405 +           ssid_info["policytype"],
   3.406 +           ssid_info["ssidref"])
   3.407 +
   3.408 +
   3.409 +
   3.410 +def get_decision(arg1, arg2):
   3.411 +    """
   3.412 +    enables domains to retrieve access control decisions from
   3.413 +    the hypervisor Access Control Module.
   3.414 +    IN: args format = ['domid', id] or ['ssidref', ssidref]
   3.415 +    or ['access_control', ['policy', policy], ['label', label]]
   3.416 +    """
   3.417 +
   3.418 +    if not on():
   3.419 +        err("No policy active.")
   3.420 +
   3.421 +    #translate labels before calling low-level function
   3.422 +    if arg1[0] == 'access_control':
   3.423 +        if (arg1[1][0] != 'policy') or (arg1[2][0] != 'label') :
   3.424 +            err("Argument type not supported.")
   3.425 +        ssidref = label2ssidref(arg1[2][1], arg1[1][1])
   3.426 +        arg1 = ['ssidref', str(ssidref)]
   3.427 +    if arg2[0] == 'access_control':
   3.428 +        if (arg2[1][0] != 'policy') or (arg2[2][0] != 'label') :
   3.429 +            err("Argument type not supported.")
   3.430 +        ssidref = label2ssidref(arg2[2][1], arg2[1][1])
   3.431 +        arg2 = ['ssidref', str(ssidref)]
   3.432 +    try:
   3.433 +        decision = acm.getdecision(arg1[0], arg1[1], arg2[0], arg2[1])
   3.434 +    except:
   3.435 +        err("Cannot determine decision.")
   3.436 +
   3.437 +    if decision:
   3.438 +        return decision
   3.439 +    else:
   3.440 +        err("Cannot determine decision (Invalid parameter).")
   3.441 +
   3.442 +
   3.443 +
   3.444 +def make_policy(policy_name):
   3.445 +    policy_file = string.join(string.split(policy_name, "."), "/")
   3.446 +    if not os.path.isfile(policy_dir_prefix + "/" + policy_file + "-security_policy.xml"):
   3.447 +        err("Unknown policy \'" + policy_name + "\'")
   3.448 +
   3.449 +    (ret, output) = commands.getstatusoutput(xensec_xml2bin + " -d " + policy_dir_prefix + " " + policy_file)
   3.450 +    if ret:
   3.451 +        err("Creating policy failed:\n" + output)
   3.452 +
   3.453 +
   3.454 +
   3.455 +def load_policy(policy_name):
   3.456 +    global active_policy
   3.457 +    policy_file = policy_dir_prefix + "/" + string.join(string.split(policy_name, "."), "/")
   3.458 +    if not os.path.isfile(policy_file + ".bin"):
   3.459 +        if os.path.isfile(policy_file + "-security_policy.xml"):
   3.460 +            err("Binary file does not exist." +
   3.461 +                "Please use makepolicy to build the policy binary.")
   3.462 +        else:
   3.463 +            err("Unknown Policy " + policy_name)
   3.464 +
   3.465 +    #require this policy to be the first or the same as installed
   3.466 +    if active_policy not in ['DEFAULT', policy_name]:
   3.467 +        err("Active policy \'" + active_policy +
   3.468 +            "\' incompatible with new policy \'" + policy_name + "\'")
   3.469 +    (ret, output) = commands.getstatusoutput(xensec_tool + " loadpolicy " + policy_file + ".bin")
   3.470 +    if ret:
   3.471 +        err("Loading policy failed:\n" + output)
   3.472 +    else:
   3.473 +        # refresh active policy
   3.474 +        refresh_security_policy()
   3.475 +
   3.476 +
   3.477 +
   3.478 +def dump_policy():
   3.479 +    if active_policy in ['NULL', 'INACTIVE']:
   3.480 +        err("\'" + active_policy + "\' policy. Nothing to dump.")
   3.481 +
   3.482 +    (ret, output) = commands.getstatusoutput(xensec_tool + " getpolicy")
   3.483 +    if ret:
   3.484 +       err("Dumping hypervisor policy failed:\n" + output)
   3.485 +    print output
   3.486 +
   3.487 +
   3.488 +
   3.489 +def list_labels(policy_name, condition):
   3.490 +    if (not policy_name) and (active_policy) in ["NULL", "INACTIVE", "DEFAULT"]:
   3.491 +        err("Current policy \'" + active_policy + "\' has no labels defined.\n")
   3.492 +
   3.493 +    (primary, secondary, f, pol_exists) = getmapfile(policy_name)
   3.494 +    if not f:
   3.495 +        if pol_exists:
   3.496 +            err("Cannot find mapfile for policy \'" + policy_name +
   3.497 +                "\'.\nPlease use makepolicy to create mapping file.")
   3.498 +        else:
   3.499 +            err("Unknown policy \'" + policy_name + "\'")
   3.500 +
   3.501 +    labels = []
   3.502 +    for line in f:
   3.503 +        if condition.match(line):
   3.504 +            label = line.split()[3]
   3.505 +            if label not in labels:
   3.506 +                labels.append(label)
   3.507 +    return labels
     4.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     4.2 +++ b/tools/python/xen/xm/addlabel.py	Mon Apr 24 10:58:25 2006 +0100
     4.3 @@ -0,0 +1,76 @@
     4.4 +#============================================================================
     4.5 +# This library is free software; you can redistribute it and/or
     4.6 +# modify it under the terms of version 2.1 of the GNU Lesser General Public
     4.7 +# License as published by the Free Software Foundation.
     4.8 +#
     4.9 +# This library is distributed in the hope that it will be useful,
    4.10 +# but WITHOUT ANY WARRANTY; without even the implied warranty of
    4.11 +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    4.12 +# Lesser General Public License for more details.
    4.13 +#
    4.14 +# You should have received a copy of the GNU Lesser General Public
    4.15 +# License along with this library; if not, write to the Free Software
    4.16 +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
    4.17 +#============================================================================
    4.18 +# Copyright (C) 2006 International Business Machines Corp.
    4.19 +# Author: Reiner Sailer <sailer@us.ibm.com>
    4.20 +#============================================================================
    4.21 +
    4.22 +"""Labeling a domain configuration file.
    4.23 +"""
    4.24 +import sys, os
    4.25 +import traceback
    4.26 +
    4.27 +
    4.28 +from xen.util.security import ACMError, err, active_policy, label2ssidref, on, access_control_re
    4.29 +
    4.30 +
    4.31 +def usage():
    4.32 +    print "\nUsage: xm addlabel <configfile> <label> [<policy>]\n"
    4.33 +    print "  This program adds an acm_label entry into the 'configfile'."
    4.34 +    print "  It derives the policy from the running hypervisor if it"
    4.35 +    print "  is not given (optional parameter). If the configfile is"
    4.36 +    print "  already labeled, then addlabel fails.\n"
    4.37 +    err("Usage")
    4.38 +
    4.39 +
    4.40 +def main(argv):
    4.41 +    try:
    4.42 +        policyref = None
    4.43 +        if len(argv) not in [3,4]:
    4.44 +            usage()
    4.45 +        configfile = argv[1]
    4.46 +        label = argv[2]
    4.47 +
    4.48 +        if len(argv) == 4:
    4.49 +            policyref = argv[3]
    4.50 +        elif on():
    4.51 +            policyref = active_policy
    4.52 +        else:
    4.53 +            err("No active policy. Policy must be specified in command line.")
    4.54 +
    4.55 +        #sanity checks: make sure this label can be instantiated later on
    4.56 +        ssidref = label2ssidref(label, policyref)
    4.57 +
    4.58 +        new_label = "access_control = ['policy=%s,label=%s']\n" % (policyref, label)
    4.59 +        if not os.path.isfile(configfile):
    4.60 +            err("Configuration file \'" + configfile + "\' not found.")
    4.61 +        config_fd = open(configfile, "ra+")
    4.62 +        for line in config_fd:
    4.63 +            if not access_control_re.match(line):
    4.64 +                continue
    4.65 +            config_fd.close()
    4.66 +            err("Config file \'" + configfile + "\' is already labeled.")
    4.67 +        config_fd.write(new_label)
    4.68 +        config_fd.close()
    4.69 +
    4.70 +    except ACMError:
    4.71 +        pass
    4.72 +    except:
    4.73 +        traceback.print_exc(limit=1)
    4.74 +
    4.75 +
    4.76 +if __name__ == '__main__':
    4.77 +    main(sys.argv)
    4.78 +
    4.79 +
     5.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     5.2 +++ b/tools/python/xen/xm/cfgbootpolicy.py	Mon Apr 24 10:58:25 2006 +0100
     5.3 @@ -0,0 +1,188 @@
     5.4 +#============================================================================
     5.5 +# This library is free software; you can redistribute it and/or
     5.6 +# modify it under the terms of version 2.1 of the GNU Lesser General Public
     5.7 +# License as published by the Free Software Foundation.
     5.8 +#
     5.9 +# This library is distributed in the hope that it will be useful,
    5.10 +# but WITHOUT ANY WARRANTY; without even the implied warranty of
    5.11 +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    5.12 +# Lesser General Public License for more details.
    5.13 +#
    5.14 +# You should have received a copy of the GNU Lesser General Public
    5.15 +# License along with this library; if not, write to the Free Software
    5.16 +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
    5.17 +#============================================================================
    5.18 +# Copyright (C) 2006 International Business Machines Corp.
    5.19 +# Author: Reiner Sailer <sailer@us.ibm.com>
    5.20 +#============================================================================
    5.21 +"""Configuring a security policy into the boot configuration
    5.22 +"""
    5.23 +
    5.24 +import sys
    5.25 +import traceback
    5.26 +import tempfile
    5.27 +import os, stat
    5.28 +import re
    5.29 +import commands
    5.30 +import shutil
    5.31 +import string
    5.32 +from xen.util.security import ACMError, err
    5.33 +from xen.util.security import policy_dir_prefix, boot_filename, xen_title_re
    5.34 +from xen.util.security import any_title_re, xen_kernel_re, kernel_ver_re, any_module_re
    5.35 +from xen.util.security import empty_line_re, binary_name_re, policy_name_re
    5.36 +
    5.37 +
    5.38 +def usage():
    5.39 +    print "\nUsage: xm cfgbootpolicy <policy> [<kernelversion>]\n"
    5.40 +    print "  Adds a 'module' line to the Xen grub.conf entry"
    5.41 +    print "  so that xen boots into a specific access control"
    5.42 +    print "  policy. If kernelversion is not given, then this"
    5.43 +    print "  script tries to determine it by looking for a grub"
    5.44 +    print "  entry with a line kernel xen.* If there are multiple"
    5.45 +    print "  Xen entries, then it must be called with an explicit"
    5.46 +    print "  version (it will fail otherwise).\n"
    5.47 +    err("Usage")
    5.48 +
    5.49 +
    5.50 +
    5.51 +def determine_kernelversion(user_specified):
    5.52 +    within_xen_title = 0
    5.53 +    within_xen_entry = 0
    5.54 +    version_list = []
    5.55 +    guess_version = None
    5.56 +
    5.57 +    grub_fd = open(boot_filename)
    5.58 +    for line in grub_fd:
    5.59 +        if xen_title_re.match(line):
    5.60 +            within_xen_title = 1
    5.61 +        elif within_xen_title and xen_kernel_re.match(line):
    5.62 +            within_xen_entry = 1
    5.63 +        elif within_xen_title and within_xen_entry and kernel_ver_re.match(line):
    5.64 +            for i in line.split():
    5.65 +                if (i.find("vmlinuz-") >= 0):
    5.66 +                    # skip start until "vmlinuz-"
    5.67 +                    guess_version = i[i.find("vmlinuz-") + len("vmlinuz-"):]
    5.68 +                    if user_specified:
    5.69 +                        if (guess_version == user_specified):
    5.70 +                            version_list.append(guess_version)
    5.71 +                    else:
    5.72 +                        version_list.append(guess_version)
    5.73 +        elif len(line.split()) > 0:
    5.74 +            if line.split()[0] == "title":
    5.75 +                within_xen_title = 0
    5.76 +                within_xen_entry = 0
    5.77 +    if len(version_list) > 1:
    5.78 +        err("Cannot decide between entries for kernels: " + version_list)
    5.79 +    elif len(version_list) == 0:
    5.80 +        err("Cannot find a boot entry candidate (please create a Xen boot entry first).")
    5.81 +    else:
    5.82 +        return version_list[0]
    5.83 +
    5.84 +
    5.85 +
    5.86 +def insert_policy(boot_file, kernel_version, policy_name):
    5.87 +    """
    5.88 +    inserts policy binary file as last line of the grub entry
    5.89 +    matching the kernel_version version
    5.90 +    """
    5.91 +    within_xen_title = 0
    5.92 +    within_xen_entry = 0
    5.93 +    insert_at_end_of_entry = 0
    5.94 +    path_prefix = ''
    5.95 +    done = False
    5.96 +    (tmp_fd, tmp_grub) = tempfile.mkstemp()
    5.97 +    #follow symlink since menue.lst might be linked to grub.conf
    5.98 +    if stat.S_ISLNK(os.lstat(boot_file)[stat.ST_MODE]):
    5.99 +        new_name = os.readlink(boot_file)
   5.100 +        if new_name[0] == "/":
   5.101 +            boot_file = new_name
   5.102 +        else:
   5.103 +            path = boot_file.split('/')
   5.104 +            path[len(path)-1] = new_name
   5.105 +            boot_file = '/'.join(path)
   5.106 +        if not os.path.exists(boot_file):
   5.107 +            err("Boot file \'" + boot_file + "\' not found.")
   5.108 +    grub_fd = open(boot_file)
   5.109 +    for line in grub_fd:
   5.110 +        if xen_title_re.match(line):
   5.111 +            within_xen_title = 1
   5.112 +        elif within_xen_title and xen_kernel_re.match(line):
   5.113 +            within_xen_entry = 1
   5.114 +        elif within_xen_title and within_xen_entry and kernel_ver_re.match(line):
   5.115 +            for i in line.split():
   5.116 +                if (i.find("vmlinuz-") >= 0):
   5.117 +                    if  kernel_version == i[i.find("vmlinuz-") + len("vmlinuz-"):]:
   5.118 +                        insert_at_end_of_entry = 1
   5.119 +                        path_prefix = i[0:i.find("vmlinuz-")]
   5.120 +        elif any_module_re.match(line) and insert_at_end_of_entry:
   5.121 +            if binary_name_re.match(line):
   5.122 +                #delete existing policy module line
   5.123 +                line=''
   5.124 +        elif any_title_re.match(line):
   5.125 +            within_xen_title = 0
   5.126 +            within_xen_entry = 0
   5.127 +
   5.128 +        if (empty_line_re.match(line) or any_title_re.match(line)) and insert_at_end_of_entry:
   5.129 +            #newline or new title: we insert the policy module line here
   5.130 +            os.write(tmp_fd, "\tmodule " + path_prefix + policy_name + ".bin\n")
   5.131 +            insert_at_end_of_entry = 0
   5.132 +        #write the line that was read (except potential existing policy entry)
   5.133 +        os.write(tmp_fd, line)
   5.134 +
   5.135 +    if insert_at_end_of_entry:
   5.136 +        #last entry, no empty line at end of file
   5.137 +        os.write(tmp_fd, "\tmodule " + path_prefix + policy_name + ".bin\n")
   5.138 +
   5.139 +    #temp file might be destroyed when closing it, first copy ...
   5.140 +    shutil.move(boot_file, boot_file+"_save")
   5.141 +    shutil.copyfile(tmp_grub, boot_file)
   5.142 +    os.close(tmp_fd)
   5.143 +    #temp file did not disappear on my system ...
   5.144 +    try:
   5.145 +        os.remove(tmp_grub)
   5.146 +    except:
   5.147 +        pass
   5.148 +
   5.149 +
   5.150 +
   5.151 +def main(argv):
   5.152 +    try:
   5.153 +        user_kver = None
   5.154 +        policy = None
   5.155 +        if len(argv) == 2:
   5.156 +            policy = argv[1]
   5.157 +        elif len(argv) == 3:
   5.158 +            policy = argv[1]
   5.159 +            user_kver = argv[2]
   5.160 +        else:
   5.161 +            usage()
   5.162 +
   5.163 +        if not policy_name_re.match(policy):
   5.164 +            err("Illegal policy name \'" + policy + "\'")
   5.165 +
   5.166 +        policy_file = policy_dir_prefix + "/" + string.join(string.split(policy, "."), "/")
   5.167 +        src_binary_policy_file = policy_file + ".bin"
   5.168 +        #check if .bin exists or if policy file exists
   5.169 +        if not os.path.isfile(src_binary_policy_file):
   5.170 +            if not os.path.isfile(policy_file + "-security_policy.xml"):
   5.171 +                err("Unknown policy \'" + policy +"\'")
   5.172 +            else:
   5.173 +                err("Cannot find binary file for policy \'" + policy +
   5.174 +                    "\'. Please use makepolicy to create binary file.")
   5.175 +        dst_binary_policy_file = "/boot/" + policy + ".bin"
   5.176 +        shutil.copyfile(src_binary_policy_file, dst_binary_policy_file)
   5.177 +
   5.178 +        kernel_version = determine_kernelversion(user_kver)
   5.179 +        insert_policy(boot_filename, kernel_version, policy)
   5.180 +        print "Boot entry created and \'%s\' copied to /boot" % (policy + ".bin")
   5.181 +
   5.182 +    except ACMError:
   5.183 +        pass
   5.184 +    except:
   5.185 +        traceback.print_exc(limit=1)
   5.186 +
   5.187 +
   5.188 +
   5.189 +if __name__ == '__main__':
   5.190 +    main(sys.argv)
   5.191 +
     6.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     6.2 +++ b/tools/python/xen/xm/dumppolicy.py	Mon Apr 24 10:58:25 2006 +0100
     6.3 @@ -0,0 +1,49 @@
     6.4 +#============================================================================
     6.5 +# This library is free software; you can redistribute it and/or
     6.6 +# modify it under the terms of version 2.1 of the GNU Lesser General Public
     6.7 +# License as published by the Free Software Foundation.
     6.8 +#
     6.9 +# This library is distributed in the hope that it will be useful,
    6.10 +# but WITHOUT ANY WARRANTY; without even the implied warranty of
    6.11 +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    6.12 +# Lesser General Public License for more details.
    6.13 +#
    6.14 +# You should have received a copy of the GNU Lesser General Public
    6.15 +# License along with this library; if not, write to the Free Software
    6.16 +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
    6.17 +#============================================================================
    6.18 +# Copyright (C) 2006 International Business Machines Corp.
    6.19 +# Author: Reiner Sailer <sailer@us.ibm.com>
    6.20 +#============================================================================
    6.21 +"""Display currently enforced policy (low-level hypervisor representation).
    6.22 +"""
    6.23 +import sys
    6.24 +import traceback
    6.25 +import os
    6.26 +import commands
    6.27 +import shutil
    6.28 +import string
    6.29 +from xen.util.security import ACMError, err, dump_policy
    6.30 +
    6.31 +
    6.32 +def usage():
    6.33 +    print "\nUsage: xm dumppolicy\n"
    6.34 +    print " Retrieve and print currently enforced"
    6.35 +    print " hypervisor policy information (low-level).\n"
    6.36 +    err("Usage")
    6.37 +
    6.38 +
    6.39 +def main(argv):
    6.40 +    try:
    6.41 +        dump_policy()
    6.42 +
    6.43 +    except ACMError:
    6.44 +        pass
    6.45 +    except:
    6.46 +        traceback.print_exc(limit=1)
    6.47 +
    6.48 +
    6.49 +if __name__ == '__main__':
    6.50 +    main(sys.argv)
    6.51 +
    6.52 +
     7.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     7.2 +++ b/tools/python/xen/xm/labels.py	Mon Apr 24 10:58:25 2006 +0100
     7.3 @@ -0,0 +1,85 @@
     7.4 +#============================================================================
     7.5 +# This library is free software; you can redistribute it and/or
     7.6 +# modify it under the terms of version 2.1 of the GNU Lesser General Public
     7.7 +# License as published by the Free Software Foundation.
     7.8 +#
     7.9 +# This library is distributed in the hope that it will be useful,
    7.10 +# but WITHOUT ANY WARRANTY; without even the implied warranty of
    7.11 +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    7.12 +# Lesser General Public License for more details.
    7.13 +#
    7.14 +# You should have received a copy of the GNU Lesser General Public
    7.15 +# License along with this library; if not, write to the Free Software
    7.16 +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
    7.17 +#============================================================================
    7.18 +# Copyright (C) 2006 International Business Machines Corp.
    7.19 +# Author: Reiner Sailer <sailer@us.ibm.com>
    7.20 +#============================================================================
    7.21 +
    7.22 +"""Listing available labels for a policy.
    7.23 +"""
    7.24 +import sys
    7.25 +import traceback
    7.26 +import os
    7.27 +import commands
    7.28 +import shutil
    7.29 +import string
    7.30 +from xen.util.security import ACMError, err, list_labels, active_policy
    7.31 +from xen.util.security import vm_label_re, res_label_re, all_label_re
    7.32 +
    7.33 +def usage():
    7.34 +    print "\nUsage: xm labels [<policy>] [<type=dom|res|any>]\n"
    7.35 +    print " Prints labels of the specified type (default is dom)"
    7.36 +    print " that are defined in policy (default is current"
    7.37 +    print " hypervisor policy).\n"
    7.38 +    err("Usage")
    7.39 +
    7.40 +
    7.41 +def main(argv):
    7.42 +    try:
    7.43 +        policy = None
    7.44 +        type = None
    7.45 +        for i in argv[1:]:
    7.46 +            i_s = string.split(i, '=')
    7.47 +            if len(i_s) > 1:
    7.48 +                if (i_s[0] == 'type') and (len(i_s) == 2):
    7.49 +                    if not type:
    7.50 +                        type = i_s[1]
    7.51 +                    else:
    7.52 +                        usage()
    7.53 +                else:
    7.54 +                    usage()
    7.55 +            else:
    7.56 +                if not policy:
    7.57 +                    policy = i
    7.58 +                else:
    7.59 +                    usage()
    7.60 +
    7.61 +        if not policy:
    7.62 +            policy = active_policy
    7.63 +            if active_policy in ['NULL', 'INACTIVE', 'DEFAULT']:
    7.64 +                err("No policy active. Please specify the <policy> parameter.")
    7.65 +
    7.66 +        if not type or (type in ['DOM', 'dom']):
    7.67 +            condition = vm_label_re
    7.68 +        elif type in ['RES', 'res']:
    7.69 +            condition = res_label_re
    7.70 +        elif type in ['ANY', 'any']:
    7.71 +            condition = all_label_re
    7.72 +        else:
    7.73 +            err("Unknown label type \'" + type + "\'")
    7.74 +
    7.75 +        labels = list_labels(policy, condition)
    7.76 +        labels.sort()
    7.77 +        for label in labels:
    7.78 +            print label
    7.79 +    except ACMError:
    7.80 +        pass
    7.81 +    except:
    7.82 +        traceback.print_exc(limit=1)
    7.83 +
    7.84 +
    7.85 +if __name__ == '__main__':
    7.86 +    main(sys.argv)
    7.87 +
    7.88 +
     8.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     8.2 +++ b/tools/python/xen/xm/loadpolicy.py	Mon Apr 24 10:58:25 2006 +0100
     8.3 @@ -0,0 +1,51 @@
     8.4 +#============================================================================
     8.5 +# This library is free software; you can redistribute it and/or
     8.6 +# modify it under the terms of version 2.1 of the GNU Lesser General Public
     8.7 +# License as published by the Free Software Foundation.
     8.8 +#
     8.9 +# This library is distributed in the hope that it will be useful,
    8.10 +# but WITHOUT ANY WARRANTY; without even the implied warranty of
    8.11 +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    8.12 +# Lesser General Public License for more details.
    8.13 +#
    8.14 +# You should have received a copy of the GNU Lesser General Public
    8.15 +# License along with this library; if not, write to the Free Software
    8.16 +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
    8.17 +#============================================================================
    8.18 +# Copyright (C) 2006 International Business Machines Corp.
    8.19 +# Author: Reiner Sailer <sailer@us.ibm.com>
    8.20 +#============================================================================
    8.21 +
    8.22 +"""Loading a compiled binary policy into the hypervisor.
    8.23 +"""
    8.24 +import sys
    8.25 +import traceback
    8.26 +import os
    8.27 +import commands
    8.28 +import shutil
    8.29 +import string
    8.30 +from xen.util.security import ACMError, err, load_policy
    8.31 +
    8.32 +
    8.33 +def usage():
    8.34 +    print "\nUsage: xm loadpolicy <policy>\n"
    8.35 +    print " Load the compiled binary (.bin) policy"
    8.36 +    print " into the running hypervisor.\n"
    8.37 +    err("Usage")
    8.38 +
    8.39 +def main(argv):
    8.40 +    try:
    8.41 +        if len(argv) != 2:
    8.42 +            usage()
    8.43 +        load_policy(argv[1])
    8.44 +    except ACMError:
    8.45 +        pass
    8.46 +    except:
    8.47 +        traceback.print_exc(limit=1)
    8.48 +
    8.49 +
    8.50 +
    8.51 +if __name__ == '__main__':
    8.52 +    main(sys.argv)
    8.53 +
    8.54 +
     9.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     9.2 +++ b/tools/python/xen/xm/makepolicy.py	Mon Apr 24 10:58:25 2006 +0100
     9.3 @@ -0,0 +1,53 @@
     9.4 +#============================================================================
     9.5 +# This library is free software; you can redistribute it and/or
     9.6 +# modify it under the terms of version 2.1 of the GNU Lesser General Public
     9.7 +# License as published by the Free Software Foundation.
     9.8 +#
     9.9 +# This library is distributed in the hope that it will be useful,
    9.10 +# but WITHOUT ANY WARRANTY; without even the implied warranty of
    9.11 +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    9.12 +# Lesser General Public License for more details.
    9.13 +#
    9.14 +# You should have received a copy of the GNU Lesser General Public
    9.15 +# License along with this library; if not, write to the Free Software
    9.16 +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
    9.17 +#============================================================================
    9.18 +# Copyright (C) 2006 International Business Machines Corp.
    9.19 +# Author: Reiner Sailer <sailer@us.ibm.com>
    9.20 +#============================================================================
    9.21 +"""Compiling a XML source policy file into mapping and binary versions.
    9.22 +"""
    9.23 +import sys
    9.24 +import traceback
    9.25 +import os
    9.26 +import commands
    9.27 +import shutil
    9.28 +import string
    9.29 +from xen.util.security import ACMError, err, make_policy
    9.30 +
    9.31 +
    9.32 +def usage():
    9.33 +    print "\nUsage: xm makepolicy <policy>\n"
    9.34 +    print " Translate an XML source policy and create"
    9.35 +    print " mapping file and binary policy.\n"
    9.36 +    err("Usage")
    9.37 +
    9.38 +
    9.39 +
    9.40 +def main(argv):
    9.41 +    try:
    9.42 +        if len(argv) != 2:
    9.43 +            usage()
    9.44 +        make_policy(argv[1])
    9.45 +
    9.46 +    except ACMError:
    9.47 +        pass
    9.48 +    except:
    9.49 +        traceback.print_exc(limit=1)
    9.50 +
    9.51 +
    9.52 +
    9.53 +if __name__ == '__main__':
    9.54 +    main(sys.argv)
    9.55 +
    9.56 +
    10.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    10.2 +++ b/tools/security/python/xensec_tools/acm_getdecision	Mon Apr 24 10:58:25 2006 +0100
    10.3 @@ -0,0 +1,55 @@
    10.4 +#!/usr/bin/env python
    10.5 +#  -*- mode: python; -*-
    10.6 +import sys
    10.7 +import traceback
    10.8 +import getopt
    10.9 +
   10.10 +# add fallback path for non-native python path installs if needed
   10.11 +sys.path.insert(-1, '/usr/lib/python')
   10.12 +sys.path.insert(-1, '/usr/lib64/python')
   10.13 +
   10.14 +from xen.util.security import ACMError, err, get_decision, active_policy
   10.15 +
   10.16 +def usage():
   10.17 +    print "Usage: acm_getdecision -i domainid --label labelname"
   10.18 +    print "  Test program illustrating the retrieval of"
   10.19 +    print "  access control decisions from Xen. At this time,"
   10.20 +    print "  only sharing (STE) policy decisions are supported."
   10.21 +    print "  Arguments are two paramters in any combination:"
   10.22 +    print "\t -i domain_id or --domid domain_id"
   10.23 +    print "\t -l labelname or --label labelname"
   10.24 +    print "  Return value:"
   10.25 +    print "\t PERMITTED if access is permitted"
   10.26 +    print "\t DENIED if access is denied"
   10.27 +    print "\t ACMError -- e.g., unknown label or domain id"
   10.28 +    err("Usage")
   10.29 +
   10.30 +try:
   10.31 +
   10.32 +    if len(sys.argv) != 5:
   10.33 +        usage()
   10.34 +
   10.35 +    decision_args = []
   10.36 +
   10.37 +    for idx in range(1, len(sys.argv), 2):
   10.38 +        if sys.argv[idx] in ['-i', '--domid']:
   10.39 +            decision_args.append(['domid', sys.argv[idx+1]])
   10.40 +        elif sys.argv[idx] in ['-l', '--label']:
   10.41 +            decision_args.append(['access_control',
   10.42 +                                  ['policy', active_policy],
   10.43 +                                  ['label', sys.argv[idx+1]]
   10.44 +                                  ])
   10.45 +        else:
   10.46 +            print "unknown argument %s" % sys.argv[idx]
   10.47 +            usage()
   10.48 +
   10.49 +    if len(decision_args) != 2:
   10.50 +        print "too many arguments"
   10.51 +        usage()
   10.52 +
   10.53 +    print get_decision(decision_args[0], decision_args[1])
   10.54 +
   10.55 +except ACMError:
   10.56 +	pass
   10.57 +except:
   10.58 +    traceback.print_exc(limit=1)
    11.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    11.2 +++ b/tools/security/python/xensec_tools/acm_getlabel	Mon Apr 24 10:58:25 2006 +0100
    11.3 @@ -0,0 +1,48 @@
    11.4 +#!/usr/bin/env python
    11.5 +#  -*- mode: python; -*-
    11.6 +import sys
    11.7 +import traceback
    11.8 +import getopt
    11.9 +
   11.10 +# add fallback path for non-native python path installs if needed
   11.11 +sys.path.insert(-1, '/usr/lib/python')
   11.12 +sys.path.insert(-1, '/usr/lib64/python')
   11.13 +
   11.14 +from xen.util.security import ACMError, err, get_ssid
   11.15 +
   11.16 +# getopt.gnu_getopt is better, but only exists in Python 2.3+.  Use
   11.17 +# getopt.getopt if gnu_getopt is not available.  This will mean that options
   11.18 +# may only be specified before positional arguments.
   11.19 +if not hasattr(getopt, 'gnu_getopt'):
   11.20 +    getopt.gnu_getopt = getopt.getopt
   11.21 +
   11.22 +def usage():
   11.23 +    print "Usage: acm_getlabel -i domainid"
   11.24 +    print "  Test program illustrating the retrieval of"
   11.25 +    print "  label information (for domains) from Xen."
   11.26 +    print "  Argument is one paramter describing the domain"
   11.27 +    print "  for which the label is retrieved."
   11.28 +    print "\t -i domain_id or --domid=domain_id"
   11.29 +    print "  Return value:"
   11.30 +    print "\t none -- Error (e.g., unknown ssidref, label, or domain id)"
   11.31 +    print "\t (labelname, policyname, ssidref)"
   11.32 +    err("Usage")
   11.33 +
   11.34 +try:
   11.35 +    domid = None
   11.36 +    (options, params) = getopt.gnu_getopt(sys.argv[1:], ':i:', ['domid='])
   11.37 +    for (k, v) in options:
   11.38 +        if k in ['-i', '--domid']:
   11.39 +            if not domid:
   11.40 +                domid = v
   11.41 +            else:
   11.42 +                usage()
   11.43 +    if not domid:
   11.44 +        usage()
   11.45 +
   11.46 +    print get_ssid(domid)
   11.47 +
   11.48 +except ACMError:
   11.49 +    pass
   11.50 +except:
   11.51 +    traceback.print_exc(limit=1)