source: trunk/packages/xen-common/xen-common/tools/python/xen/xm/addlabel.py @ 34

Last change on this file since 34 was 34, checked in by hartmans, 17 years ago

Add xen and xen-common

File size: 5.2 KB
Line 
1#============================================================================
2# This library is free software; you can redistribute it and/or
3# modify it under the terms of version 2.1 of the GNU Lesser General Public
4# License as published by the Free Software Foundation.
5#
6# This library is distributed in the hope that it will be useful,
7# but WITHOUT ANY WARRANTY; without even the implied warranty of
8# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
9# Lesser General Public License for more details.
10#
11# You should have received a copy of the GNU Lesser General Public
12# License along with this library; if not, write to the Free Software
13# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
14#============================================================================
15# Copyright (C) 2006 International Business Machines Corp.
16# Author: Reiner Sailer <sailer@us.ibm.com>
17# Author: Bryan D. Payne <bdpayne@us.ibm.com>
18#============================================================================
19
20"""Labeling a domain configuration file or a resource.
21"""
22import os
23import sys
24
25from xen.util import dictio
26from xen.util import security
27from xen.xm.opts import OptionError
28
29def help():
30    return """
31    Format: xm addlabel <label> dom <configfile> [<policy>]
32            xm addlabel <label> res <resource> [<policy>]
33   
34    This program adds an acm_label entry into the 'configfile'
35    for a domain or to the global resource label file for a
36    resource. It derives the policy from the running hypervisor
37    if it is not given (optional parameter). If a label already
38    exists for the given domain or resource, then addlabel fails."""
39
40
41def validate_config_file(configfile):
42    """Performs a simple sanity check on the configuration file passed on
43       the command line.  We basically just want to make sure that it's
44       not a domain image file so we check for a few configuration values
45       and then we are satisfied.  Returned 1 on success, otherwise 0.
46    """
47    # read in the config file
48    globs = {}
49    locs = {}
50    try:
51        execfile(configfile, globs, locs)
52    except:
53        print "Invalid configuration file."
54        return 0
55
56    # sanity check on the data from the file
57    count = 0
58    required = ['kernel', 'memory', 'name']
59    for (k, v) in locs.items():
60        if k in required:
61            count += 1
62    if count != 3:
63        print "Invalid configuration file."
64        return 0
65    else:
66        return 1
67
68
69def add_resource_label(label, resource, policyref):
70    """Adds a resource label to the global resource label file.
71    """
72    # sanity check: make sure this label can be instantiated later on
73    ssidref = security.label2ssidref(label, policyref, 'res')
74
75    #build canonical resource name
76    resource = security.unify_resname(resource)
77
78    # see if this resource is already in the file
79    access_control = {}
80    file = security.res_label_filename
81    try:
82        access_control = dictio.dict_read("resources", file)
83    except:
84        print "Resource file not found, creating new file at:"
85        print "%s" % (file)
86
87    if access_control.has_key(resource):
88        security.err("This resource is already labeled.")
89
90    # write the data to file
91    new_entry = { resource : tuple([policyref, label]) }
92    access_control.update(new_entry)
93    dictio.dict_write(access_control, "resources", file)
94
95
96def add_domain_label(label, configfile, policyref):
97    # sanity checks: make sure this label can be instantiated later on
98    ssidref = security.label2ssidref(label, policyref, 'dom')
99
100    new_label = "access_control = ['policy=%s,label=%s']\n" % (policyref, label)
101    if not os.path.isfile(configfile):
102        security.err("Configuration file \'" + configfile + "\' not found.")
103    config_fd = open(configfile, "ra+")
104    for line in config_fd:
105        if not security.access_control_re.match(line):
106            continue
107        config_fd.close()
108        security.err("Config file \'" + configfile + "\' is already labeled.")
109    config_fd.write(new_label)
110    config_fd.close()
111
112
113def main(argv):
114    policyref = None
115    if len(argv) not in (4, 5):
116        raise OptionError('Needs either 2 or 3 arguments')
117   
118    label = argv[1]
119   
120    if len(argv) == 5:
121        policyref = argv[4]
122    elif security.on():
123        policyref = security.active_policy
124    else:
125        raise OptionError("No active policy. Must specify policy on the "
126                          "command line.")
127
128    if argv[2].lower() == "dom":
129        configfile = argv[3]
130        if configfile[0] != '/':
131            for prefix in [".", "/etc/xen"]:
132                configfile = prefix + "/" + configfile
133                if os.path.isfile(configfile):
134                    break
135        if not validate_config_file(configfile):
136            raise OptionError('Invalid config file')
137        else:
138            add_domain_label(label, configfile, policyref)
139    elif argv[2].lower() == "res":
140        resource = argv[3]
141        add_resource_label(label, resource, policyref)
142    else:
143        raise OptionError('Need to specify either "dom" or "res" as '
144                          'object to add label to.')
145           
146if __name__ == '__main__':
147    try:
148        main(sys.argv)
149    except Exception, e:
150        sys.stderr.write('Error: %s\n' % str(e))
151        sys.exit(-1)
152   
153
154
Note: See TracBrowser for help on using the repository browser.