stslib package

stslib.core module

Summary:
stslib generates temporary credentials used to assume roles across many AWS accounts. It is commonly used for progammatic use cases where avoiding a multi-factor auth prompt in a cli environment is desired
Module Attributes:
logger - logging object
Example Usage:
see https://bitbucket.org/blakeca00/stslib/overview
class stslib.core.StsCore(**kwargs)[source]

Bases: object

Class definition, STS credentials library

calc_lifetime(credentials=None, human_readable=False)[source]

Return remaining time on sts token, sts temporary credentials

Args:
type credentials:
 STSCredentials object (if specified)
param credentials:
 generated for which remaining life requested
type self.token:
 STSToken object (if exists)
param self.token:
 latest token generated
Returns:
tuple containing TYPE: datetime.timedelta objects (DEFAULT) human_readable: returns tuple containing strings
(
    token_life_remaining,
    credential_life_remaining
)
current_credentials()[source]

returns credentials when refreshed

Args:
type self.credentials:
 dict
param self.credentials:
 latest credentials generated and stored as class attribute
Returns:
Valid credentials | None if expired {}
filter_args(kwarg_dict, *args)[source]
Summary:
arg, kwarg validity test
Args:
kwarg_dict: kwargs passed in to calling method or func args: valid keywords for the caller
Returns:
True if kwargs are valid; else raise exception
generate_credentials(accounts, token=None, strict=True)[source]
Summary:
generate temporary credentials for profiles
Args:
accounts: TYPE: list
List of account aliases or profile names from the local awscli configuration in accounts to assume a role
strict: TYPE: list
Determines if strict membership checking is applied to aliases found in accounts parameter list. if strict=True (Default), then if 1 account profilename given in the accounts list, all accounts will be rejected and no temporary credentials are generated. If False, temporary credentials generated for all profiles that are valid, only invalid profiles will fail to generate credentials
Returns:
iam role temporary credentials | TYPE: Dict
{
    'sts-acme-gen-ra1-prod' : {
        'AccessKeyId': 'ASIAI6QV2U3JJAYRHCJQ',
        'Expiration': datetime.datetime(2017, 8, 25, 20, 5, 37, tzinfo=tzutc()),
        'SecretAccessKey': 'MdjPAkXTHl12k64LSjmgTWMsmnHk4cJfeMHdXMLA',
        'SessionToken': 'FQoDYXdzEDMaDHAaP2wi/+77fNJJryKvAdVZjYKk...zQU='
    },
    'sts-acme-gen-ra1-dev' : {
        'AccessKeyId': 'ASIAI6QV2U3 ...',
    }
}
generate_session_token(**kwargs)[source]
Summary:
generates session token for use in gen temp credentials
Args:
lifetime (int): token lifetime duration in hours mfa_code (str): 6 digit authorization code from a multi-factor (mfa) authentication device
Returns:
session credentials | TYPE: dict
{
    'AccessKeyId': 'ASIAI6QV2U3JJAYRHCJQ',
    'StartTime': datetime.datetime(2017, 8, 25, 20, 2, 37, tzinfo=tzutc()),
    'Expiration': datetime.datetime(2017, 8, 25, 20, 5, 37, tzinfo=tzutc()),
    'SecretAccessKey': 'MdjPAkXTHl12k64LSjmgTWMsmnHk4cJfeMHdXMLA',
    'SessionToken': 'FQoDYXdzEDMaDHAaP2wi/+77fNJJryKvAdVZjYKk...zQU='
}
get_mfa_info(user, client)[source]
Summary:
Extracts the mfa_serial arn (soft token) or SerialNumber (if hardware token assigned)
Args:
type user:string
param user:iam_user in local awscli profile. user may be a profile name which is used exclusively in the awscli but does not represent an actual iam name recorded in the Amazon Web Services account.
Returns:
TYPE: string
get_valid_users(client)[source]
Summary:
Retrieve list valid iam users from local config
Arg:
iam client object
Returns:
TYPE list
local_config()[source]

override defaults in statics with local config values

parse_profiles(pre_name, post_name)[source]

Creates list of account profiles from local configuration file

Args:

:type string :param pre_name: input file containing iam role credentials in non-default location or fname

:type string :param post_name: json file containing role profiles for which stslib will generate temporary credentials. This file is generated by stslib and will be located in the ~/.stslib directory. Format:

Returns:
type:dictionary
param profile_dict:
 list of aws account profile role names, role arns
{
    "AliceIAMUser": {
        "aws_access_key_id": "AKIAIDYCI6Q4469WORVQ",
        "aws_secret_access_key": "Wf2A0dx1ApMrEdljjkjteBmqqCdPB3Ng3kx/ow",
        "mfa_serial": "arn:aws:iam::715400231659:mfa/AliceIAMUser"
    },
    "DynamoDBAccessRole": {
        "role_arn": "arn:aws:iam::357115911622:role/DynamoDBFullAccess",
        "mfa_serial": "arn:aws:iam::715400231659:mfa/AliceIAMUser",
        "source_profile": "default"
    },
    "EC2AccessRole": {
        ...
    }
}
refactor(input_file='/home/docs/.aws/credentials', output_file='profiles.json', force_rewrite=True)[source]
Summary:

Refactors native awscli credentials file into a useable form. Credentials file in the native format used by awscli is refactored into a json file located in the stslib configuration directory (typically ~/.stslib) in user’s home.

refactor exists as a StsCore class method so that it refactoring operations can be initiated on an ad hoc basis whenever credentails are refreshed

Args:
input_file (str): pathname of awscli credentails file output_file (str): name of json formatted output file, post awscli transformation
Returns:
TYPE Boolean | Success or Failure

