Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def get_ceph_expected_pools(self, radosgw=False): if self._get_openstack_release() == self.trusty_icehouse: # Icehouse pools = [ 'data', 'metadata', 'rbd', 'cinder-ceph'...
[ "Return a list of expected ceph pools in a ceph + cinder + glance\n test scenario, based on OpenStack release and whether ceph radosgw\n is flagged as present or not." ]
Please provide a description of the function:def get_platform(): # linux_distribution is deprecated and will be removed in Python 3.7 # Warings *not* disabled, as we certainly need to fix this. tuple_platform = platform.linux_distribution() current_platform = tuple_platform[0] if "Ubuntu" in cu...
[ "Return the current OS platform.\n\n For example: if current os platform is Ubuntu then a string \"ubuntu\"\n will be returned (which is the name of the module).\n This string is used to decide which platform module should be imported.\n " ]
Please provide a description of the function:def get_audits(): checks = [] settings = utils.get_settings('os') if not settings['security']['suid_sgid_enforce']: log("Skipping suid/sgid hardening", level=INFO) return checks # Build the blacklist and whitelist of files for suid/sgid ...
[ "Get OS hardening suid/sgid audits.\n\n :returns: dictionary of audits\n " ]
Please provide a description of the function:def find_paths_with_suid_sgid(root_path): cmd = ['find', root_path, '-perm', '-4000', '-o', '-perm', '-2000', '-type', 'f', '!', '-path', '/proc/*', '-print'] p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, _ = p.co...
[ "Finds all paths/files which have an suid/sgid bit enabled.\n\n Starting with the root_path, this will recursively find all paths which\n have an suid or sgid bit set.\n " ]
Please provide a description of the function:def current_version_string(): return "{0}.{1}.{2}".format(sys.version_info.major, sys.version_info.minor, sys.version_info.micro)
[ "Current system python version as string major.minor.micro" ]
Please provide a description of the function:def get_audits(): if subprocess.call(['which', 'mysql'], stdout=subprocess.PIPE) != 0: log("MySQL does not appear to be installed on this node - " "skipping mysql hardening", level=WARNING) return [] settings = utils.get_settings('my...
[ "Get MySQL hardening config audits.\n\n :returns: dictionary of audits\n " ]
Please provide a description of the function:def service_reload(service_name, restart_on_failure=False, **kwargs): service_result = service('reload', service_name, **kwargs) if not service_result and restart_on_failure: service_result = service('restart', service_name, **kwargs) return service_...
[ "Reload a system service, optionally falling back to restart if\n reload fails.\n\n The specified service name is managed via the system level init system.\n Some init systems (e.g. upstart) require that additional arguments be\n provided in order to directly control service instances whereas other init...
Please provide a description of the function:def service_pause(service_name, init_dir="/etc/init", initd_dir="/etc/init.d", **kwargs): stopped = True if service_running(service_name, **kwargs): stopped = service_stop(service_name, **kwargs) upstart_file = os.path.join(init_dir...
[ "Pause a system service.\n\n Stop it, and prevent it from starting again at boot.\n\n :param service_name: the name of the service to pause\n :param init_dir: path to the upstart init directory\n :param initd_dir: path to the sysv init directory\n :param **kwargs: additional parameters to pass to the...
Please provide a description of the function:def service_resume(service_name, init_dir="/etc/init", initd_dir="/etc/init.d", **kwargs): upstart_file = os.path.join(init_dir, "{}.conf".format(service_name)) sysv_file = os.path.join(initd_dir, service_name) if init_is_systemd(): ...
[ "Resume a system service.\n\n Reenable starting again at boot. Start the service.\n\n :param service_name: the name of the service to resume\n :param init_dir: the path to the init dir\n :param initd dir: the path to the initd dir\n :param **kwargs: additional parameters to pass to the init system wh...
Please provide a description of the function:def service(action, service_name, **kwargs): if init_is_systemd(): cmd = ['systemctl', action, service_name] else: cmd = ['service', service_name, action] for key, value in six.iteritems(kwargs): parameter = '%s=%s' % (key, va...
[ "Control a system service.\n\n :param action: the action to take on the service\n :param service_name: the name of the service to perform th action on\n :param **kwargs: additional params to be passed to the service command in\n the form of key=value.\n " ]
Please provide a description of the function:def service_running(service_name, **kwargs): if init_is_systemd(): return service('is-active', service_name) else: if os.path.exists(_UPSTART_CONF.format(service_name)): try: cmd = ['status', service_name] ...
[ "Determine whether a system service is running.\n\n :param service_name: the name of the service\n :param **kwargs: additional args to pass to the service command. This is\n used to pass additional key=value arguments to the\n service command line for managing specific ...
Please provide a description of the function:def adduser(username, password=None, shell='/bin/bash', system_user=False, primary_group=None, secondary_groups=None, uid=None, home_dir=None): try: user_info = pwd.getpwnam(username) log('user {0} already exists!'.format(user...
[ "Add a user to the system.\n\n Will log but otherwise succeed if the user already exists.\n\n :param str username: Username to create\n :param str password: Password for user; if ``None``, create a system user\n :param str shell: The default shell for the user\n :param bool system_user: Whether to cr...
Please provide a description of the function:def user_exists(username): try: pwd.getpwnam(username) user_exists = True except KeyError: user_exists = False return user_exists
[ "Check if a user exists" ]
Please provide a description of the function:def uid_exists(uid): try: pwd.getpwuid(uid) uid_exists = True except KeyError: uid_exists = False return uid_exists
[ "Check if a uid exists" ]
Please provide a description of the function:def group_exists(groupname): try: grp.getgrnam(groupname) group_exists = True except KeyError: group_exists = False return group_exists
[ "Check if a group exists" ]
Please provide a description of the function:def gid_exists(gid): try: grp.getgrgid(gid) gid_exists = True except KeyError: gid_exists = False return gid_exists
[ "Check if a gid exists" ]
Please provide a description of the function:def add_user_to_group(username, group): cmd = ['gpasswd', '-a', username, group] log("Adding user {} to group {}".format(username, group)) subprocess.check_call(cmd)
[ "Add a user to a group" ]
Please provide a description of the function:def chage(username, lastday=None, expiredate=None, inactive=None, mindays=None, maxdays=None, root=None, warndays=None): cmd = ['chage'] if root: cmd.extend(['--root', root]) if lastday: cmd.extend(['--lastday', lastday]) if exp...
[ "Change user password expiry information\n\n :param str username: User to update\n :param str lastday: Set when password was changed in YYYY-MM-DD format\n :param str expiredate: Set when user's account will no longer be\n accessible in YYYY-MM-DD format.\n ...
Please provide a description of the function:def rsync(from_path, to_path, flags='-r', options=None, timeout=None): options = options or ['--delete', '--executability'] cmd = ['/usr/bin/rsync', flags] if timeout: cmd = ['timeout', str(timeout)] + cmd cmd.extend(options) cmd.append(from_...
[ "Replicate the contents of a path" ]
Please provide a description of the function:def symlink(source, destination): log("Symlinking {} as {}".format(source, destination)) cmd = [ 'ln', '-sf', source, destination, ] subprocess.check_call(cmd)
[ "Create a symbolic link" ]
Please provide a description of the function:def mkdir(path, owner='root', group='root', perms=0o555, force=False): log("Making dir {} {}:{} {:o}".format(path, owner, group, perms)) uid = pwd.getpwnam(owner).pw_uid gid = grp.getgrnam(group).gr_gid realpath ...
[ "Create a directory" ]
Please provide a description of the function:def write_file(path, content, owner='root', group='root', perms=0o444): uid = pwd.getpwnam(owner).pw_uid gid = grp.getgrnam(group).gr_gid # lets see if we can grab the file and compare the context, to avoid doing # a write. existing_content = None ...
[ "Create or overwrite a file with the contents of a byte string." ]
Please provide a description of the function:def fstab_add(dev, mp, fs, options=None): return Fstab.add(dev, mp, fs, options=options)
[ "Adds the given device entry to the /etc/fstab file" ]
Please provide a description of the function:def mount(device, mountpoint, options=None, persist=False, filesystem="ext3"): cmd_args = ['mount'] if options is not None: cmd_args.extend(['-o', options]) cmd_args.extend([device, mountpoint]) try: subprocess.check_output(cmd_args) ...
[ "Mount a filesystem at a particular mountpoint" ]
Please provide a description of the function:def umount(mountpoint, persist=False): cmd_args = ['umount', mountpoint] try: subprocess.check_output(cmd_args) except subprocess.CalledProcessError as e: log('Error unmounting {}\n{}'.format(mountpoint, e.output)) return False i...
[ "Unmount a filesystem" ]
Please provide a description of the function:def mounts(): with open('/proc/mounts') as f: # [['/mount/point','/dev/path'],[...]] system_mounts = [m[1::-1] for m in [l.strip().split() for l in f.readlines()]] return system_mounts
[ "Get a list of all mounted volumes as [[mountpoint,device],[...]]" ]
Please provide a description of the function:def fstab_mount(mountpoint): cmd_args = ['mount', mountpoint] try: subprocess.check_output(cmd_args) except subprocess.CalledProcessError as e: log('Error unmounting {}\n{}'.format(mountpoint, e.output)) return False return True
[ "Mount filesystem using fstab" ]
Please provide a description of the function:def file_hash(path, hash_type='md5'): if os.path.exists(path): h = getattr(hashlib, hash_type)() with open(path, 'rb') as source: h.update(source.read()) return h.hexdigest() else: return None
[ "Generate a hash checksum of the contents of 'path' or None if not found.\n\n :param str hash_type: Any hash alrgorithm supported by :mod:`hashlib`,\n such as md5, sha1, sha256, sha512, etc.\n " ]
Please provide a description of the function:def check_hash(path, checksum, hash_type='md5'): actual_checksum = file_hash(path, hash_type) if checksum != actual_checksum: raise ChecksumError("'%s' != '%s'" % (checksum, actual_checksum))
[ "Validate a file using a cryptographic checksum.\n\n :param str checksum: Value of the checksum used to validate the file.\n :param str hash_type: Hash algorithm used to generate `checksum`.\n Can be any hash alrgorithm supported by :mod:`hashlib`,\n such as md5, sha1, sha256, sha512, etc.\n ...
Please provide a description of the function:def restart_on_change(restart_map, stopstart=False, restart_functions=None): def wrap(f): @functools.wraps(f) def wrapped_f(*args, **kwargs): return restart_on_change_helper( (lambda: f(*args, **kwargs)), restart_map, stop...
[ "Restart services based on configuration files changing\n\n This function is used a decorator, for example::\n\n @restart_on_change({\n '/etc/ceph/ceph.conf': [ 'cinder-api', 'cinder-volume' ]\n '/etc/apache/sites-enabled/*': [ 'apache2' ]\n })\n def config_changed(...
Please provide a description of the function:def restart_on_change_helper(lambda_f, restart_map, stopstart=False, restart_functions=None): if restart_functions is None: restart_functions = {} checksums = {path: path_hash(path) for path in restart_map} r = lambda_f()...
[ "Helper function to perform the restart_on_change function.\n\n This is provided for decorators to restart services if files described\n in the restart_map have changed after an invocation of lambda_f().\n\n @param lambda_f: function to call.\n @param restart_map: {file: [service, ...]}\n @param stop...
Please provide a description of the function:def pwgen(length=None): if length is None: # A random length is ok to use a weak PRNG length = random.choice(range(35, 45)) alphanumeric_chars = [ l for l in (string.ascii_letters + string.digits) if l not in 'l0QD1vAEIOUaeiou'] ...
[ "Generate a random pasword." ]
Please provide a description of the function:def is_phy_iface(interface): if interface: sys_net = '/sys/class/net' if os.path.isdir(sys_net): for iface in glob.glob(os.path.join(sys_net, '*')): if '/virtual/' in os.path.realpath(iface): continue ...
[ "Returns True if interface is not virtual, otherwise False." ]
Please provide a description of the function:def get_bond_master(interface): if interface: iface_path = '/sys/class/net/%s' % (interface) if os.path.exists(iface_path): if '/virtual/' in os.path.realpath(iface_path): return None master = os.path.join(ifa...
[ "Returns bond master if interface is bond slave otherwise None.\n\n NOTE: the provided interface is expected to be physical\n " ]
Please provide a description of the function:def list_nics(nic_type=None): if isinstance(nic_type, six.string_types): int_types = [nic_type] else: int_types = nic_type interfaces = [] if nic_type: for int_type in int_types: cmd = ['ip', 'addr', 'show', 'label', ...
[ "Return a list of nics of given type(s)" ]
Please provide a description of the function:def get_nic_mtu(nic): cmd = ['ip', 'addr', 'show', nic] ip_output = subprocess.check_output(cmd).decode('UTF-8').split('\n') mtu = "" for line in ip_output: words = line.split() if 'mtu' in words: mtu = words[words.index("mtu"...
[ "Return the Maximum Transmission Unit (MTU) for a network interface." ]
Please provide a description of the function:def get_nic_hwaddr(nic): cmd = ['ip', '-o', '-0', 'addr', 'show', nic] ip_output = subprocess.check_output(cmd).decode('UTF-8') hwaddr = "" words = ip_output.split() if 'link/ether' in words: hwaddr = words[words.index('link/ether') + 1] ...
[ "Return the Media Access Control (MAC) for a network interface." ]
Please provide a description of the function:def chdir(directory): cur = os.getcwd() try: yield os.chdir(directory) finally: os.chdir(cur)
[ "Change the current working directory to a different directory for a code\n block and return the previous directory after the block exits. Useful to\n run commands from a specificed directory.\n\n :param str directory: The directory path to change to for this context.\n " ]
Please provide a description of the function:def chownr(path, owner, group, follow_links=True, chowntopdir=False): uid = pwd.getpwnam(owner).pw_uid gid = grp.getgrnam(group).gr_gid if follow_links: chown = os.chown else: chown = os.lchown if chowntopdir: broken_symlink ...
[ "Recursively change user and group ownership of files and directories\n in given path. Doesn't chown path itself by default, only its children.\n\n :param str path: The string path to start changing ownership.\n :param str owner: The owner string to use when looking up the uid.\n :param str group: The g...
Please provide a description of the function:def lchownr(path, owner, group): chownr(path, owner, group, follow_links=False)
[ "Recursively change user and group ownership of files and directories\n in a given path, not following symbolic links. See the documentation for\n 'os.lchown' for more information.\n\n :param str path: The string path to start changing ownership.\n :param str owner: The owner string to use when looking ...
Please provide a description of the function:def owner(path): stat = os.stat(path) username = pwd.getpwuid(stat.st_uid)[0] groupname = grp.getgrgid(stat.st_gid)[0] return username, groupname
[ "Returns a tuple containing the username & groupname owning the path.\n\n :param str path: the string path to retrieve the ownership\n :return tuple(str, str): A (username, groupname) tuple containing the\n name of the user and group owning the path.\n :raises OSError: if the sp...
Please provide a description of the function:def get_total_ram(): with open('/proc/meminfo', 'r') as f: for line in f.readlines(): if line: key, value, unit = line.split() if key == 'MemTotal:': assert unit == 'kB', 'Unknown unit' ...
[ "The total amount of system RAM in bytes.\n\n This is what is reported by the OS, and may be overcommitted when\n there are multiple containers hosted on the same machine.\n " ]
Please provide a description of the function:def add_to_updatedb_prunepath(path, updatedb_path=UPDATEDB_PATH): if not os.path.exists(updatedb_path) or os.path.isdir(updatedb_path): # If the updatedb.conf file doesn't exist then don't attempt to update # the file as the package providing mlocate...
[ "Adds the specified path to the mlocate's udpatedb.conf PRUNEPATH list.\n\n This method has no effect if the path specified by updatedb_path does not\n exist or is not a file.\n\n @param path: string the path to add to the updatedb.conf PRUNEPATHS value\n @param updatedb_path: the path the updatedb.conf...
Please provide a description of the function:def modulo_distribution(modulo=3, wait=30, non_zero_wait=False): unit_number = int(local_unit().split('/')[1]) calculated_wait_time = (unit_number % modulo) * wait if non_zero_wait and calculated_wait_time == 0: return modulo * wait else: ...
[ " Modulo distribution\n\n This helper uses the unit number, a modulo value and a constant wait time\n to produce a calculated wait time distribution. This is useful in large\n scale deployments to distribute load during an expensive operation such as\n service restarts.\n\n If you have 1000 nodes tha...
Please provide a description of the function:def install_ca_cert(ca_cert, name=None): if not ca_cert: return if not isinstance(ca_cert, bytes): ca_cert = ca_cert.encode('utf8') if not name: name = 'juju-{}'.format(charm_name()) cert_file = '/usr/local/share/ca-certificates/{...
[ "\n Install the given cert as a trusted CA.\n\n The ``name`` is the stem of the filename where the cert is written, and if\n not provided, it will default to ``juju-{charm_name}``.\n\n If the cert is empty or None, or is unchanged, nothing is done.\n " ]
Please provide a description of the function:def get_audits(): audits = [] audits.append(TemplatedFile('/etc/securetty', SecureTTYContext(), template_dir=TEMPLATES_DIR, mode=0o0400, user='root', group='root')) return audits
[ "Get OS hardening Secure TTY audits.\n\n :returns: dictionary of audits\n " ]
Please provide a description of the function:def dict_keys_without_hyphens(a_dict): return dict( (key.replace('-', '_'), val) for key, val in a_dict.items())
[ "Return the a new dict with underscores instead of hyphens in keys." ]
Please provide a description of the function:def update_relations(context, namespace_separator=':'): # Add any relation data prefixed with the relation type. relation_type = charmhelpers.core.hookenv.relation_type() relations = [] context['current_relation'] = {} if relation_type is not None: ...
[ "Update the context with the relation data." ]
Please provide a description of the function:def juju_state_to_yaml(yaml_path, namespace_separator=':', allow_hyphens_in_keys=True, mode=None): config = charmhelpers.core.hookenv.config() # Add the charm_dir which we will need to refer to charm # file resources etc. config['...
[ "Update the juju config and state in a yaml file.\n\n This includes any current relation-get data, and the charm\n directory.\n\n This function was created for the ansible and saltstack\n support, as those libraries can use a yaml file to supply\n context to templates, but it may be useful generally ...
Please provide a description of the function:def get_audits(): if subprocess.call(['which', 'apache2'], stdout=subprocess.PIPE) != 0: log("Apache server does not appear to be installed on this node - " "skipping apache hardening", level=INFO) return [] context = ApacheConfConte...
[ "Get Apache hardening config audits.\n\n :returns: dictionary of audits\n " ]
Please provide a description of the function:def get_audits(): audits = [] settings = utils.get_settings('os') # Remove write permissions from $PATH folders for all regular users. # This prevents changing system-wide commands from normal users. path_folders = {'/usr/local/sbin', ...
[ "Get OS hardening access audits.\n\n :returns: dictionary of audits\n " ]
Please provide a description of the function:def harden(overrides=None): if overrides is None: overrides = [] def _harden_inner1(f): # As this has to be py2.7 compat, we can't use nonlocal. Use a trick # to capture the dictionary that can then be updated. _logged = {'done'...
[ "Hardening decorator.\n\n This is the main entry point for running the hardening stack. In order to\n run modules of the stack you must add this decorator to charm hook(s) and\n ensure that your charm config.yaml contains the 'harden' option set to\n one or more of the supported modules. Setting these w...
Please provide a description of the function:def kernel_version(): kver = check_output(['uname', '-r']).decode('UTF-8').strip() kver = kver.split('.') return (int(kver[0]), int(kver[1]))
[ " Retrieve the current major kernel version as a tuple e.g. (3, 13) " ]
Please provide a description of the function:def network_manager(): ''' Deals with the renaming of Quantum to Neutron in H and any situations that require compatability (eg, deploying H with network-manager=quantum, upgrading from G). ''' release = os_release('nova-common') manager = config(...
[]
Please provide a description of the function:def parse_mappings(mappings, key_rvalue=False): parsed = {} if mappings: mappings = mappings.split() for m in mappings: p = m.partition(':') if key_rvalue: key_index = 2 val_index = 0 ...
[ "By default mappings are lvalue keyed.\n\n If key_rvalue is True, the mapping will be reversed to allow multiple\n configs for the same lvalue.\n " ]
Please provide a description of the function:def parse_data_port_mappings(mappings, default_bridge='br-data'): # NOTE(dosaboy): we use rvalue for key to allow multiple values to be # proposed for <port> since it may be a mac address which will differ # across units this allowing first-known-good to be...
[ "Parse data port mappings.\n\n Mappings must be a space-delimited list of bridge:port.\n\n Returns dict of the form {port:bridge} where ports may be mac addresses or\n interface names.\n " ]
Please provide a description of the function:def parse_vlan_range_mappings(mappings): _mappings = parse_mappings(mappings) if not _mappings: return {} mappings = {} for p, r in six.iteritems(_mappings): mappings[p] = tuple(r.split(':')) return mappings
[ "Parse vlan range mappings.\n\n Mappings must be a space-delimited list of provider:start:end mappings.\n\n The start:end range is optional and may be omitted.\n\n Returns dict of the form {provider: (start, end)}.\n " ]
Please provide a description of the function:def extract_tarfile(archive_name, destpath): "Unpack a tar archive, optionally compressed" archive = tarfile.open(archive_name) archive.extractall(destpath)
[]
Please provide a description of the function:def extract_zipfile(archive_name, destpath): "Unpack a zip file" archive = zipfile.ZipFile(archive_name) archive.extractall(destpath)
[]
Please provide a description of the function:def _get_ipv6_network_from_address(address): if address['addr'].startswith('fe80') or address['addr'] == "::1": return None prefix = address['netmask'].split("/") if len(prefix) > 1: netmask = prefix[1] else: netmask = address['n...
[ "Get an netaddr.IPNetwork for the given IPv6 address\n :param address: a dict as returned by netifaces.ifaddresses\n :returns netaddr.IPNetwork: None if the address is a link local or loopback\n address\n " ]
Please provide a description of the function:def get_address_in_network(network, fallback=None, fatal=False): if network is None: if fallback is not None: return fallback if fatal: no_ip_found_error_out(network) else: return None networks = netw...
[ "Get an IPv4 or IPv6 address within the network from the host.\n\n :param network (str): CIDR presentation format. For example,\n '192.168.1.0/24'. Supports multiple networks as a space-delimited list.\n :param fallback (str): If no address is found, return fallback.\n :param fatal (boolean): If no ...
Please provide a description of the function:def is_ipv6(address): try: address = netaddr.IPAddress(address) except netaddr.AddrFormatError: # probably a hostname - so not an address at all! return False return address.version == 6
[ "Determine whether provided address is IPv6 or not." ]
Please provide a description of the function:def is_address_in_network(network, address): try: network = netaddr.IPNetwork(network) except (netaddr.core.AddrFormatError, ValueError): raise ValueError("Network (%s) is not in CIDR presentation format" % network) ...
[ "\n Determine whether the provided address is within a network range.\n\n :param network (str): CIDR presentation format. For example,\n '192.168.1.0/24'.\n :param address: An individual IPv4 or IPv6 address without a net\n mask or subnet prefix. For example, '192.168.1.1'.\n :returns bool...
Please provide a description of the function:def _get_for_address(address, key): address = netaddr.IPAddress(address) for iface in netifaces.interfaces(): addresses = netifaces.ifaddresses(iface) if address.version == 4 and netifaces.AF_INET in addresses: addr = addresses[netifa...
[ "Retrieve an attribute of or the physical interface that\n the IP address provided could be bound to.\n\n :param address (str): An individual IPv4 or IPv6 address without a net\n mask or subnet prefix. For example, '192.168.1.1'.\n :param key: 'iface' for the physical interface name or an attribute\...
Please provide a description of the function:def get_iface_addr(iface='eth0', inet_type='AF_INET', inc_aliases=False, fatal=True, exc_list=None): # Extract nic if passed /dev/ethX if '/' in iface: iface = iface.split('/')[-1] if not exc_list: exc_list = [] try: ...
[ "Return the assigned IP address for a given interface, if any.\n\n :param iface: network interface on which address(es) are expected to\n be found.\n :param inet_type: inet address family\n :param inc_aliases: include alias interfaces in search\n :param fatal: if True, raise exception i...
Please provide a description of the function:def get_iface_from_addr(addr): for iface in netifaces.interfaces(): addresses = netifaces.ifaddresses(iface) for inet_type in addresses: for _addr in addresses[inet_type]: _addr = _addr['addr'] # link local...
[ "Work out on which interface the provided address is configured." ]
Please provide a description of the function:def sniff_iface(f): def iface_sniffer(*args, **kwargs): if not kwargs.get('iface', None): kwargs['iface'] = get_iface_from_addr(unit_get('private-address')) return f(*args, **kwargs) return iface_sniffer
[ "Ensure decorated function is called with a value for iface.\n\n If no iface provided, inject net iface inferred from unit private address.\n " ]
Please provide a description of the function:def get_ipv6_addr(iface=None, inc_aliases=False, fatal=True, exc_list=None, dynamic_only=True): addresses = get_iface_addr(iface=iface, inet_type='AF_INET6', inc_aliases=inc_aliases, fatal=fatal, ...
[ "Get assigned IPv6 address for a given interface.\n\n Returns list of addresses found. If no address found, returns empty list.\n\n If iface is None, we infer the current primary interface by doing a reverse\n lookup on the unit private-address.\n\n We currently only support scope global IPv6 addresses ...
Please provide a description of the function:def get_bridges(vnic_dir='/sys/devices/virtual/net'): b_regex = "%s/*/bridge" % vnic_dir return [x.replace(vnic_dir, '').split('/')[1] for x in glob.glob(b_regex)]
[ "Return a list of bridges on the system." ]
Please provide a description of the function:def get_bridge_nics(bridge, vnic_dir='/sys/devices/virtual/net'): brif_regex = "%s/%s/brif/*" % (vnic_dir, bridge) return [x.split('/')[-1] for x in glob.glob(brif_regex)]
[ "Return a list of nics comprising a given bridge on the system." ]
Please provide a description of the function:def is_ip(address): try: # Test to see if already an IPv4/IPv6 address address = netaddr.IPAddress(address) return True except (netaddr.AddrFormatError, ValueError): return False
[ "\n Returns True if address is a valid IP address.\n " ]
Please provide a description of the function:def get_host_ip(hostname, fallback=None): if is_ip(hostname): return hostname ip_addr = ns_query(hostname) if not ip_addr: try: ip_addr = socket.gethostbyname(hostname) except Exception: log("Failed to resolve...
[ "\n Resolves the IP for a given hostname, or returns\n the input if it is already an IP.\n " ]
Please provide a description of the function:def get_hostname(address, fqdn=True): if is_ip(address): try: import dns.reversename except ImportError: if six.PY2: apt_install("python-dnspython", fatal=True) else: apt_install("py...
[ "\n Resolves hostname for given IP, or returns the input\n if it is already a hostname.\n " ]
Please provide a description of the function:def port_has_listener(address, port): cmd = ['nc', '-z', address, str(port)] result = subprocess.call(cmd) return not(bool(result))
[ "\n Returns True if the address:port is open and being listened to,\n else False.\n\n @param address: an IP address or hostname\n @param port: integer port\n\n Note calls 'zc' via a subprocess shell\n " ]
Please provide a description of the function:def get_relation_ip(interface, cidr_network=None): # Select the interface address first # For possible use as a fallback bellow with get_address_in_network try: # Get the interface specific IP address = network_get_primary_address(interface) ...
[ "Return this unit's IP for the given interface.\n\n Allow for an arbitrary interface to use with network-get to select an IP.\n Handle all address selection options including passed cidr network and\n IPv6.\n\n Usage: get_relation_ip('amqp', cidr_network='10.0.0.0/8')\n\n @param interface: string nam...
Please provide a description of the function:def ensure_compliance(self): for p in self.paths: if os.path.exists(p): if self.is_compliant(p): continue log('File %s is not in compliance.' % p, level=INFO) else: ...
[ "Ensure that the all registered files comply to registered criteria.\n " ]
Please provide a description of the function:def is_compliant(self, path): stat = self._get_stat(path) user = self.user group = self.group compliant = True if stat.st_uid != user.pw_uid or stat.st_gid != group.gr_gid: log('File %s is not owned by %s:%s.' % (...
[ "Checks if the path is in compliance.\n\n Used to determine if the path specified meets the necessary\n requirements to be in compliance with the check itself.\n\n :param path: the file path to check\n :returns: True if the path is compliant, False otherwise.\n " ]
Please provide a description of the function:def comply(self, path): utils.ensure_permissions(path, self.user.pw_name, self.group.gr_name, self.mode)
[ "Issues a chown and chmod to the file paths specified." ]
Please provide a description of the function:def is_compliant(self, path): if not os.path.isdir(path): log('Path specified %s is not a directory.' % path, level=ERROR) raise ValueError("%s is not a directory." % path) if not self.recursive: return super(Dire...
[ "Checks if the directory is compliant.\n\n Used to determine if the path specified and all of its children\n directories are in compliance with the check itself.\n\n :param path: the directory path to check\n :returns: True if the directory tree is compliant, otherwise False.\n " ...
Please provide a description of the function:def is_compliant(self, path): same_templates = self.templates_match(path) same_content = self.contents_match(path) same_permissions = self.permissions_match(path) if same_content and same_permissions and same_templates: r...
[ "Determines if the templated file is compliant.\n\n A templated file is only compliant if it has not changed (as\n determined by its sha256 hashsum) AND its file permissions are set\n appropriately.\n\n :param path: the path to check compliance.\n " ]
Please provide a description of the function:def run_service_actions(self): if not self.service_actions: return for svc_action in self.service_actions: name = svc_action['service'] actions = svc_action['actions'] log("Running service '%s' actions...
[ "Run any actions on services requested." ]
Please provide a description of the function:def comply(self, path): dirname = os.path.dirname(path) if not os.path.exists(dirname): os.makedirs(dirname) self.pre_write() render_and_write(self.template_dir, path, self.context()) utils.ensure_permissions(path...
[ "Ensures the contents and the permissions of the file.\n\n :param path: the path to correct\n " ]
Please provide a description of the function:def templates_match(self, path): template_path = get_template_path(self.template_dir, path) key = 'hardening:template:%s' % template_path template_checksum = file_hash(template_path) kv = unitdata.kv() stored_tmplt_checksum = ...
[ "Determines if the template files are the same.\n\n The template file equality is determined by the hashsum of the\n template files themselves. If there is no hashsum, then the content\n cannot be sure to be the same so treat it as if they changed.\n Otherwise, return whether or not the ...
Please provide a description of the function:def contents_match(self, path): checksum = file_hash(path) kv = unitdata.kv() stored_checksum = kv.get('hardening:%s' % path) if not stored_checksum: # If the checksum hasn't been generated, return False to ensure ...
[ "Determines if the file content is the same.\n\n This is determined by comparing hashsum of the file contents and\n the saved hashsum. If there is no hashsum, then the content cannot\n be sure to be the same so treat them as if they are not the same.\n Otherwise, return True if the hashs...
Please provide a description of the function:def permissions_match(self, path): audit = FilePermissionAudit(path, self.user, self.group, self.mode) return audit.is_compliant(path)
[ "Determines if the file owner and permissions match.\n\n :param path: the path to check.\n " ]
Please provide a description of the function:def save_checksum(self, path): checksum = file_hash(path) kv = unitdata.kv() kv.set('hardening:%s' % path, checksum) kv.flush()
[ "Calculates and saves the checksum for the path specified.\n\n :param path: the path of the file to save the checksum.\n " ]
Please provide a description of the function:def is_compliant(self, path): log("Auditing contents of file '%s'" % (path), level=DEBUG) with open(path, 'r') as fd: contents = fd.read() matches = 0 for pattern in self.pass_cases: key = re.compile(pattern, ...
[ "\n Given a set of content matching cases i.e. tuple(regex, bool) where\n bool value denotes whether or not regex is expected to match, check that\n all cases match as expected with the contents of the file. Cases can be\n expected to pass of fail.\n\n :param path: Path of file to...
Please provide a description of the function:def bool_from_string(value): if isinstance(value, six.string_types): value = six.text_type(value) else: msg = "Unable to interpret non-string value '%s' as boolean" % (value) raise ValueError(msg) value = value.strip().lower() i...
[ "Interpret string value as boolean.\n\n Returns True if value translates to True otherwise False.\n " ]
Please provide a description of the function:def bytes_from_string(value): BYTE_POWER = { 'K': 1, 'KB': 1, 'M': 2, 'MB': 2, 'G': 3, 'GB': 3, 'T': 4, 'TB': 4, 'P': 5, 'PB': 5, } if isinstance(value, six.string_types): ...
[ "Interpret human readable string value as bytes.\n\n Returns int\n " ]
Please provide a description of the function:def audit(*args): def wrapper(f): test_name = f.__name__ if _audits.get(test_name): raise RuntimeError( "Test name '{}' used more than once" .format(test_name)) non_callables = [fn for fn in args if...
[ "Decorator to register an audit.\n\n These are used to generate audits that can be run on a\n deployed system that matches the given configuration\n\n :param args: List of functions to filter tests against\n :type args: List[Callable[Dict]]\n " ]
Please provide a description of the function:def is_audit_type(*args): def _is_audit_type(audit_options): if audit_options.get('audit_type') in args: return True else: return False return _is_audit_type
[ "This audit is included in the specified kinds of audits.\n\n :param *args: List of AuditTypes to include this audit in\n :type args: List[AuditType]\n :rtype: Callable[Dict]\n " ]
Please provide a description of the function:def since_openstack_release(pkg, release): def _since_openstack_release(audit_options=None): _release = openstack_utils.get_os_codename_package(pkg) return openstack_utils.CompareOpenStackReleases(_release) >= release return _since_openstack_rel...
[ "This audit should run after the specified OpenStack version (incl).\n\n :param pkg: Package name to compare\n :type pkg: str\n :param release: The OpenStack release codename\n :type release: str\n :rtype: Callable[Dict]\n " ]
Please provide a description of the function:def run(audit_options): errors = {} results = {} for name, audit in sorted(_audits.items()): result_name = name.replace('_', '-') if result_name in audit_options.get('excludes', []): print( "Skipping {} because it ...
[ "Run the configured audits with the specified audit_options.\n\n :param audit_options: Configuration for the audit\n :type audit_options: Config\n\n :rtype: Dict[str, str]\n " ]
Please provide a description of the function:def action_parse_results(result): passed = True for test, result in result.items(): if result['success']: hookenv.action_set({test: 'PASS'}) else: hookenv.action_set({test: 'FAIL - {}'.format(result['message'])}) ...
[ "Parse the result of `run` in the context of an action.\n\n :param result: The result of running the security-checklist\n action on a unit\n :type result: Dict[str, Dict[str, str]]\n :rtype: int\n " ]
Please provide a description of the function:def generate_selfsigned(keyfile, certfile, keysize="1024", config=None, subject=None, cn=None): cmd = [] if config: cmd = ["/usr/bin/openssl", "req", "-new", "-newkey", "rsa:{}".format(keysize), "-days", "365", "-nodes", "-x509", ...
[ "Generate selfsigned SSL keypair\n\n You must provide one of the 3 optional arguments:\n config, subject or cn\n If more than one is provided the leftmost will be used\n\n Arguments:\n keyfile -- (required) full path to the keyfile to be created\n certfile -- (required) full path to the certfile t...
Please provide a description of the function:def ssh_directory_for_unit(application_name, user=None): if user: application_name = "{}_{}".format(application_name, user) _dir = os.path.join(NOVA_SSH_DIR, application_name) for d in [NOVA_SSH_DIR, _dir]: if not os.path.isdir(d): ...
[ "Return the directory used to store ssh assets for the application.\n\n :param application_name: Name of application eg nova-compute-something\n :type application_name: str\n :param user: The user that the ssh asserts are for.\n :type user: str\n :returns: Fully qualified directory path.\n :rtype:...
Please provide a description of the function:def ssh_known_host_key(host, application_name, user=None): cmd = [ 'ssh-keygen', '-f', known_hosts(application_name, user), '-H', '-F', host] try: # The first line of output is like '# Host xx found: line 1 type RS...
[ "Return the first entry in known_hosts for host.\n\n :param host: hostname to lookup in file.\n :type host: str\n :param application_name: Name of application eg nova-compute-something\n :type application_name: str\n :param user: The user that the ssh asserts are for.\n :type user: str\n :retur...
Please provide a description of the function:def remove_known_host(host, application_name, user=None): log('Removing SSH known host entry for compute host at %s' % host) cmd = ['ssh-keygen', '-f', known_hosts(application_name, user), '-R', host] subprocess.check_call(cmd)
[ "Remove the entry in known_hosts for host.\n\n :param host: hostname to lookup in file.\n :type host: str\n :param application_name: Name of application eg nova-compute-something\n :type application_name: str\n :param user: The user that the ssh asserts are for.\n :type user: str\n " ]
Please provide a description of the function:def is_same_key(key_1, key_2): # The key format get will be like '|1|2rUumCavEXWVaVyB5uMl6m85pZo=|Cp' # 'EL6l7VTY37T/fg/ihhNb/GPgs= ssh-rsa AAAAB', we only need to compare # the part start with 'ssh-rsa' followed with '= ', because the hash # value in th...
[ "Extract the key from two host entries and compare them.\n\n :param key_1: Host key\n :type key_1: str\n :param key_2: Host key\n :type key_2: str\n " ]
Please provide a description of the function:def add_known_host(host, application_name, user=None): cmd = ['ssh-keyscan', '-H', '-t', 'rsa', host] try: remote_key = subprocess.check_output(cmd).strip() except Exception as e: log('Could not obtain SSH host key from %s' % host, level=ERRO...
[ "Add the given host key to the known hosts file.\n\n :param host: host name\n :type host: str\n :param application_name: Name of application eg nova-compute-something\n :type application_name: str\n :param user: The user that the ssh asserts are for.\n :type user: str\n " ]