def handle(_name, cfg, _cloud, log, _args): cmd = ['/usr/lib/cloud-init/write-ssh-key-fingerprints'] fp_blacklist = util.get_cfg_option_list_or_str(cfg, "ssh_fp_console_blacklist", []) key_blacklist = util.get_cfg_option_list_or_str(cfg, "ssh_key_console_blacklist", ["ssh-dss"]) try: confp = open('/dev/console', "wb") cmd.append(','.join(fp_blacklist)) cmd.append(','.join(key_blacklist)) subprocess.call(cmd, stdout=confp) confp.close() except: log.warn("writing keys to console value") raise
def handle(_name, cfg, _cloud, log, _args): cmd = ['/usr/lib/cloud-init/write-ssh-key-fingerprints'] fp_blacklist = util.get_cfg_option_list_or_str(cfg, "ssh_fp_console_blacklist", []) key_blacklist = util.get_cfg_option_list_or_str( cfg, "ssh_key_console_blacklist", ["ssh-dss"]) try: confp = open('/dev/console', "wb") cmd.append(','.join(fp_blacklist)) cmd.append(','.join(key_blacklist)) subprocess.call(cmd, stdout=confp) confp.close() except: log.warn("writing keys to console value") raise
def handle(_name, cfg, _cloud, log, _args): """ Call to handle ca-cert sections in cloud-config file. @param name: The module name "ca-cert" from cloud.cfg @param cfg: A nested dict containing the entire cloud config contents. @param cloud: The L{CloudInit} object in use. @param log: Pre-initialized Python logger object to use for logging. @param args: Any module arguments from cloud.cfg """ # If there isn't a ca-certs section in the configuration don't do anything if "ca-certs" not in cfg: return ca_cert_cfg = cfg['ca-certs'] # If there is a remove-defaults option set to true, remove the system # default trusted CA certs first. if ca_cert_cfg.get("remove-defaults", False): log.debug("removing default certificates") remove_default_ca_certs() # If we are given any new trusted CA certs to add, add them. if "trusted" in ca_cert_cfg: trusted_certs = get_cfg_option_list_or_str(ca_cert_cfg, "trusted") if trusted_certs: log.debug("adding %d certificates" % len(trusted_certs)) add_ca_certs(trusted_certs) # Update the system with the new cert configuration. update_ca_certs()
def handle(_name, cfg, _cloud, log, args): if len(args) != 0: user = args[0] ids = [] if len(args) > 1: ids = args[1:] else: user = util.get_cfg_option_str(cfg, "user", "ubuntu") ids = util.get_cfg_option_list_or_str(cfg, "ssh_import_id", []) if len(ids) == 0: return cmd = ["sudo", "-Hu", user, "ssh-import-id"] + ids log.debug("importing ssh ids. cmd = %s" % cmd) try: subprocess.check_call(cmd) except subprocess.CalledProcessError as e: log.debug(traceback.format_exc(e)) raise Exception("Cmd returned %s: %s" % (e.returncode, cmd)) except OSError as e: log.debug(traceback.format_exc(e)) raise Exception("Cmd failed to execute: %s" % (cmd))
def handle(_name, cfg, _cloud, log, args): pkglist = util.get_cfg_option_list_or_str(cfg, "packages", []) if pkglist: try: yum_install(pkglist) except subprocess.CalledProcessError: log.warn("Failed to install yum packages: %s" % pkglist) log.debug(traceback.format_exc()) raise return True
def test_value_is_none(self): """If value is None empty list is returned.""" config = {"key": None} result = get_cfg_option_list_or_str(config, "key") self.assertEqual([], result)
def test_found_convert_to_list(self): """Single string is converted to one element list.""" config = {"key": "value1"} result = get_cfg_option_list_or_str(config, "key") self.assertEqual(["value1"], result)
def test_found_with_default(self): """Default is not returned if key is found.""" config = {"key": ["value1"]} result = get_cfg_option_list_or_str(config, "key", default=["DEFAULT"]) self.assertEqual(["value1"], result)
def test_not_found_no_default(self): """None is returned if key is not found and no default given.""" config = {} result = get_cfg_option_list_or_str(config, "key") self.assertIsNone(result)
def handle(_name, cfg, cloud, log, _args): update = util.get_cfg_option_bool(cfg, 'apt_update', False) upgrade = util.get_cfg_option_bool(cfg, 'apt_upgrade', False) release = get_release() mirror = find_apt_mirror(cloud, cfg) log.debug("selected mirror at: %s" % mirror) if not util.get_cfg_option_bool(cfg, \ 'apt_preserve_sources_list', False): generate_sources_list(release, mirror) old_mir = util.get_cfg_option_str(cfg, 'apt_old_mirror', \ "archive.ubuntu.com/ubuntu") rename_apt_lists(old_mir, mirror) # set up proxy proxy = cfg.get("apt_proxy", None) proxy_filename = "/etc/apt/apt.conf.d/95cloud-init-proxy" if proxy: try: contents = "Acquire::HTTP::Proxy \"%s\";\n" with open(proxy_filename, "w") as fp: fp.write(contents % proxy) except Exception as e: log.warn("Failed to write proxy to %s" % proxy_filename) elif os.path.isfile(proxy_filename): os.unlink(proxy_filename) # process 'apt_sources' if 'apt_sources' in cfg: errors = add_sources(cfg['apt_sources'], {'MIRROR': mirror, 'RELEASE': release}) for e in errors: log.warn("Source Error: %s\n" % ':'.join(e)) dconf_sel = util.get_cfg_option_str(cfg, 'debconf_selections', False) if dconf_sel: log.debug("setting debconf selections per cloud config") try: util.subp(('debconf-set-selections', '-'), dconf_sel) except: log.error("Failed to run debconf-set-selections") log.debug(traceback.format_exc()) pkglist = util.get_cfg_option_list_or_str(cfg, 'packages', []) errors = [] if update or len(pkglist) or upgrade: try: cc.update_package_sources() except subprocess.CalledProcessError as e: log.warn("apt-get update failed") log.debug(traceback.format_exc()) errors.append(e) if upgrade: try: cc.apt_get("upgrade") except subprocess.CalledProcessError as e: log.warn("apt upgrade failed") log.debug(traceback.format_exc()) errors.append(e) if len(pkglist): try: cc.install_packages(pkglist) except subprocess.CalledProcessError as e: log.warn("Failed to install packages: %s " % pkglist) log.debug(traceback.format_exc()) errors.append(e) if len(errors): raise errors[0] return(True)
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")
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")