Пример #1
0
def main(argv):

    if len(argv) != 3:
        raise OptionError('Requires 2 arguments')

    if argv[1].lower() == "dom":
        configfile = argv[2]
        rm_domain_label(configfile)
    elif argv[1].lower() == "mgt":
        domain = argv[2]
        rm_domain_label_xapi(domain)
    elif argv[1].lower().startswith("vif-"):
        try:
            idx = int(argv[1][4:])
            if idx < 0:
                raise
        except:
            raise OptionError("Bad VIF device index.")
        vmname = argv[2]
        rm_vif_label(vmname, idx)
    elif argv[1].lower() == "res":
        resource = argv[2]
        rm_resource_label(resource)
    else:
        raise OptionError('Unrecognised type argument: %s' % argv[1])
Пример #2
0
def main(argv):
    if len(argv) != 3:
        raise OptionError('Requires 2 arguments')

    if argv[1].lower() == "dom":
        configfile = argv[2]
        get_domain_label(configfile)
    elif argv[1].lower() == "mgt":
        domainname = argv[2]
        get_domain_label_xapi(domainname)
    elif argv[1].lower() == "res":
        resource = argv[2]
        get_resource_label(resource)
    elif argv[1].lower().startswith("vif-"):
        try:
            idx = int(argv[1][4:])
            if idx < 0:
                raise
        except:
            raise OptionError("Bad VIF device index.")
        vmname = argv[2]
        get_vif_label(vmname, idx)
    else:
        raise OptionError('First subcommand argument must be "dom"'
                          ', "mgt" or "res"')
Пример #3
0
def rm_vif_label(vmname, idx):
    if xm_main.serverType != xm_main.SERVER_XEN_API:
        raise OptionError('Need to be configure for using xen-api.')
    vm_refs = server.xenapi.VM.get_by_name_label(vmname)
    if len(vm_refs) == 0:
        raise OptionError('A VM with the name %s does not exist.' % vmname)
    vif_refs = server.xenapi.VM.get_VIFs(vm_refs[0])
    if len(vif_refs) <= idx:
        raise OptionError("Bad VIF index.")
    vif_ref = server.xenapi.VIF.get_by_uuid(vif_refs[idx])
    if not vif_ref:
        raise security.XSMError("A VIF with this UUID does not exist.")
    try:
        old_lab = server.xenapi.VIF.get_security_label(vif_ref)
        if old_lab != "":
            rc = server.xenapi.VIF.set_security_label(vif_ref, "", old_lab)
            if int(rc) != 0:
                raise security.XSMError("Could not remove the label from"
                                        " the VIF.")
            else:
                print "Successfully removed the label from the VIF."
        else:
            raise security.XSMError("VIF is not labeled.")
    except Exception, e:
        raise security.XSMError("Could not remove the label from the VIF: %s" %
                                str(e))
Пример #4
0
def get_login_pwd():
    if xmmain.serverType == xmmain.SERVER_XEN_API:
        try:
            login, password = xmmain.parseAuthentication()
            return (login, password)
        except:
            raise OptionError("Configuration for login/pwd not found. "
                              "Need to run xapi-setup.py?")
    raise OptionError("Xm configuration file not using Xen-API for "
                      "communication with xend.")
Пример #5
0
def setpolicy(policytype, policy_name, flags, overwrite):

    if policytype.upper() == xsconstants.ACM_POLICY_ID:
        xs_type = xsconstants.XS_POLICY_ACM

        for prefix in ['./', install_policy_dir_prefix + "/"]:
            policy_file = prefix + "/".join(policy_name.split(".")) + \
                          "-security_policy.xml"

            if os.path.exists(policy_file):
                break

    elif policytype.upper() == xsconstants.FLASK_POLICY_ID:
        xs_type = xsconstants.XS_POLICY_FLASK
        policy_file = policy_name

    else:
        raise OptionError("Unsupported policytype '%s'." % policytype)

    try:
        f = open(policy_file, "r")
        policy = f.read()
        f.close()
    except:
        raise OptionError("Could not read policy file: %s" % policy_file)

    if xs_type == xsconstants.XS_POLICY_FLASK:
        policy = base64.b64encode(policy)

    if xm_main.serverType == xm_main.SERVER_XEN_API:
        if xs_type != int(server.xenapi.XSPolicy.get_xstype()):
            raise security.XSMError("Policy type not supported.")

        try:
            policystate = server.xenapi.XSPolicy.set_xspolicy(
                xs_type, policy, flags, overwrite)
        except Exception, e:
            raise security.XSMError("An error occurred setting the "
                                    "policy: %s" % str(e))
        xserr = int(policystate['xserr'])
        if xserr != xsconstants.XSERR_SUCCESS:
            txt = "An error occurred trying to set the policy: %s." % \
                   xsconstants.xserr2string(abs(xserr))
            errors = policystate['errors']
            if len(errors) > 0:
                txt += " " + build_hv_error_message(base64.b64decode(errors))
            raise security.XSMError(txt)
        else:
            print "Successfully set the new policy."
            if xs_type == xsconstants.XS_POLICY_ACM:
                getpolicy(False)