Module Index


stslib.async module

Summary:
Non-blocking event caller
Module Attributes:
logger: TYPE logging
Returns:
TYPE: Bool, False when cycle completes

Example Use:

thread = TimeKeeper(
roles=[‘DynamoDBReadOnlyRole’, ‘EC2FullAccessRole’], event=<self.method of calling class>, RefreshCount=3

) thread.start()

class stslib.async.TimeKeeper(roles, event, RefreshCount, debug=False)[source]

Bases: threading.Thread

class def async process trigger

dead()[source]
halt()[source]
run()[source]
Summary:
non-blocking event trigger cycle
RETURNS:
thread status information | TYPE: dict
thread_status(**kwargs)[source]

log thread and event status

stslib.async.convert_time(timedelta_object, return_iter=False)[source]
Summary:
convert timedelta objects to human readable output
Args:
  • timedelta_object | TYPE: datetime.timedelta
  • return_iter (tuple): tuple containing time sequence
Returns:
days, hours, minutes, seconds | TYPE: tuple (integers) or human readable, notated units | TYPE: string
stslib.async.convert_to_seconds(days, hours, minutes, seconds)[source]
Summary:
convert time to seconds
Args:
time delinations in days, hours, minutes, seconds | TYPE: integer
Returns:
timedata in seconds | TYPE: integer

Module Index


stslib.refactor module

refactor Module Level comments NEEDED HERE

Module Attributes:
logger - logging object
stslib.refactor.parse_awscli(parameter_input=None, parameter_output=None)[source]
Summary:
imports awscli credentials file, refactors format to json
Args:
parameter_input: TYPE: string, opt input file if not awscli default parameter_output: TYPE: string, opt ouput file if not stslib default
Returns:
Success or Failure, TYPE: Boolean

Module Index


stslib.vault module

Summary:

The vault module contains classes definitions for various types of credentials generated by Amazon’s Secure Token Service (STS):

  • STSToken: type definition for Amazon STS session tokens
  • STSCredentials: type definition for Amazon STS temporary credentials
Module Attributes:
  • logger: logging object
class stslib.vault.STSCredentials(credentials)[source]

Bases: object

structure for temporary credentials generated by Amazon STS

add(new_credentials, token=None, overwrite=True)[source]

adds new credentials to the ring

index_credentials(creds)[source]
named_tuple(single_set)[source]

converts boto credentials into namedtuple format

request_ring(index=0)[source]

a facility for managing multiple session credentials gen at diff times

class stslib.vault.STSToken(token=None)[source]

Bases: object

structure for session tokens generated by Amazon STS

add(new_token, overwrite=True)[source]

adds a new token to the ring (FUTURE)

request_ring(index=None)[source]

token ring is a facility for managing multiple session tokens (FUTURE)

set(token)[source]

creates a new token object

class stslib.vault.STSingleSet(credential_set)[source]

Bases: object

Class definition of single credential object representing temporary credentials for a single iam role

set(single_set)[source]

Module Index


stslib.statics module

Summary:

stslib Project-level Defaults and Settings

NOTE: local defaults for your specific installation are derived from
settings found in ~/.stslib/config.yml
Module Attributes:
  • user_home (TYPE str):
    $HOME environment variable, present for most Unix and Unix-like POSIX systems
  • config_dirname (TYPE str):
    directory name default for stslib config files (.stslib)
  • config_path (TYPE str):
    default for stslib config files, includes config_dirname (~/.stslib)
  • sts_min (TYPE int):
    min Amazon STS temp credential lifetime (minutes)
  • sts_max (TYPE int):
    max Amazon STS temp credential lifetime (minutes)
  • token_life_default (TYPE int):
    Default valid lifetime for Amazon STS generated session tokens (minutes)
  • credential_life_default (TYPE int):
    Default valid lifetime for Amazon STS generated temp credentails (minutes)
  • awscli_creds (TYPE str):
    Path including filename to the default awscli credentials file
  • awscli_creds_alternate (TYPE str):
    Path including filename to the alternate default awscli credentials file
  • default_awscli (TYPE str):
    valid local location of the default awscli credentials file. Either awscli_creds or awscli_creds_alternate
  • default_output (TYPE str):
    default output file written to disk during refactoring operations
stslib.statics.read_local_config(cfg)[source]

Parses local config file for override values

Args:
local_file (str): filename of local config file
Returns:
dict of values contained in local config file

Module Index


stslib.local_config module

Summary:
local_config Module, creates local config file (yaml) to override default values set in statics module
Module Attributes:
  • config_file (TYPE str):
    Name of local config file, usually found in ~/.stslib dir
  • logger (TYPE logging obj):
    system logger, output set by log_mode project-level attribute
  • config_seed (TYPE str):
    yaml config file template used to seed local config file if none exists
class stslib.local_config.ReadConfig(local_file='')[source]

Bases: object

load(cfg='')[source]

returns object from yaml file

read(cfg='')[source]

reads values from local config file

class stslib.local_config.UpdateConfig(local_file)[source]

Bases: object

create(cfg, parameter_dict=None)[source]

create new config file

print_header(header)[source]

prints header strings to stdout

update(cfg)[source]

updates values in local config file

Module Index


stslib.seed module

Summary:
local yaml configuration file template
Args:
config_seed (str): file template
Returns:
None

Module Index


stslib.logd module

Project-level logging module

stslib.logd.getLogger(*args, **kwargs)[source]
Summary:
custom format logger
Args:
__version__: global var, project level log_mode: stream | file output format
Returns:
logger object | TYPE: logging

Module Index


( Table Of Contents )