Exemple #1
0
def config_dhcp(interface, info, create=True):
    infile = "/etc/dhcpcd.ini"
    eat = 0
    updated = 0

    if interface is not None:
        with open(infile, 'r+') as f, util.tempdir() as tmpd:
            tmpf = "%s/dhcpcd.ini" % tmpd
            for line in f.readlines():
                if create is False:
                    util.append_file(tmpf, line)
                else:
                    if eat == 0 and not line.startswith("interface "):
                        util.append_file(tmpf, line)
                    elif eat == 0 and line.startswith("interface "):
                        eat = 1
                    elif eat == 1 and re.match("{", line.strip()):
                        eat = 2
                    elif eat == 2:
                        update_dhcp(tmpf, interface, info)
                        updated = 1
                        eat = 3
            if create is False:
                update_dhcp(tmpf, interface, info)
            else:
                if updated == 0:
                    update_dhcp(tmpf, interface, info)

            util.copy(tmpf, infile)
Exemple #2
0
def handle(name, cfg, cloud, log, _args):
    mycfg = cfg.get('random_seed', {})
    seed_path = mycfg.get('file', '/dev/urandom')
    seed_data = mycfg.get('data', b'')

    seed_buf = BytesIO()
    if seed_data:
        seed_buf.write(_decode(seed_data, encoding=mycfg.get('encoding')))

    # 'random_seed' is set up by Azure datasource, and comes already in
    # openstack meta_data.json
    metadata = cloud.datasource.metadata
    if metadata and 'random_seed' in metadata:
        seed_buf.write(util.encode_text(metadata['random_seed']))

    seed_data = seed_buf.getvalue()
    if len(seed_data):
        log.debug("%s: adding %s bytes of random seed entropy to %s", name,
                  len(seed_data), seed_path)
        util.append_file(seed_path, seed_data)

    command = mycfg.get('command', None)
    req = mycfg.get('command_required', False)
    try:
        env = os.environ.copy()
        env['RANDOM_SEED_FILE'] = seed_path
        handle_random_seed_command(command=command, required=req, env=env)
    except ValueError as e:
        log.warn("handling random command [%s] failed: %s", command, e)
        raise e
Exemple #3
0
    def write_sudo_rules(self, user, rules, sudo_file=None):
        if not sudo_file:
            sudo_file = self.ci_sudoers_fn

        lines = ["", "# User rules for %s" % user]
        if isinstance(rules, (list, tuple)):
            for rule in rules:
                lines.append("%s %s" % (user, rule))
        elif isinstance(rules, (basestring, str)):
            lines.append("%s %s" % (user, rules))
        else:
            msg = "Can not create sudoers rule addition with type %r"
            raise TypeError(msg % (type_utils.obj_name(rules)))
        content = "\n".join(lines)
        content += "\n"  # trailing newline

        self.ensure_sudo_dir(os.path.dirname(sudo_file))
        if not os.path.exists(sudo_file):
            contents = [util.make_header(), content]
            try:
                util.write_file(sudo_file, "\n".join(contents), 0440)
            except IOError as e:
                util.logexc(LOG, "Failed to write sudoers file %s", sudo_file)
                raise e
        else:
            try:
                util.append_file(sudo_file, content)
            except IOError as e:
                util.logexc(LOG, "Failed to append sudoers file %s", sudo_file)
                raise e
Exemple #4
0
def config_dhcp(interface, info, create=True):
    infile = "/etc/dhcpcd.ini"
    eat = 0
    updated = 0

    if interface is not None:
        with open(infile, 'r+') as f, util.tempdir() as tmpd:
            tmpf = "%s/dhcpcd.ini" % tmpd
            for line in f.readlines():
                if create is False:
                    util.append_file(tmpf, line)
                else:
                    if eat == 0 and not line.startswith("interface "):
                        util.append_file(tmpf, line)
                    elif eat == 0 and line.startswith("interface "):
                        eat = 1
                    elif eat == 1 and re.match("{", line.strip()):
                        eat = 2
                    elif eat == 2:
                        update_dhcp(tmpf, interface, info)
                        updated = 1
                        eat = 3
            if create is False:
                update_dhcp(tmpf, interface, info)
            else:
                if updated == 0:
                    update_dhcp(tmpf, interface, info)

            util.copy(tmpf, infile)
Exemple #5
0
 def ensure_sudo_dir(self, path, sudo_base="/etc/sudoers"):
     # Ensure the dir is included and that
     # it actually exists as a directory
     sudoers_contents = ""
     base_exists = False
     if os.path.exists(sudo_base):
         sudoers_contents = util.load_file(sudo_base)
         base_exists = True
     found_include = False
     for line in sudoers_contents.splitlines():
         line = line.strip()
         include_match = re.search(r"^[#|@]includedir\s+(.*)$", line)
         if not include_match:
             continue
         included_dir = include_match.group(1).strip()
         if not included_dir:
             continue
         included_dir = os.path.abspath(included_dir)
         if included_dir == path:
             found_include = True
             break
     if not found_include:
         try:
             if not base_exists:
                 lines = [
                     "# See sudoers(5) for more information"
                     ' on "#include" directives:',
                     "",
                     util.make_header(base="added"),
                     "#includedir %s" % (path),
                     "",
                 ]
                 sudoers_contents = "\n".join(lines)
                 util.write_file(sudo_base, sudoers_contents, 0o440)
             else:
                 lines = [
                     "",
                     util.make_header(base="added"),
                     "#includedir %s" % (path),
                     "",
                 ]
                 sudoers_contents = "\n".join(lines)
                 util.append_file(sudo_base, sudoers_contents)
             LOG.debug("Added '#includedir %s' to %s", path, sudo_base)
         except IOError as e:
             util.logexc(LOG, "Failed to write %s", sudo_base)
             raise e
     util.ensure_dir(path, 0o750)