Пример #6
0
def get_domain_label_xapi(domain):
    if xm_main.serverType != xm_main.SERVER_XEN_API:
        sec_lab = server.xend.security.get_domain_label(domain)
        if len(sec_lab) > 0 and sec_lab[0] == '\'':
            sec_lab = sec_lab[1:]
    else:
        uuids = server.xenapi.VM.get_by_name_label(domain)
        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 = server.xenapi.VM.get_security_label(uuid)
    print "%s" % sec_lab
Пример #7
0
def get_vif_label(vmname, idx):
    if xm_main.serverType != xm_main.SERVER_XEN_API:
        raise OptionError('xm needs to be configure to use the xen-api.')
    vm_refs = server.xenapi.VM.get_by_name_label(vmname)
    if len(vm_refs) == 0:
        raise OptionError('A VM with the name %s does not exist.' % vmname)
    vif_refs = server.xenapi.VM.get_VIFs(vm_refs[0])
    if len(vif_refs) <= idx:
        raise OptionError("Bad VIF index.")
    vif_ref = server.xenapi.VIF.get_by_uuid(vif_refs[idx])
    if not vif_ref:
        print "No VIF with this UUID."
    sec_lab = server.xenapi.VIF.get_security_label(vif_ref)
    print "%s" % sec_lab
Пример #8
0
def getenforce():
    if xm_main.serverType == xm_main.SERVER_XEN_API:
        if xsconstants.XS_POLICY_FLASK != \
                int(server.xenapi.XSPolicy.get_xstype()):
            raise OptionError("Unsupported policy type")
        mode = int(server.xenapi.XSPolicy.getenforce())
    else:
        if server.xend.security.on() != xsconstants.XS_POLICY_FLASK:
            raise OptionError("Unsupported policy type")
        mode = server.xend.security.getenforce()

    if mode == 0:
        print "Permissive"
    elif mode == 1:
        print "Enforcing"
Пример #9
0
def main(argv):
    if "-?" in argv:
        help()
        return

    if len(argv) != 1:
        raise OptionError("No arguments expected.")

    getenforce()
Пример #10
0
def setenforce(mode):
    if len(mode) == 1 and (mode == "0" or mode == "1"):
        val = int(mode)
    elif mode.lower() == "enforcing":
        val = 1
    elif mode.lower() == "permissive":
        val = 0
    else:
        raise OptionError("%s is an unsupported mode" % mode)

    if xm_main.serverType == xm_main.SERVER_XEN_API:
        if xsconstants.XS_POLICY_FLASK != \
                int(server.xenapi.XSPolicy.get_xstype()):
            raise OptionError("Unsupported policy type")
        ret = server.xenapi.XSPolicy.setenforce(val)
    else:
        if server.xend.security.on() != xsconstants.XS_POLICY_FLASK:
            raise OptionError("Unsupported policy type")
        ret = server.xend.security.setenforce(val)
Пример #11
0
def add_domain_label_xapi(label, domainname, policyref, policy_type):
    sec_lab = "%s:%s:%s" % (policy_type, policyref, label)
    if xm_main.serverType != xm_main.SERVER_XEN_API:
        old_seclab = server.xend.security.get_domain_label(domainname)
        if old_seclab[0] == '\'':
            old_seclab = old_seclab[1:]
        results = server.xend.security.set_domain_label(
            domainname, sec_lab, old_seclab)
        rc, ssidref = results
        if rc == xsconstants.XSERR_SUCCESS:
            if ssidref != 0:
                print "Successfully set the label of domain '%s' to '%s'.\n" \
                      % (domainname,label)
            else:
                print "Successfully set the label of the dormant domain " \
                      "'%s' to '%s'." % (domainname,label)
        else:
            msg = xsconstants.xserr2string(-rc)
            raise security.XSMError("An error occurred relabeling "
                                    "the domain: %s" % msg)
    else:
        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]
        try:
            old_lab = server.xenapi.VM.get_security_label(uuid)
            rc = server.xenapi.VM.set_security_label(uuid, sec_lab, old_lab)
        except Exception, e:
            raise security.XSMError("Could not label the domain: %s" % e)
        if int(rc) < 0:
            raise OptionError('Could not label domain.')
        else:
            ssidref = int(rc)
            if ssidref != 0:
                print "Successfully set the label of domain '%s' to '%s'.\n" \
                      % (domainname,label)
            else:
                print "Successfully set the label of the dormant domain " \
                      "'%s' to '%s'." % (domainname,label)
