コード例 #1
0
def setup_user_keys(keys, user, key_prefix, log=None):
    import pwd
    saved_umask = os.umask(077)

    pwent = pwd.getpwnam(user)

    ssh_dir = '%s/.ssh' % pwent.pw_dir
    if not os.path.exists(ssh_dir):
        os.mkdir(ssh_dir)
        os.chown(ssh_dir, pwent.pw_uid, pwent.pw_gid)

    try:
        ssh_cfg = parse_ssh_config()
        akeys = ssh_cfg.get("AuthorizedKeysFile", "%h/.ssh/authorized_keys")
        akeys = akeys.replace("%h", pwent.pw_dir)
        akeys = akeys.replace("%u", user)
        authorized_keys = akeys
    except Exception:
        authorized_keys = '%s/.ssh/authorized_keys' % pwent.pw_dir
        if log:
            util.logexc(log)

    key_entries = []
    for k in keys:
        ke = AuthKeyEntry(k, def_opt=key_prefix)
        key_entries.append(ke)

    content = update_authorized_keys(authorized_keys, key_entries)
    util.write_file(authorized_keys, content, 0600)

    os.chown(authorized_keys, pwent.pw_uid, pwent.pw_gid)
    util.restorecon_if_possible(ssh_dir, recursive=True)

    os.umask(saved_umask)
コード例 #2
0
def setup_user_keys(keys, user, key_prefix, log=None):
    import pwd
    saved_umask = os.umask(077)

    pwent = pwd.getpwnam(user)

    ssh_dir = '%s/.ssh' % pwent.pw_dir
    if not os.path.exists(ssh_dir):
        os.mkdir(ssh_dir)
        os.chown(ssh_dir, pwent.pw_uid, pwent.pw_gid)

    try:
        ssh_cfg = parse_ssh_config()
        akeys = ssh_cfg.get("AuthorizedKeysFile", "%h/.ssh/authorized_keys")
        akeys = akeys.replace("%h", pwent.pw_dir)
        akeys = akeys.replace("%u", user)
        authorized_keys = akeys
    except Exception:
        authorized_keys = '%s/.ssh/authorized_keys' % pwent.pw_dir
        if log:
            util.logexc(log)

    key_entries = []
    for k in keys:
        ke = AuthKeyEntry(k, def_opt=key_prefix)
        key_entries.append(ke)

    content = update_authorized_keys(authorized_keys, key_entries)
    util.write_file(authorized_keys, content, 0600)

    os.chown(authorized_keys, pwent.pw_uid, pwent.pw_gid)
    util.restorecon_if_possible(ssh_dir, recursive=True)

    os.umask(saved_umask)