def handle(name, cfg, cloud, log, _args):
    if not cfg or "random_seed" not in cfg:
        log.debug(("Skipping module named %s, " "no 'random_seed' configuration found"), name)
        return

    my_cfg = cfg["random_seed"]
    seed_path = my_cfg.get("file", "/dev/urandom")
    seed_buf = StringIO()
    seed_buf.write(_decode(my_cfg.get("data", ""), encoding=my_cfg.get("encoding")))

    metadata = cloud.datasource.metadata
    if metadata and "random_seed" in metadata:
        seed_buf.write(metadata["random_seed"])

    seed_data = seed_buf.getvalue()
    if len(seed_data):
        log.debug("%s: adding %s bytes of random seed entrophy to %s", name, len(seed_data), seed_path)
        util.append_file(seed_path, seed_data)
Exemple #7
0
 def ensure_sudo_dir(self, path, sudo_base="/etc/sudoers"):
     # Ensure the dir is included and that
     # it actually exists as a directory
     sudoers_contents = ""
     base_exists = False
     if os.path.exists(sudo_base):
         sudoers_contents = util.load_file(sudo_base)
         base_exists = True
     found_include = False
     for line in sudoers_contents.splitlines():
         line = line.strip()
         include_match = re.search(r"^#includedir\s+(.*)$", line)
         if not include_match:
             continue
         included_dir = include_match.group(1).strip()
         if not included_dir:
             continue
         included_dir = os.path.abspath(included_dir)
         if included_dir == path:
             found_include = True
             break
     if not found_include:
         try:
             if not base_exists:
                 lines = [
                     ("# See sudoers(5) for more information" ' on "#include" directives:'),
                     "",
                     util.make_header(base="added"),
                     "#includedir %s" % (path),
                     "",
                 ]
                 sudoers_contents = "\n".join(lines)
                 util.write_file(sudo_base, sudoers_contents, 0440)
             else:
                 lines = ["", util.make_header(base="added"), "#includedir %s" % (path), ""]
                 sudoers_contents = "\n".join(lines)
                 util.append_file(sudo_base, sudoers_contents)
             LOG.debug("Added '#includedir %s' to %s" % (path, sudo_base))
         except IOError as e:
             util.logexc(LOG, "Failed to write %s", sudo_base)
             raise e
     util.ensure_dir(path, 0750)
def handle(name, cfg, cloud, log, _args):
    if not cfg or "random_seed" not in cfg:
        log.debug(("Skipping module named %s, "
                   "no 'random_seed' configuration found"), name)
        return

    my_cfg = cfg['random_seed']
    seed_path = my_cfg.get('file', '/dev/urandom')
    seed_buf = StringIO()
    seed_buf.write(
        _decode(my_cfg.get('data', ''), encoding=my_cfg.get('encoding')))

    metadata = cloud.datasource.metadata
    if metadata and 'random_seed' in metadata:
        seed_buf.write(metadata['random_seed'])

    seed_data = seed_buf.getvalue()
    if len(seed_data):
        log.debug("%s: adding %s bytes of random seed entrophy to %s", name,
                  len(seed_data), seed_path)
        util.append_file(seed_path, seed_data)
Exemple #9
0
    def write_sudo_rules(self, user, rules, sudo_file=None):
        if not sudo_file:
            sudo_file = self.ci_sudoers_fn

        lines = [
            '',
            "# User rules for %s" % user,
        ]
        if isinstance(rules, (list, tuple)):
            for rule in rules:
                lines.append("%s %s" % (user, rule))
        elif isinstance(rules, str):
            lines.append("%s %s" % (user, rules))
        else:
            msg = "Can not create sudoers rule addition with type %r"
            raise TypeError(msg % (type_utils.obj_name(rules)))
        content = "\n".join(lines)
        content += "\n"  # trailing newline

        self.ensure_sudo_dir(os.path.dirname(sudo_file))
        if not os.path.exists(sudo_file):
            contents = [
                util.make_header(),
                content,
            ]
            try:
                util.write_file(sudo_file, "\n".join(contents), 0o440)
            except IOError as e:
                util.logexc(LOG, "Failed to write sudoers file %s", sudo_file)
                raise e
        else:
            try:
                util.append_file(sudo_file, content)
            except IOError as e:
                util.logexc(LOG, "Failed to append sudoers file %s", sudo_file)
                raise e
Exemple #10
0
def update_dhcp(tmpf, interface, info):
    util.append_file(tmpf, "interface %s\n" % interface)
    util.append_file(tmpf, "{\n")
    if info.get('netmask'):
        util.append_file(tmpf, " option 1  %s\n" % (info.get('netmask')))
    if interface == "en0":
        if info.get('gateway'):
            util.append_file(tmpf, " option 3  %s\n" % (info.get('gateway')))
    else:
        util.append_file(tmpf, " reject 3\n")         
    if info.get('address'):
        util.append_file(tmpf, " option 50 %s\n" % (info.get('address')))
    util.append_file(tmpf, "}\n\n")
Exemple #11
0
def update_dhcp(tmpf, interface, info):
    util.append_file(tmpf, "interface %s\n" % interface)
    util.append_file(tmpf, "{\n")
    if info.get('netmask'):
        util.append_file(tmpf, " option 1  %s\n" % (info.get('netmask')))
    if interface == "en0":
        if info.get('gateway'):
            util.append_file(tmpf, " option 3  %s\n" % (info.get('gateway')))
    else:
        util.append_file(tmpf, " reject 3\n")         
    if info.get('address'):
        util.append_file(tmpf, " option 50 %s\n" % (info.get('address')))
    util.append_file(tmpf, "}\n\n")