Пример #12
0
def main(argv):
    if len(argv) != 2:
        raise OptionError("Invalid arguments")

    if "-?" in argv:
        help()
        return

    mode = argv[1]

    setenforce(mode)
Пример #13
0
def main(argv):
    policy = None
    ptype = None
    for arg in argv[1:]:
        key_val = arg.split('=')
        if len(key_val) == 2 and key_val[0] == 'type':
            if ptype:
                raise OptionError('type is definied twice')
            ptype = key_val[1].lower()

        elif len(key_val) == 1:
            if policy:
                raise OptionError('policy is defined twice')
            policy = arg
        else:
            raise OptionError('Unrecognised option: %s' % arg)

    if xm_main.serverType != xm_main.SERVER_XEN_API:
        labels(policy, ptype)
    else:
        labels_xapi(policy, ptype)
Пример #14
0
def add_vif_label(label, vmname, idx, policyref, policy_type):
    if xm_main.serverType != xm_main.SERVER_XEN_API:
        raise OptionError('Need to be configure for using xen-api.')
    vm_refs = server.xenapi.VM.get_by_name_label(vmname)
    if len(vm_refs) == 0:
        raise OptionError('A VM with the name %s does not exist.' % vmname)
    vif_refs = server.xenapi.VM.get_VIFs(vm_refs[0])
    if len(vif_refs) <= idx:
        raise OptionError("Bad VIF index.")
    vif_ref = server.xenapi.VIF.get_by_uuid(vif_refs[idx])
    if not vif_ref:
        print "Internal error: VIF does not exist."
    sec_lab = "%s:%s:%s" % (policy_type, policyref, label)
    try:
        old_lab = server.xenapi.VIF.get_security_label(vif_ref)
        rc = server.xenapi.VIF.set_security_label(vif_ref, sec_lab, old_lab)
        if int(rc) != 0:
            print "Could not label the VIF."
        else:
            print "Successfully labeled the VIF."
    except Exception, e:
        print "Could not label the VIF: %s" % str(e)
Пример #15
0
def rm_domain_label_xapi(domain):
    if xm_main.serverType != xm_main.SERVER_XEN_API:
        old_lab = server.xend.security.get_domain_label(domain)

        vmlabel = ""
        if old_lab != "":
            tmp = old_lab.split(":")
            if len(tmp) == 3:
                vmlabel = tmp[2]

        if old_lab != "" and vmlabel != ACM_LABEL_UNLABELED:
            server.xend.security.set_domain_label(domain, "", old_lab)
            print "Successfully removed label from domain %s." % domain
        else:
            raise security.XSMError("Domain was not labeled.")
    else:
        uuids = server.xenapi.VM.get_by_name_label(domain)
        if len(uuids) == 0:
            raise OptionError('A VM with that name does not exist.')
        if len(uuids) != 1:
            raise OptionError('Too many domains with the same name.')
        uuid = uuids[0]
        try:
            old_lab = server.xenapi.VM.get_security_label(uuid)

            vmlabel = ""
            if old_lab != "":
                tmp = old_lab.split(":")
                if len(tmp) == 3:
                    vmlabel = tmp[2]

            if old_lab != "":
                server.xenapi.VM.set_security_label(uuid, "", old_lab)
            else:
                raise security.XSMError("Domain was not labeled.")
        except Exception, e:
            raise security.XSMError('Could not remove label from domain: %s' %
                                    e)
Пример #16
0
def main(argv):
    if len(argv) < 3:
        raise OptionError("Need at least 3 arguments.")

    if "-?" in argv:
        help()
        return

    policytype = argv[1]
    policy_name = argv[2]

    flags = xsconstants.XS_INST_LOAD | xsconstants.XS_INST_BOOT
    overwrite = True

    setpolicy(policytype, policy_name, flags, overwrite)
Пример #17
0
def connect(*args):
    creds = ("", "")
    uri = "http://localhost:9363"

    try:
        session = XenAPI.Session(uri)
    except:
        raise OptionError("Could not create XenAPI session with Xend." \
                          "URI=%s" % uri)
    try:
        session.login_with_password(*creds)
    except:
        raise OptionError("Could not login to Xend. URI=%s" % uri)

    def logout():
        try:
            for s in sessions:
                s.xenapi.session.logout()
        except:
            pass

    sessions.append(session)
    atexit.register(logout)
    return session