コード例 #3
0
def handle(_name, cfg, cloud, log, _args):
    # If there isn't a puppet key in the configuration don't do anything
    if 'puppet' not in cfg:
        return
    puppet_cfg = cfg['puppet']
    # Start by installing the puppet package ...
    cc.install_packages(("puppet", ))

    # ... and then update the puppet configuration
    if 'conf' in puppet_cfg:
        # Add all sections from the conf object to puppet.conf
        puppet_conf_fh = open('/etc/puppet/puppet.conf', 'r')
        # Create object for reading puppet.conf values
        puppet_config = ConfigParser.ConfigParser()
        # Read puppet.conf values from original file in order to be able to
        # mix the rest up
        puppet_config.readfp(
            StringIO.StringIO(''.join(i.lstrip()
                                      for i in puppet_conf_fh.readlines())))
        # Close original file, no longer needed
        puppet_conf_fh.close()
        for cfg_name, cfg in puppet_cfg['conf'].iteritems():
            # ca_cert configuration is a special case
            # Dump the puppetmaster ca certificate in the correct place
            if cfg_name == 'ca_cert':
                # Puppet ssl sub-directory isn't created yet
                # Create it with the proper permissions and ownership
                os.makedirs('/var/lib/puppet/ssl')
                os.chmod('/var/lib/puppet/ssl', 0771)
                os.chown('/var/lib/puppet/ssl',
                         pwd.getpwnam('puppet').pw_uid, 0)
                os.makedirs('/var/lib/puppet/ssl/certs/')
                os.chown('/var/lib/puppet/ssl/certs/',
                         pwd.getpwnam('puppet').pw_uid, 0)
                ca_fh = open('/var/lib/puppet/ssl/certs/ca.pem', 'w')
                ca_fh.write(cfg)
                ca_fh.close()
                os.chown('/var/lib/puppet/ssl/certs/ca.pem',
                         pwd.getpwnam('puppet').pw_uid, 0)
                util.restorecon_if_possible('/var/lib/puppet', recursive=True)
            else:
                #puppet_conf_fh.write("\n[%s]\n" % (cfg_name))
                # If puppet.conf already has this section we don't want to
                # write it again
                if puppet_config.has_section(cfg_name) == False:
                    puppet_config.add_section(cfg_name)
                # Iterate throug the config items, we'll use ConfigParser.set
                # to overwrite or create new items as needed
                for o, v in cfg.iteritems():
                    if o == 'certname':
                        # Expand %f as the fqdn
                        v = v.replace("%f", socket.getfqdn())
                        # Expand %i as the instance id
                        v = v.replace("%i", cloud.datasource.get_instance_id())
                        # certname needs to be downcase
                        v = v.lower()
                    puppet_config.set(cfg_name, o, v)
                    #puppet_conf_fh.write("%s=%s\n" % (o, v))
            # We got all our config as wanted we'll rename
            # the previous puppet.conf and create our new one
            os.rename('/etc/puppet/puppet.conf', '/etc/puppet/puppet.conf.old')
            with open('/etc/puppet/puppet.conf', 'wb') as configfile:
                puppet_config.write(configfile)
            util.restorecon_if_possible('/etc/puppet/puppet.conf')
    # Set puppet to automatically start
    if os.path.exists('/etc/default/puppet'):
        subprocess.check_call([
            'sed', '-i', '-e', 's/^START=.*/START=yes/', '/etc/default/puppet'
        ])
    elif os.path.exists('/bin/systemctl'):
        subprocess.check_call(['/bin/systemctl', 'enable', 'puppet.service'])
    elif os.path.exists('/sbin/chkconfig'):
        subprocess.check_call(['/sbin/chkconfig', 'puppet', 'on'])
    else:
        log.warn("Do not know how to enable puppet service on this system")
    # Start puppetd
    subprocess.check_call(['service', 'puppet', 'start'])
コード例 #4
0
def handle(_name, cfg, cloud, log, _args):

    # remove the static keys from the pristine image
    if cfg.get("ssh_deletekeys", True):
        for f in glob.glob("/etc/ssh/ssh_host_*key*"):
            try:
                os.unlink(f)
            except:
                pass

    if "ssh_keys" in cfg:
        # if there are keys in cloud-config, use them
        key2file = {
            "rsa_private": ("/etc/ssh/ssh_host_rsa_key", 0600),
            "rsa_public": ("/etc/ssh/ssh_host_rsa_key.pub", 0644),
            "dsa_private": ("/etc/ssh/ssh_host_dsa_key", 0600),
            "dsa_public": ("/etc/ssh/ssh_host_dsa_key.pub", 0644),
            "ecdsa_private": ("/etc/ssh/ssh_host_ecdsa_key", 0600),
            "ecdsa_public": ("/etc/ssh/ssh_host_ecdsa_key.pub", 0644),
        }

        for key, val in cfg["ssh_keys"].items():
            if key in key2file:
                util.write_file(key2file[key][0], val, key2file[key][1])

        priv2pub = {'rsa_private': 'rsa_public', 'dsa_private': 'dsa_public',
                    'ecdsa_private': 'ecdsa_public', }

        cmd = 'o=$(ssh-keygen -yf "%s") && echo "$o" root@localhost > "%s"'
        for priv, pub in priv2pub.iteritems():
            if pub in cfg['ssh_keys'] or not priv in cfg['ssh_keys']:
                continue
            pair = (key2file[priv][0], key2file[pub][0])
            subprocess.call(('sh', '-xc', cmd % pair))
            log.debug("generated %s from %s" % pair)
    else:
        # if not, generate them
        for keytype in util.get_cfg_option_list_or_str(cfg, 'ssh_genkeytypes',
                                                      ['rsa', 'dsa', 'ecdsa']):
            keyfile = '/etc/ssh/ssh_host_%s_key' % keytype
            if not os.path.exists(keyfile):
                subprocess.call(['ssh-keygen', '-t', keytype, '-N', '',
                                 '-f', keyfile])

    util.restorecon_if_possible('/etc/ssh', recursive=True)

    try:
        user = util.get_cfg_option_str(cfg, 'user')
        disable_root = util.get_cfg_option_bool(cfg, "disable_root", True)
        disable_root_opts = util.get_cfg_option_str(cfg, "disable_root_opts",
            DISABLE_ROOT_OPTS)
        keys = cloud.get_public_ssh_keys()

        if "ssh_authorized_keys" in cfg:
            cfgkeys = cfg["ssh_authorized_keys"]
            keys.extend(cfgkeys)

        apply_credentials(keys, user, disable_root, disable_root_opts, log)
    except:
        util.logexc(log)
        log.warn("applying credentials failed!\n")
