text
stringlengths
81
112k
Returns the mountpoint for this path def mount_for_path(path, client): """Returns the mountpoint for this path""" backend_data = client.list_secret_backends()['data'] backends = [mnt for mnt in backend_data.keys()] path_bits = path.split('/') if len(path_bits) == 1: vault_path = "%s/" % pat...
Returns the type of backend at the given mountpoint def backend_type(path, client): """Returns the type of backend at the given mountpoint""" backends = client.list_secret_backends()['data'] vault_path = "%s/" % path return backends[vault_path]['type']
Loads a words file as a list of lines def load_word_file(filename): """Loads a words file as a list of lines""" words_file = resource_filename(__name__, "words/%s" % filename) handle = open(words_file, 'r') words = handle.readlines() handle.close() return words
Returns a random entry from a list of things def choose_one(things): """Returns a random entry from a list of things""" choice = SystemRandom().randint(0, len(things) - 1) return things[choice].strip()
Returns a file path relative to another path. def subdir_path(directory, relative): """Returns a file path relative to another path.""" item_bits = directory.split(os.sep) relative_bits = relative.split(os.sep) for i, _item in enumerate(item_bits): if i == len(relative_bits) - 1: re...
Opens something that might be binary but also might be "plain text". def open_maybe_binary(filename): """Opens something that might be binary but also might be "plain text".""" if sys.version_info >= (3, 0): data = open(filename, 'rb').read() try: return data.decode('utf-8')...
Ensures a directory exists def ensure_dir(path): """Ensures a directory exists""" if not (os.path.exists(path) and os.path.isdir(path)): os.mkdir(path)
Invoked atexit, this removes our tmpdir def clean_tmpdir(path): """Invoked atexit, this removes our tmpdir""" if os.path.exists(path) and \ os.path.isdir(path): rmtree(path)
Ensure that every string in a dict is properly represented by unicode strings def dict_unicodeize(some_dict): """Ensure that every string in a dict is properly represented by unicode strings""" # some python 2/3 compat if isinstance(some_dict, ("".__class__, u"".__class__)): if sys.version...
Performs a base type comparison between two dicts def diff_dict(dict1, dict2, ignore_missing=False): """Performs a base type comparison between two dicts""" unidict1 = dict_unicodeize(dict1) unidict2 = dict_unicodeize(dict2) if ((not ignore_missing) and (len(unidict1) != len(unidict2))) or \ (ig...
Will ensure a dict has values sourced from either another dict or based on the provided default def map_val(dest, src, key, default=None, src_key=None): """Will ensure a dict has values sourced from either another dict or based on the provided default""" if not src_key: src_key = key ...
Filters a context This will return a new context with only the resources that are actually available for use. Uses tags and command line options to make determination. def filtered_context(context): """Filters a context This will return a new context with only the resources that are actually av...
Ensure the backend for a resource is properly in context def ensure_backend(resource, backend, backends, opt, managed=True): """Ensure the backend for a resource is properly in context""" existing_mount = find_backend(resource.mount, backends) if not existing_mount: new_mount = backend(resource, op...
Given a list of mods (as returned by py_resources) attempts to determine if a given Python obj fits one of the models def find_model(config, obj, mods): """Given a list of mods (as returned by py_resources) attempts to determine if a given Python obj fits one of the models""" for mod in mods: i...
Discovers all aomi Vault resource models. This includes anything extending aomi.model.Mount or aomi.model.Resource. def py_resources(): """Discovers all aomi Vault resource models. This includes anything extending aomi.model.Mount or aomi.model.Resource.""" aomi_mods = [m for m, _v in ...
Loads and returns a full context object based on the Secretfile def load(config, opt): """Loads and returns a full context object based on the Secretfile""" ctx = Context(opt) seed_map = py_resources() seed_keys = sorted(set([m[0] for m in seed_map]), key=resource_sort) for conf...
Will thaw every secret into an appropriate temporary location def thaw(self, tmp_dir): """Will thaw every secret into an appropriate temporary location""" for resource in self.resources(): if resource.present: resource.thaw(tmp_dir)
Freezes every resource within a context def freeze(self, dest_dir): """Freezes every resource within a context""" for resource in self.resources(): if resource.present: resource.freeze(dest_dir)
Vault resources within context def resources(self): """Vault resources within context""" res = [] for resource in self._resources: res = res + resource.resources() return res
Add a resource to the context def add(self, resource): """Add a resource to the context""" if isinstance(resource, Resource): if isinstance(resource, Secret) and \ resource.mount != 'cubbyhole': ensure_backend(resource, SecretBac...
Removes a resource from the context def remove(self, resource): """Removes a resource from the context""" if isinstance(resource, Resource): self._resources.remove(resource)
Synchronizes policies only def sync_policies(self, vault_client): """Synchronizes policies only""" p_resources = [x for x in self.resources() if isinstance(x, Policy)] for resource in p_resources: resource.sync(vault_client) return [x for x in self.re...
Synchronizes auth mount wrappers. These happen early in the cycle, to ensure that user backends are proper. They may also be used to set mount tuning def sync_auth(self, vault_client, resources): """Synchronizes auth mount wrappers. These happen early in the cycle, to ensure tha...
Handle the actual (potential) mounting of a secret backend. This is called in multiple contexts, but the action will always be the same. If we were not aware of the mountpoint at the start and it has not already been mounted, then mount it. def actually_mount(self, vault_client, resource, activ...
Synchronizes mount points. Removes things before adding new. def sync_mounts(self, active_mounts, resources, vault_client): """Synchronizes mount points. Removes things before adding new.""" # Create a resource set that is only explicit mounts # and sort so removals are first ...
Synchronizes the context to the Vault server. This has the effect of updating every resource which is in the context and has changes pending. def sync(self, vault_client, opt): """Synchronizes the context to the Vault server. This has the effect of updating every resource which is ...
Will remove any mount point which is not actually defined in this context. def prune(self, vault_client): """Will remove any mount point which is not actually defined in this context. """ existing = getattr(vault_client, SecretBackend.list_fun)()['data'].items...
Updates the context based on the contents of the Vault server. Note that some resources can not be read after they have been written to and it is up to those classes to handle that case properly. def fetch(self, vault_client): """Updates the context based on the contents of the Vault ...
Will create representational objects for any preset (push) based AppRole Secrets. def presets(self, presets, opt): """Will create representational objects for any preset (push) based AppRole Secrets.""" for preset in presets: secret_obj = dict(preset) secret_obj[...
Renders a Secret key name appropriately def secret_key_name(path, key, opt): """Renders a Secret key name appropriately""" value = key if opt.merge_path: norm_path = [x for x in path.split('/') if x] value = "%s_%s" % ('_'.join(norm_path), key) if opt.add_prefix: value = "%s%s"...
Determine the real deal template file def grok_template_file(src): """Determine the real deal template file""" if not src.startswith('builtin:'): return abspath(src) builtin = src.split(':')[1] builtin = "templates/%s.j2" % builtin return resource_filename(__name__, builtin)
Blends secret and static variables together def blend_vars(secrets, opt): """Blends secret and static variables together""" base_obj = load_vars(opt) merged = merge_dicts(base_obj, secrets) template_obj = dict((k, v) for k, v in iteritems(merged) if v) # give templates something to iterate over ...
Writes a template using variables from a vault path def template(client, src, dest, paths, opt): """Writes a template using variables from a vault path""" key_map = cli_hash(opt.key_map) obj = {} for path in paths: response = client.read(path) if not response: raise aomi.exc...
Writes an actual secret out to a file def write_raw_file(secret, dest): """Writes an actual secret out to a file""" secret_file = None secret_filename = abspath(dest) if sys.version_info >= (3, 0): if not isinstance(secret, str): secret_file = open(secret_filename, 'wb') if not...
Write the contents of a vault path/key to a file. Is smart enough to attempt and handle binary files that are base64 encoded. def raw_file(client, src, dest, opt): """Write the contents of a vault path/key to a file. Is smart enough to attempt and handle binary files that are base64 encoded.""" ...
Renders a shell snippet based on paths in a Secretfile def env(client, paths, opt): """Renders a shell snippet based on paths in a Secretfile""" old_prefix = False old_prefix = opt.prefix and not (opt.add_prefix or opt.add_suffix or ...
Renders a shell environment snippet with AWS information def aws(client, path, opt): """Renders a shell environment snippet with AWS information""" try: creds = client.read(path) except (hvac.exceptions.InternalServerError) as vault_exception: # this is how old vault behaves if vau...
Create the proper generated key value def generated_key(key): """Create the proper generated key value""" key_name = key['name'] if key['method'] == 'uuid': LOG.debug("Setting %s to a uuid", key_name) return str(uuid4()) elif key['method'] == 'words': LOG.debug("Setting %s to ra...
Generates the secret object, respecting existing information and user specified options def generate_obj(self): """Generates the secret object, respecting existing information and user specified options""" secret_obj = {} if self.existing: secret_obj = deepcopy(self....
Handle uncaught/unexpected errors and be polite about it def unhandled(exception, opt): """ Handle uncaught/unexpected errors and be polite about it""" exmod = type(exception).__module__ name = "%s.%s" % (exmod, type(exception).__name__) # this is a Vault error if exmod == 'aomi.exceptions' or exmo...
Politely display an unexpected error def output(message, opt, extra=None): """ Politely display an unexpected error""" print(message, file=sys.stderr) if opt.verbose: if extra: print(extra) traceback.print_exc(sys.stderr)
Ensures that we are returning just seconds def grok_seconds(lease): """Ensures that we are returning just seconds""" if lease.endswith('s'): return int(lease[0:-1]) elif lease.endswith('m'): return int(lease[0:-1]) * 60 elif lease.endswith('h'): return int(lease[0:-1]) * 3600 ...
Renews a secret. This will occur unless the user has specified on the command line that it is not neccesary def renew_secret(client, creds, opt): """Renews a secret. This will occur unless the user has specified on the command line that it is not neccesary""" if opt.reuse_token: return sec...
Returns a vault token based on the role and seret id def approle_token(vault_client, role_id, secret_id): """Returns a vault token based on the role and seret id""" resp = vault_client.auth_approle(role_id, secret_id) if 'auth' in resp and 'client_token' in resp['auth']: return resp['auth']['client...
Returns a vault token based on the app and user id. def app_token(vault_client, app_id, user_id): """Returns a vault token based on the app and user id.""" resp = vault_client.auth_app_id(app_id, user_id) if 'auth' in resp and 'client_token' in resp['auth']: return resp['auth']['client_token'] ...
Generates metadata for a token def token_meta(opt): """Generates metadata for a token""" meta = { 'via': 'aomi', 'operation': opt.operation, 'hostname': socket.gethostname() } if 'USER' in os.environ: meta['unix_user'] = os.environ['USER'] if opt.metadata: m...
Returns mountpoint details for a backend def get_backend(backend, path, backends): """Returns mountpoint details for a backend""" m_norm = normalize_vault_path(path) for mount_name, values in backends.items(): b_norm = normalize_vault_path(mount_name) if (m_norm == b_norm) and values['type'...
Error catching Vault API wrapper This decorator wraps API interactions with Vault. It will catch and return appropriate error output on common problems. Do we even need this now that we extend the hvac class? def wrap_hvac(msg): """Error catching Vault API wrapper This decorator wraps API inter...
Attempts to determine the version of Vault that a server is running. Some actions will change on older Vault deployments. def server_version(self): """Attempts to determine the version of Vault that a server is running. Some actions will change on older Vault deployments.""" ...
This sets up the tokens we expect to see in a way that hvac also expects. def connect(self, opt): """This sets up the tokens we expect to see in a way that hvac also expects.""" if not self._kwargs['verify']: LOG.warning('Skipping SSL Validation!') self.version = se...
Generate our first token based on workstation configuration def init_token(self): """Generate our first token based on workstation configuration""" app_filename = appid_file() token_filename = token_file() approle_filename = approle_file() token = None if 'VAULT_ROLE_ID...
Return a properly annotated token for our use. This token will be revoked at the end of the session. The token will have some decent amounts of metadata tho. def op_token(self, display_name, opt): """Return a properly annotated token for our use. This token will be revoked at the end of...
Wrap the hvac read call, using the right token for cubbyhole interactions. def read(self, path, wrap_ttl=None): """Wrap the hvac read call, using the right token for cubbyhole interactions.""" path = sanitize_mount(path) if path.startswith('cubbyhole'): self.token = ...
Wrap the hvac write call, using the right token for cubbyhole interactions. def write(self, path, wrap_ttl=None, **kwargs): """Wrap the hvac write call, using the right token for cubbyhole interactions.""" path = sanitize_mount(path) val = None if path.startswith('cubbyh...
Wrap the hvac delete call, using the right token for cubbyhole interactions. def delete(self, path): """Wrap the hvac delete call, using the right token for cubbyhole interactions.""" path = sanitize_mount(path) val = None if path.startswith('cubbyhole'): sel...
Will attempt to retrieve a GPG public key from Keybase, importing if neccesary def from_keybase(username): """Will attempt to retrieve a GPG public key from Keybase, importing if neccesary""" public_key = key_from_keybase(username) fingerprint = public_key['fingerprint'][-8:].upper().encode('ascii'...
Will retrieve a GPG key from either Keybase or GPG directly def grok_keys(config): """Will retrieve a GPG key from either Keybase or GPG directly""" key_ids = [] for key in config['pgp_keys']: if key.startswith('keybase:'): key_id = from_keybase(key[8:]) LOG.debug("Encryptin...
Generates a ZIP file of secrets def freeze_archive(tmp_dir, dest_prefix): """Generates a ZIP file of secrets""" zip_filename = "%s/aomi-blah.zip" % tmp_dir archive = zipfile.ZipFile(zip_filename, 'w') for root, _dirnames, filenames in os.walk(dest_prefix): for filename in filenames: ...
Encrypts the zip file def freeze_encrypt(dest_dir, zip_filename, config, opt): """Encrypts the zip file""" pgp_keys = grok_keys(config) icefile_prefix = "aomi-%s" % \ os.path.basename(os.path.dirname(opt.secretfile)) if opt.icefile_prefix: icefile_prefix = opt.icefile_prefi...
Iterates over the Secretfile looking for secrets to freeze def freeze(dest_dir, opt): """Iterates over the Secretfile looking for secrets to freeze""" tmp_dir = ensure_tmpdir() dest_prefix = "%s/dest" % tmp_dir ensure_dir(dest_dir) ensure_dir(dest_prefix) config = get_secretfile(opt) Contex...
Decrypts the encrypted ice file def thaw_decrypt(vault_client, src_file, tmp_dir, opt): """Decrypts the encrypted ice file""" if not os.path.isdir(opt.secrets): LOG.info("Creating secret directory %s", opt.secrets) os.mkdir(opt.secrets) zip_file = "%s/aomi.zip" % tmp_dir if opt.gpg_p...
Given the combination of a Secretfile and the output of a freeze operation, will restore secrets to usable locations def thaw(vault_client, src_file, opt): """Given the combination of a Secretfile and the output of a freeze operation, will restore secrets to usable locations""" if not os.path.exists(sr...
Determines if changes are needed for the Vault backend def diff(self): """Determines if changes are needed for the Vault backend""" if not self.present: if self.existing: return DEL return NOOP is_diff = NOOP if self.present and self.existing: ...
Synchronizes the local and remote Vault resources. Has the net effect of adding backend if needed def sync(self, vault_client): """Synchronizes the local and remote Vault resources. Has the net effect of adding backend if needed""" if self.present: if not self.existing: ...
Synchtonizes any tunables we have set def sync_tunables(self, vault_client): """Synchtonizes any tunables we have set""" if not self.config: return a_prefix = self.tune_prefix if self.tune_prefix: a_prefix = "%s/" % self.tune_prefix v_path = "sys/mounts...
Updates local resource with context on whether this backend is actually mounted and available def fetch(self, vault_client, backends): """Updates local resource with context on whether this backend is actually mounted and available""" if not is_mounted(self.backend, self.path, backends)...
Unmounts a backend within Vault def unmount(self, client): """Unmounts a backend within Vault""" getattr(client, self.unmount_fun)(mount_point=self.path)
Actually mount something in Vault def actually_mount(self, client): """Actually mount something in Vault""" a_obj = self.config.copy() if 'description' in a_obj: del a_obj['description'] try: m_fun = getattr(client, self.mount_fun) if self.descriptio...
Will perform some validation and copy a decrypted secret to it's final location def thaw(self, tmp_dir): """Will perform some validation and copy a decrypted secret to it's final location""" for sfile in self.secrets(): src_file = "%s/%s" % (tmp_dir, sfile) err_m...
A tunable resource maps against a backend... def tunable(self, obj): """A tunable resource maps against a backend...""" self.tune = dict() if 'tune' in obj: for tunable in MOUNT_TUNABLES: tunable_key = tunable[0] map_val(self.tune, obj['tune'], tunabl...
Get a filehandle for exporting def export_handle(self, directory): """Get a filehandle for exporting""" filename = getattr(self, 'filename') dest_file = "%s/%s" % (directory, filename) dest_dir = os.path.dirname(dest_file) if not os.path.isdir(dest_dir): os.mkdir(des...
Export exportable resources decoding as needed def export(self, directory): """Export exportable resources decoding as needed""" if not self.existing or not hasattr(self, 'filename'): return secret_h = self.export_handle(directory) obj = self.existing if isinstance(...
Copies a secret into a particular location def freeze(self, tmp_dir): """Copies a secret into a particular location""" for sfile in self.secrets(): src_file = hard_path(sfile, self.opt.secrets) if not os.path.exists(src_file): raise aomi_excep.IceFile("%s secret ...
Determine the desired state of this resource based on data present def grok_state(self, obj): """Determine the desired state of this resource based on data present""" if 'state' in obj: my_state = obj['state'].lower() if my_state != 'absent' and my_state != 'pres...
Base validation method. Will inspect class attributes to dermine just what should be present def validate(self, obj): """Base validation method. Will inspect class attributes to dermine just what should be present""" if 'tags' in obj and not isinstance(obj['tags'], list): ra...
Determine if something has changed or not def diff(self, obj=None): """Determine if something has changed or not""" if self.no_resource: return NOOP if not self.present: if self.existing: return DEL return NOOP if not obj: ...
Populate internal representation of remote Vault resource contents def fetch(self, vault_client): """Populate internal representation of remote Vault resource contents""" result = self.read(vault_client) if result: if isinstance(result, dict) and 'data' in result: ...
Update remove Vault resource contents if needed def sync(self, vault_client): """Update remove Vault resource contents if needed""" if self.present and not self.existing: LOG.info("Writing new %s to %s", self.secret_format, self) self.write(vault_client) ...
Determines whether or not resource is filtered. Resources may be filtered if the tags do not match or the user has specified explict paths to include or exclude via command line options def filtered(self): """Determines whether or not resource is filtered. Resources may be filte...
A different implementation of diff that is used for those Vault resources that are write-only such as AWS root configs def diff_write_only(resource): """A different implementation of diff that is used for those Vault resources that are write-only such as AWS root configs""" ...
Read from Vault while handling non surprising errors. def read(self, client): """Read from Vault while handling non surprising errors.""" val = None if self.no_resource: return val LOG.debug("Reading from %s", self) try: val = client.read(self.path) ...
Write to Vault while handling non-surprising errors. def write(self, client): """Write to Vault while handling non-surprising errors.""" val = None if not self.no_resource: val = client.write(self.path, **self.obj()) return val
Searches up from a directory looking for a file def find_file(name, directory): """Searches up from a directory looking for a file""" path_bits = directory.split(os.sep) for i in range(0, len(path_bits) - 1): check_path = path_bits[0:len(path_bits) - i] check_file = "%s%s%s" % (os.sep.join(...
Looks in a file for a string. def in_file(string, search_file): """Looks in a file for a string.""" handle = open(search_file, 'r') for line in handle.readlines(): if string in line: return True return False
Will check directories upwards from the Secretfile in order to ensure the gitignore file is set properly def gitignore(opt): """Will check directories upwards from the Secretfile in order to ensure the gitignore file is set properly""" directory = os.path.dirname(abspath(opt.secretfile)) gitignore_...
Will check the permissions of things which really should be secret files def secret_file(filename): """Will check the permissions of things which really should be secret files""" filestat = os.stat(abspath(filename)) if stat.S_ISREG(filestat.st_mode) == 0 and \ stat.S_ISLNK(filestat.st_mode)...
Super simple "object" validation. def validate_obj(keys, obj): """Super simple "object" validation.""" msg = '' for k in keys: if isinstance(k, str): if k not in obj or (not isinstance(obj[k], list) and not obj[k]): if msg: msg = "%s," % msg ...
Will make checks against include/exclude to determine if we actually care about the path in question. def specific_path_check(path, opt): """Will make checks against include/exclude to determine if we actually care about the path in question.""" if opt.exclude: if path in opt.exclude: ...
Do basic validation on an object def check_obj(keys, name, obj): """Do basic validation on an object""" msg = validate_obj(keys, obj) if msg: raise aomi.exceptions.AomiData("object check : %s in %s" % (msg, name))
Returns a quote-unquote sanitized mount path def sanitize_mount(mount): """Returns a quote-unquote sanitized mount path""" sanitized_mount = mount if sanitized_mount.startswith('/'): sanitized_mount = sanitized_mount[1:] if sanitized_mount.endswith('/'): sanitized_mount = sanitized_mou...
Validates a GPG key fingerprint This handles both pre and post GPG 2.1 def gpg_fingerprint(key): """Validates a GPG key fingerprint This handles both pre and post GPG 2.1""" if (len(key) == 8 and re.match(r'^[0-9A-F]{8}$', key)) or \ (len(key) == 40 and re.match(r'^[0-9A-F]{40}$', key)): ...
Validates that we are some kinda unicode string def is_unicode_string(string): """Validates that we are some kinda unicode string""" try: if sys.version_info >= (3, 0): # isn't a python 3 str actually unicode if not isinstance(string, str): string.decode('utf-8')...
Validates that the object itself is some kinda string def is_unicode(string): """Validates that the object itself is some kinda string""" str_type = str(type(string)) if str_type.find('str') > 0 or str_type.find('unicode') > 0: return True return False
Safe version of the modulo operation (%) of strings Parameters ---------- s: str string to apply the modulo operation with meta: dict or tuple meta informations to insert (usually via ``s % meta``) checked: {'KEY', 'VALUE'}, optional Security parameter for the recursive stru...
Method that extracts the specified sections out of the given string if (and only if) the docstring follows the numpy documentation guidelines [1]_. Note that the section either must appear in the :attr:`param_like_sections` or the :attr:`text_sections` attribute. Parameters ----...
Decorator method to extract sections from a function docstring Parameters ---------- ``*args`` and ``**kwargs`` See the :meth:`get_sections` method. Note, that the first argument will be the docstring of the specified function Returns ------- fun...
Convenience method to set the __doc__ attribute of a python object def _set_object_doc(self, obj, doc, stacklevel=3): """Convenience method to set the __doc__ attribute of a python object """ if isinstance(obj, types.MethodType) and six.PY2: obj = obj.im_func try: ...
Dedent the docstring of a function and substitute with :attr:`params` Parameters ---------- func: function function with the documentation to dedent and whose sections shall be inserted from the :attr:`params` attribute def dedent(self, func): """ Dedent...
Dedent a string and substitute with the :attr:`params` attribute Parameters ---------- s: str string to dedent and insert the sections of the :attr:`params` attribute stacklevel: int The stacklevel for the warning raised in :func:`safe_module` when ...
Substitute in the docstring of a function with indented :attr:`params` Parameters ---------- indent: int The number of spaces that the substitution should be indented Returns ------- function Wrapper that takes a function as input and substitutes...