Пример #18
0
def main(argv):
    if len(argv) != 2:
        raise OptionError('Invalid number of arguments')

    passed = 0
    (opts, config) = create.parseCommandLine(argv)
    if check_domain_label(config, verbose=1):
        if config_security_check(config, verbose=1):
            passed = 1
    else:
        print "Checking resources: (skipped)"

    if passed:
        print "Dry Run: PASSED"
    else:
        print "Dry Run: FAILED"
        sys.exit(-1)
Пример #19
0
def parseCommandLine(argv):
    GOPTS.reset()
    args = GOPTS.parse(argv)

    if GOPTS.vals.help or GOPTS.vals.help_config:
        if GOPTS.vals.help_config:
            print GOPTS.val_usage()
        return (None, None)

    # Process remaining args as config variables.
    for arg in args:
        if '=' in arg:
            (var, val) = arg.strip().split('=', 1)
            GOPTS.setvar(var.strip(), val.strip())
    if GOPTS.vals.config:
        try:
            config = sxp.parse(file(GOPTS.vals.config))[0]
        except IOError, ex:
            raise OptionError("Cannot read file %s: %s" % (config, ex[1]))
Пример #20
0
    def create_vif(self, vm_ref, vif, networks):
        log(DEBUG, "create_vif")

        if 'network' in vif.attributes.keys():
            network_name = vif.attributes['network'].value

            if network_name in networks.keys():
                network_uuid = networks[network_name]
            else:
                networks = dict([
                    (record['name_label'], ref) for ref, record in
                    server.xenapi.network.get_all_records().items()
                ])
                if network_name in networks.keys():
                    network_uuid = networks[network_name]
                else:
                    raise OptionError("Network %s doesn't exist" %
                                      vif.attributes["network"].value)
        else:
            network_uuid = self._get_network_ref()

        vif_record = {
            "device":
            vif.attributes["device"].value,
            "network":
            network_uuid,
            "VM":
            vm_ref,
            "MAC":
            vif.attributes["mac"].value,
            "MTU":
            vif.attributes["mtu"].value,
            "qos_algorithm_type":
            vif.attributes["qos_algorithm_type"].value,
            "qos_algorithm_params":
            get_child_nodes_as_dict(vif, "qos_algorithm_param", "key",
                                    "value"),
            "security_label":
            vif.attributes["security_label"].value
        }

        return server.xenapi.VIF.create(vif_record)
Пример #21
0
def rm_domain_label(configfile):
    # open the domain config file
    fd = None
    fil = None
    if configfile[0] == '/':
        fil = configfile
        fd = open(fil, "rb")
    else:
        for prefix in [".", auxbin.xen_configdir()]:
            fil = prefix + "/" + configfile
            if os.path.isfile(fil):
                fd = open(fil, "rb")
                break
    if not fd:
        raise OptionError("Configuration file '%s' not found." % configfile)

    # read in the domain config file, removing label
    ac_entry_re = re.compile("^access_control\s*=.*", re.IGNORECASE)
    ac_exit_re = re.compile(".*'\].*")
    file_contents = ""
    comment = 0
    removed = 0
    for line in fd.readlines():
        if ac_entry_re.match(line):
            comment = 1
        if comment:
            removed = 1
            line = "#" + line
        if comment and ac_exit_re.match(line):
            comment = 0
        file_contents = file_contents + line
    fd.close()

    # send error message if we didn't find anything to remove
    if not removed:
        raise security.XSMError('Domain not labeled')

    # write the data back out to the file
    fd = open(fil, "wb")
    fd.writelines(file_contents)
    fd.close()
Пример #22
0
def main(argv):
    if len(argv) != 1:
        raise OptionError("No arguments expected.")

    if xm_main.serverType == xm_main.SERVER_XEN_API:
        try:
            bin_pol = server.xenapi.ACMPolicy.get_enforced_binary()
            if bin_pol:
                dom0_ssid = server.xenapi.ACMPolicy.get_VM_ssidref(DOM0_UUID)
                bin = base64.b64decode(bin_pol)
                try:
                    fd, filename = tempfile.mkstemp(suffix=".bin")
                    os.write(fd, bin)
                    os.close(fd)
                    dump_policy_file(filename, dom0_ssid)
                finally:
                    os.unlink(filename)
            else:
                err("No policy is installed.")
        except Exception, e:
            err("An error occurred getting the running policy: %s" % str(e))