コード例 #5
0
def handle(_name, cfg, cloud, log, _args):
    # If there isn't a puppet key in the configuration don't do anything
    if 'puppet' not in cfg:
        return
    puppet_cfg = cfg['puppet']
    # Start by installing the puppet package ...
    cc.install_packages(("puppet",))

    # ... and then update the puppet configuration
    if 'conf' in puppet_cfg:
        # Add all sections from the conf object to puppet.conf
        puppet_conf_fh = open('/etc/puppet/puppet.conf', 'r')
        # Create object for reading puppet.conf values
        puppet_config = ConfigParser.ConfigParser()
        # Read puppet.conf values from original file in order to be able to
        # mix the rest up
        puppet_config.readfp(StringIO.StringIO(''.join(i.lstrip() for i in
                                               puppet_conf_fh.readlines())))
        # Close original file, no longer needed
        puppet_conf_fh.close()
        for cfg_name, cfg in puppet_cfg['conf'].iteritems():
            # ca_cert configuration is a special case
            # Dump the puppetmaster ca certificate in the correct place
            if cfg_name == 'ca_cert':
                # Puppet ssl sub-directory isn't created yet
                # Create it with the proper permissions and ownership
                os.makedirs('/var/lib/puppet/ssl')
                os.chmod('/var/lib/puppet/ssl', 0771)
                os.chown('/var/lib/puppet/ssl',
                         pwd.getpwnam('puppet').pw_uid, 0)
                os.makedirs('/var/lib/puppet/ssl/certs/')
                os.chown('/var/lib/puppet/ssl/certs/',
                         pwd.getpwnam('puppet').pw_uid, 0)
                ca_fh = open('/var/lib/puppet/ssl/certs/ca.pem', 'w')
                ca_fh.write(cfg)
                ca_fh.close()
                os.chown('/var/lib/puppet/ssl/certs/ca.pem',
                         pwd.getpwnam('puppet').pw_uid, 0)
                util.restorecon_if_possible('/var/lib/puppet', recursive=True)
            else:
                #puppet_conf_fh.write("\n[%s]\n" % (cfg_name))
                # If puppet.conf already has this section we don't want to
                # write it again
                if puppet_config.has_section(cfg_name) == False:
                    puppet_config.add_section(cfg_name)
                # Iterate throug the config items, we'll use ConfigParser.set
                # to overwrite or create new items as needed
                for o, v in cfg.iteritems():
                    if o == 'certname':
                        # Expand %f as the fqdn
                        v = v.replace("%f", socket.getfqdn())
                        # Expand %i as the instance id
                        v = v.replace("%i",
                              cloud.datasource.get_instance_id())
                        # certname needs to be downcase
                        v = v.lower()
                    puppet_config.set(cfg_name, o, v)
                    #puppet_conf_fh.write("%s=%s\n" % (o, v))
            # We got all our config as wanted we'll rename
            # the previous puppet.conf and create our new one
            os.rename('/etc/puppet/puppet.conf', '/etc/puppet/puppet.conf.old')
            with open('/etc/puppet/puppet.conf', 'wb') as configfile:
                puppet_config.write(configfile)
            util.restorecon_if_possible('/etc/puppet/puppet.conf')
    # Set puppet to automatically start
    if os.path.exists('/etc/default/puppet'):
        subprocess.check_call(['sed', '-i',
                               '-e', 's/^START=.*/START=yes/',
                               '/etc/default/puppet'])
    elif os.path.exists('/bin/systemctl'):
        subprocess.check_call(['/bin/systemctl', 'enable', 'puppet.service'])
    elif os.path.exists('/sbin/chkconfig'):
        subprocess.check_call(['/sbin/chkconfig', 'puppet', 'on'])
    else:
        log.warn("Do not know how to enable puppet service on this system")
    # Start puppetd
    subprocess.check_call(['service', 'puppet', 'start'])