Пример #23
0
def get_domain_label(configfile):
    # open the domain config file
    fd = None
    if configfile[0] == '/':
        fd = open(configfile, "rb")
    else:
        for prefix in [".", "/etc/xen"]:
            abs_file = prefix + "/" + configfile
            if os.path.isfile(abs_file):
                fd = open(abs_file, "rb")
                break
    if not fd:
        raise OptionError("Configuration file '%s' not found." % configfile)

    # read in the domain config file, finding the label line
    ac_entry_re = re.compile("^access_control\s*=.*", re.IGNORECASE)
    ac_exit_re = re.compile(".*'\].*")
    acline = ""
    record = 0
    for line in fd.readlines():
        if ac_entry_re.match(line):
            record = 1
        if record:
            acline = acline + line
        if record and ac_exit_re.match(line):
            record = 0
    fd.close()

    # send error message if we didn't find anything
    if acline == "":
        raise security.XSMError("Domain not labeled")

    # print out the label
    (title, data) = acline.split("=", 1)
    data = data.strip()
    data = data.lstrip("[\'")
    data = data.rstrip("\']")
    print "policytype=%s," % xsconstants.ACM_POLICY_ID + data
Пример #24
0
def main(argv):
    policyref = None
    policy_type = ""
    if len(argv) not in (4, 5):
        raise OptionError('Needs either 2 or 3 arguments')

    label = argv[1]

    if len(argv) == 5:
        policyref = argv[4]
    elif security.on() == xsconstants.XS_POLICY_ACM:
        policyref = security.active_policy
        policy_type = xsconstants.ACM_POLICY_ID
    else:
        raise OptionError("ACM security is not enabled. You must specify "\
                          "the policy on the command line.")

    if argv[2].lower() == "dom":
        configfile = argv[3]
        if configfile[0] != '/':
            for prefix in [os.path.realpath(os.path.curdir), "/etc/xen"]:
                configfile = prefix + "/" + configfile
                if os.path.isfile(configfile):
                    break
        if not validate_config_file(configfile):
            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]
        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)
    elif argv[2].lower().startswith("vif-"):
        try:
            idx = int(argv[2][4:])
            if idx < 0:
                raise
        except:
            raise OptionError("Bad VIF device index.")
        vmname = argv[3]
        if policy_type == "":
            tmp = policyref.split(":")
            if len(tmp) != 2:
                raise OptionError("Policy name in wrong format.")
            policy_type, policyref = tmp
        add_vif_label(label, vmname, idx, policyref, policy_type)
    else:
        raise OptionError('Need to specify either "dom", "mgt" or "res" as '
                          'object to add label to.')
Пример #25
0
    raise OptionError("Xm configuration file not using Xen-API for "
                      "communication with xend.")


sessions = []


def connect(*args):
    try:
        creds = get_login_pwd()
    except Exception, e:
        FAIL("%s" % str(e))
    try:
        session = XenAPI.Session(xmmain.serverURI)
    except:
        raise OptionError("Could not create XenAPI session with Xend." \
                          "URI=%s" % xmmain.serverURI)
    try:
        session.login_with_password(*creds)
    except:
        raise OptionError("Could not login to Xend. URI=%s" % xmmain.serverURI)

    def logout():
        try:
            for s in sessions:
                s.xenapi.session.logout()
        except:
            pass

    sessions.append(session)
    atexit.register(logout)
    return session
Пример #26
0
def main(argv):
    if len(argv) != 1:
        raise OptionError("No arguments expected.")

    resetpolicy()
Пример #27
0
                raise security.XSMError("ACM policy type not supported.")

            rc, errors = server.xend.security.set_policy(
                xs_type, xml, flags, overwrite)
            if rc != xsconstants.XSERR_SUCCESS:
                txt = "An error occurred trying to set the policy: %s." % \
                      xsconstants.xserr2string(abs(rc))
                if len(errors) > 0:
                    txt += " " + build_hv_error_message(
                        base64.b64decode(errors))
                raise security.XSMError(txt)
            else:
                print "Successfully set the new policy."
                getpolicy(False)
    else:
        raise OptionError("Unsupported policytype '%s'." % policytype)


def main(argv):
    if len(argv) < 3:
        raise OptionError("Need at least 3 arguments.")

    if "-?" in argv:
        help()
        return

    policytype = argv[1]
    policy_name = argv[2]

    flags = xsconstants.XS_INST_LOAD | xsconstants.XS_INST_BOOT
    overwrite = True