コード例 #6
0
def handle(_name, cfg, cloud, log, _args):

    # remove the static keys from the pristine image
    if cfg.get("ssh_deletekeys", True):
        for f in glob.glob("/etc/ssh/ssh_host_*key*"):
            try:
                os.unlink(f)
            except:
                pass

    if "ssh_keys" in cfg:
        # if there are keys in cloud-config, use them
        key2file = {
            "rsa_private": ("/etc/ssh/ssh_host_rsa_key", 0600),
            "rsa_public": ("/etc/ssh/ssh_host_rsa_key.pub", 0644),
            "dsa_private": ("/etc/ssh/ssh_host_dsa_key", 0600),
            "dsa_public": ("/etc/ssh/ssh_host_dsa_key.pub", 0644),
            "ecdsa_private": ("/etc/ssh/ssh_host_ecdsa_key", 0600),
            "ecdsa_public": ("/etc/ssh/ssh_host_ecdsa_key.pub", 0644),
        }

        for key, val in cfg["ssh_keys"].items():
            if key in key2file:
                util.write_file(key2file[key][0], val, key2file[key][1])

        priv2pub = {
            'rsa_private': 'rsa_public',
            'dsa_private': 'dsa_public',
            'ecdsa_private': 'ecdsa_public',
        }

        cmd = 'o=$(ssh-keygen -yf "%s") && echo "$o" root@localhost > "%s"'
        for priv, pub in priv2pub.iteritems():
            if pub in cfg['ssh_keys'] or not priv in cfg['ssh_keys']:
                continue
            pair = (key2file[priv][0], key2file[pub][0])
            subprocess.call(('sh', '-xc', cmd % pair))
            log.debug("generated %s from %s" % pair)
    else:
        # if not, generate them
        for keytype in util.get_cfg_option_list_or_str(
                cfg, 'ssh_genkeytypes', ['rsa', 'dsa', 'ecdsa']):
            keyfile = '/etc/ssh/ssh_host_%s_key' % keytype
            if not os.path.exists(keyfile):
                subprocess.call(
                    ['ssh-keygen', '-t', keytype, '-N', '', '-f', keyfile])

    util.restorecon_if_possible('/etc/ssh', recursive=True)

    try:
        user = util.get_cfg_option_str(cfg, 'user')
        disable_root = util.get_cfg_option_bool(cfg, "disable_root", True)
        disable_root_opts = util.get_cfg_option_str(cfg, "disable_root_opts",
                                                    DISABLE_ROOT_OPTS)
        keys = cloud.get_public_ssh_keys()

        if "ssh_authorized_keys" in cfg:
            cfgkeys = cfg["ssh_authorized_keys"]
            keys.extend(cfgkeys)

        apply_credentials(keys, user, disable_root, disable_root_opts, log)
    except:
        util.logexc(log)
        log.warn("applying credentials failed!\n")