desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'alert when an IAM Object has a policy allowing \'iam:PassRole\'.
This allows the object to pass any role specified in the resource block to an ec2 instance.'
| def library_check_iamobj_has_iam_passrole(self, iamobj_item, policies_key='InlinePolicies', multiple_policies=True):
| tag = '{0} has iam:PassRole privileges.'.format(self.i_am_singular)
def check_statement(statement):
if (statement['Effect'] == 'Allow'):
if (('Action' in statement) and (type(statement['Action']) is list)):
for action in statement['Action']:
if (a... |
'alert when an IAM Object has a policy containing \'NotAction\'.
NotAction combined with an "Effect": "Allow" often provides more privilege
than is desired.'
| def library_check_iamobj_has_notaction(self, iamobj_item, policies_key='InlinePolicies', multiple_policies=True):
| tag = '{0} contains NotAction.'.format(self.i_am_singular)
def check_statement(statement):
if (statement['Effect'] == 'Allow'):
if ('NotAction' in statement):
self.add_issue(10, tag, iamobj_item, notes=json.dumps(statement['NotAction']))
if multiple_policies:
... |
'alert when an IAM Object has ec2:AuthorizeSecurityGroupEgress or ec2:AuthorizeSecurityGroupIngress.'
| def library_check_iamobj_has_security_group_permissions(self, iamobj_item, policies_key='InlinePolicies', multiple_policies=True):
| tag = '{0} can change security groups.'.format(self.i_am_singular)
def check_statement(statement):
if (statement['Effect'] == 'Allow'):
if (('Action' in statement) and (type(statement['Action']) is list)):
for action in statement['Action']:
if ... |
'alert when an IAM item (group, user or role) is attached to a managed policy with issues'
| def library_check_attached_managed_policies(self, iam_item, iam_type):
| mp_items = self.get_auditor_support_items(ManagedPolicy.index, iam_item.account)
managed_policies = iam_item.config.get('managed_policies', iam_item.config.get('ManagedPolicies'))
for item_mp in (managed_policies or []):
found = False
item_mp_arn = item_mp.get('arn', item_mp.get('Arn'))
... |
'alert when a cert\'s expiration is within 30 days'
| def check_upcoming_expiration(self, cert_item):
| expiration = cert_item.config.get('NotAfter', None)
if expiration:
expiration = parser.parse(expiration)
now = expiration.now(tzutc())
time_to_expiration = (expiration - now).days
if (0 <= time_to_expiration <= 30):
notes = 'Expires on {0}.'.format(str(expiratio... |
'alert when a cert\'s expiration is within 60 days'
| def check_future_expiration(self, cert_item):
| expiration = cert_item.config.get('NotAfter', None)
if expiration:
expiration = parser.parse(expiration)
now = expiration.now(tzutc())
time_to_expiration = (expiration - now).days
if (0 <= time_to_expiration <= 60):
notes = 'Expires on {0}.'.format(str(expiratio... |
'alert when a cert is expired'
| def check_expired(self, cert_item):
| expiration = cert_item.config.get('NotAfter', None)
if expiration:
expiration = parser.parse(expiration)
now = expiration.now(tzutc())
time_to_expiration = (expiration - now).days
if (time_to_expiration < 0):
notes = 'Expired on {0}.'.format(str(expiration))
... |
'alert when a VPN tunnel is not UP.'
| def check_tunnels(self, vpn_item):
| if vpn_item.config.get('tunnels'):
for tunnel in vpn_item.config.get('tunnels'):
if (tunnel.get('status') != 'UP'):
notes = '{} - {} - {}'.format(tunnel.get('outside_ip_address'), tunnel.get('status'), tunnel.get('status_message'))
self.add_issue(1, '{... |
'alert when flow logs are not enabled for VPC'
| def check_flow_logs_enabled(self, vpc_item):
| flow_log_items = self.get_watcher_support_items(FlowLog.index, vpc_item.account)
vpc_id = vpc_item.config.get('id')
tag = 'Flow Logs not enabled for VPC'
severity = 5
flow_logs_enabled = False
for flow_log in flow_log_items:
if (vpc_id == flow_log.config.get('resource_id')... |
'alert when an SES identity is not verified.'
| def check_verified(self, ses_item):
| if (not ses_item.config.get('verified')):
self.add_issue(1, 'SES Identity Not Verified.', ses_item)
|
'ALB SSL Policies are much simpler than ELB (classic) policies.
- Custom policies are not allowed.
- Try to use ELBSecurityPolicy-2016-08
- Alert on unknown policy or if using ELBSecurityPolicy-TLS-1-0-2015-04
- The ELBSecurityPolicy-2016-08 and ELBSecurityPolicy-2015-05 security policies for Application Load Balancers... | def check_ssl_policy(self, alb):
| supported_ssl_policies = set(['ELBSecurityPolicy-2016-08', 'ELBSecurityPolicy-TLS-1-2-2017-01', 'ELBSecurityPolicy-TLS-1-1-2017-01', 'ELBSecurityPolicy-2015-05', 'ELBSecurityPolicy-TLS-1-0-2015-04'])
for listener in alb.config.get('Listeners', []):
port = listener.get('Port')
ssl_policy = listen... |
'Starts the process of watchers -> auditors -> alerters'
| def run(self, account, interval=None):
| app.logger.info('Starting work on account {}.'.format(account))
time1 = time.time()
mons = self.get_monitors_to_run(account, interval)
watchers_with_changes = set()
for monitor in mons:
app.logger.info('Running slurp {} for {} ({} minutes interval)'.format(mo... |
'Return a list of (watcher, auditor) enabled for a specific account,
optionally filtered by interval time'
| def get_monitors_to_run(self, account, interval=None):
| mons = []
if interval:
for monitor in self.all_monitors:
if (monitor.watcher and (interval == monitor.watcher.get_interval())):
mons.append(monitor)
else:
mons = self.all_monitors
return mons
|
'Returns current intervals for watchers'
| def get_intervals(self, account):
| buckets = []
for monitor in self.all_monitors:
if monitor.watcher:
interval = monitor.watcher.get_interval()
if (interval not in buckets):
buckets.append(interval)
return buckets
|
'Returns the items that have changed if there are no changes in dependencies,
otherwise returns all slurped items for reauditing'
| def get_items_to_audit(self, watcher, auditor, watchers_with_changes):
| watcher.full_audit_list = None
if auditor.support_watcher_indexes:
for support_watcher_index in auditor.support_watcher_indexes:
if (support_watcher_index in watchers_with_changes):
app.logger.debug('Upstream watcher changed {}. reauditing {}'.format(support_wa... |
'Initializes the Watcher'
| def __init__(self, accounts=None, debug=False):
| self.datastore = datastore.Datastore()
if (not accounts):
accounts = Account.query.filter((Account.third_party == False)).filter((Account.active == True)).all()
else:
accounts = Account.query.filter((Account.third_party == False)).filter((Account.active == True)).filter(Account.name.in_(acco... |
'Should be run before slurp is run to grab the IgnoreList.'
| def prep_for_slurp(self):
| query = IgnoreListEntry.query
query = query.join((Technology, (Technology.id == IgnoreListEntry.tech_id)))
self.ignore_list = query.filter((Technology.name == self.index)).all()
|
'Should be run before batching slurps to set the current account (and region).
This will load the DB objects for account and technology for where we are currently at in the process.
:return:'
| def prep_for_batch_slurp(self):
| self.prep_for_slurp()
if (not self.current_account):
index = 0
technology = Technology.query.filter((Technology.name == self.index)).first()
if (not technology):
technology = Technology(name=self.index)
db.session.add(technology)
db.session.commit()
... |
'See if the given item has a name flagging it to be ignored by security_monkey.'
| def check_ignore_list(self, name):
| for result in self.ignore_list:
prefix = (result.prefix or '')
if name.lower().startswith(prefix.lower()):
app.logger.warn('Ignoring {}/{} because of IGNORELIST prefix {}'.format(self.index, name, result.prefix))
return True
return False
|
'Used by the Jinja templates
:returns: True if created_items is not empty
:returns: False otherwise.'
| def created(self):
| return (len(self.created_items) > 0)
|
'Used by the Jinja templates
:returns: True if deleted_items is not empty
:returns: False otherwise.'
| def deleted(self):
| return (len(self.deleted_items) > 0)
|
'Used by the Jinja templates
:returns: True if changed_items is not empty
:returns: False otherwise.'
| def changed(self):
| return (len(self.changed_items) > 0)
|
'This will fetch all the items in question that will need to get slurped.
This is used to know what we are going to have to batch up.
:return:'
| def slurp_list(self):
| raise NotImplementedError()
|
'method to slurp configuration from AWS for whatever it is that I\'m
interested in. This will be overridden for each technology.'
| def slurp(self):
| raise NotImplementedError()
|
'Logs any exceptions that happen in slurp and adds them to the exception_map
using their location as the key. The location is a tuple in the form:
(technology, account, region, item_name) that describes the object where the exception occurred.
Location can also exclude an item_name if the exception is region wide.'
| def slurp_exception(self, location=None, exception=None, exception_map={}, source='watcher'):
| if (location in exception_map):
app.logger.debug('Exception map already has location {}. This should not happen.'.format(location))
exception_map[location] = exception
app.logger.debug('Adding {} to the exceptions list. Exception was: {}'.format(loc... |
'Determines whether a given location is covered by an exception already in the
exception map.
Item location: (self.index, self.account, self.region, self.name)
exception Maps: (index, account, region, name)
(index, account, region)
(index, account)
:returns: True if location is covered by an entry in the exception map.... | def location_in_exception_map(self, item_location, exception_map={}):
| if (item_location in exception_map):
app.logger.debug('Skipping {} due to an item-level exception {}.'.format(item_location, exception_map[item_location]))
return True
if (item_location[0:3] in exception_map):
app.logger.debug('Skipping {} due to a reg... |
'Find any items that have been deleted since the last run of the watcher.
Add these items to the deleted_items list.'
| def find_deleted(self, previous=[], current=[], exception_map={}):
| prev_map = {item.location(): item for item in previous}
curr_map = {item.location(): item for item in current}
item_locations = list(set(prev_map).difference(set(curr_map)))
item_locations = [item_location for item_location in item_locations if (not self.location_in_exception_map(item_location, exceptio... |
'Find any new objects that have been created since the last run of the watcher.
Add these items to the created_items list.'
| def find_new(self, previous=[], current=[]):
| prev_map = {item.location(): item for item in previous}
curr_map = {item.location(): item for item in current}
item_locations = list(set(curr_map).difference(set(prev_map)))
list_new_items = [curr_map[item] for item in item_locations]
for item in list_new_items:
new_change_item = ChangeItem.... |
'Find any objects that have been changed since the last run of the watcher.
Add these items to the changed_items list.'
| def find_modified(self, previous=[], current=[], exception_map={}):
| prev_map = {item.location(): item for item in previous}
curr_map = {item.location(): item for item in current}
item_locations = list(set(curr_map).intersection(set(prev_map)))
item_locations = [item_location for item_location in item_locations if (not self.location_in_exception_map(item_location, except... |
'Identify changes between the configuration I have and what I had
last time the watcher ran.
This ignores any account/region which caused an exception during slurp.'
| def find_changes(self, current=None, exception_map=None):
| current = (current or [])
exception_map = (exception_map or {})
if (self.batched_size > 0):
return self.find_changes_batch(current, exception_map)
else:
prev = self.read_previous_items()
self.find_deleted(previous=prev, current=current, exception_map=exception_map)
self.f... |
'Pulls the last-recorded configuration from the database.
:return: List of all items for the given technology and the given account.'
| def read_previous_items(self):
| prev_list = []
for account in self.accounts:
prev = self.datastore.get_all_ctype_filtered(tech=self.index, account=account, include_inactive=False)
for item in prev:
item_revision = prev[item]
new_item = ChangeItem(index=self.index, region=item.region, account=item.accoun... |
'Note: It is intentional that self.ephemeral_items is not included here
so that emails will not go out about those changes.
Those changes will still be recorded in the database and visible in the UI.
:return: boolean whether or not we\'ve found any changes'
| def is_changed(self):
| return (self.deleted_items or self.created_items or self.changed_items)
|
'Runs through any changed items to see if any have issues.
:return: boolean whether any changed items have issues'
| def issues_found(self):
| has_issues = False
has_new_issue = False
has_unjustified_issue = False
for item in (self.created_items + self.changed_items):
if item.audit_issues:
has_issues = True
if item.found_new_issue:
has_new_issue = True
has_unjustified_issue = True... |
'save new configs, if necessary'
| def save(self):
| app.logger.info('{} deleted {} in {}'.format(len(self.deleted_items), self.i_am_plural, self.accounts))
app.logger.info('{} created {} in {}'.format(len(self.created_items), self.i_am_plural, self.accounts))
for item in (self.created_items + self.deleted_items):
item.save(sel... |
'Used for Jinja Template
:return: i_am_plural'
| def plural_name(self):
| return self.i_am_plural
|
'Used for Jinja Template
:return: i_am_singular'
| def singular_name(self):
| return self.i_am_singular
|
'Returns interval time (in minutes)'
| def get_interval(self):
| config = WatcherConfig.query.filter((WatcherConfig.index == self.index)).first()
if config:
return config.interval
return self.interval
|
'Returns active'
| def is_active(self):
| config = WatcherConfig.query.filter((WatcherConfig.index == self.index)).first()
if config:
return config.active
return self.active
|
'Returns whether ephemerals locations are ignored'
| def ephemerals_skipped(self):
| return self.honor_ephemerals
|
'Create ChangeItem from two separate items.
:return: An instance of ChangeItem'
| @classmethod
def from_items(cls, old_item=None, new_item=None):
| if ((not old_item) and (not new_item)):
return
valid_item = (new_item if new_item else old_item)
audit_issues = (old_item.audit_issues if old_item else [])
active = (True if new_item else False)
old_config = (old_item.config if old_item else {})
new_config = (new_item.config if new_item ... |
'Construct a location from the object.
:return: tuple containing index, account, region, and name.'
| def location(self):
| return (self.index, self.account, self.region, self.name)
|
'Provide an HTML description of the object for change emails and the Jinja templates.
:return: string of HTML describing the object.'
| def description(self):
| jenv = get_jinja_env()
template = jenv.get_template('jinja_change_item.html')
body = template.render(self._dict_for_template())
return body
|
'Save the item'
| def save(self, datastore, ephemeral=False):
| app.logger.debug('Saving {}/{}/{}/{}\n DCTB {}'.format(self.index, self.account, self.region, self.name, self.new_config))
self.db_item = datastore.store(self.index, self.region, self.account, self.name, self.active, self.new_config, arn=self.arn, new_issues=self.audit_issues, ephemeral=ephemeral)
|
'Adds a new issue to an item, if not already reported.
:return: The new issue'
| def add_issue(self, score, issue, item, notes=None):
| if (notes and (len(notes) > 1024)):
notes = notes[0:1024]
if (not self.override_scores):
query = ItemAuditScore.query.filter((ItemAuditScore.technology == self.index))
self.override_scores = query.all()
score = self._check_for_override_score(score, item.account)
for existing_issu... |
'To be overridden by child classes who
need a way to prepare for the next run.'
| def prep_for_audit(self):
| pass
|
'Inspect all of the auditor\'s items.'
| def audit_objects(self):
| app.logger.debug('Asked to audit {} Objects'.format(len(self.items)))
self.prep_for_audit()
self.current_support_items = {}
query = ItemAuditScore.query.filter((ItemAuditScore.technology == self.index))
self.override_scores = query.all()
methods = [getattr(self, method_name) for meth... |
'Determines whether this method has been marked as disabled based on Audit Issue Scores
settings.'
| def _is_current_method_disabled(self):
| for override_score in self.override_scores:
if (override_score.method == (((self.current_method_name + ' (') + self.__class__.__name__) + ')')):
return override_score.disabled
return False
|
'Pulls the last-recorded configuration from the database.
:return: List of all items for the given technology and the given account.'
| def read_previous_items(self):
| prev_list = []
for account in self.accounts:
prev = self.datastore.get_all_ctype_filtered(tech=self.index, account=account, include_inactive=False)
for item in prev:
item_revision = prev[item]
new_item = ChangeItem(index=self.index, region=item.region, account=item.accoun... |
'Pulls the last-recorded configuration from the database.
:return: List of all items for the given technology and the given account.'
| def read_previous_items_for_account(self, index, account):
| prev_list = []
prev = self.datastore.get_all_ctype_filtered(tech=index, account=account, include_inactive=False)
for item in prev:
item_revision = prev[item]
new_item = ChangeItem(index=self.index, region=item.region, account=item.account.name, name=item.name, arn=item.arn, new_config=item_r... |
'Save all new issues. Delete all fixed issues.'
| def save_issues(self):
| app.logger.debug('\n\nSaving Issues.')
db.session.rollback()
for item in self.items:
changes = False
loaded = False
if (not hasattr(item, 'db_item')):
loaded = True
item.db_item = self.datastore._get_item(item.index, item.region, item.account, item.name)
... |
'Given a report, send an email using SES.'
| def email_report(self, report):
| if (not report):
app.logger.info('No Audit issues. Not sending audit email.')
return
subject = 'Security Monkey {} Auditor Report'.format(self.i_am_singular)
send_email(subject=subject, recipients=self.emails, html=report)
|
'Using a Jinja template (jinja_audit_email.html), create a report that can be emailed.
:return: HTML - The output of the rendered template.'
| def create_report(self):
| jenv = get_jinja_env()
template = jenv.get_template('jinja_audit_email.html')
for item in self.items:
item.totalscore = 0
for issue in item.db_item.issues:
item.totalscore = (item.totalscore + issue.score)
sorted_list = sorted(self.items, key=(lambda item: item.totalscore))
... |
'Placeholder for custom auditors which may only want to run against
certain types of accounts'
| def applies_to_account(self, account):
| return True
|
'Checks to see if an AuditorSettings entry exists for each issue.
If it does not, one will be created with disabled set to false.'
| def _create_auditor_settings(self):
| app.logger.debug('Creating/Assigning Auditor Settings in account {} and tech {}'.format(self.accounts, self.index))
query = ItemAudit.query
query = query.join((Item, (Item.id == ItemAudit.item_id)))
query = query.join((Technology, (Technology.id == Item.tech_id)))
query = que... |
'Creates a new issue that is linked to an issue in a support auditor'
| def link_to_support_item_issues(self, item, sub_item, sub_issue_message=None, issue_message=None, issue=None, score=None):
| matching_issues = []
for sub_issue in sub_item.issues:
if ((not sub_issue_message) or (sub_issue.issue == sub_issue_message)):
matching_issues.append(sub_issue)
if (len(matching_issues) > 0):
for matching_issue in matching_issues:
if (issue is None):
i... |
'Creates a new issue that is linked a support watcher item'
| def link_to_support_item(self, score, issue_message, item, sub_item, issue=None):
| if (issue is None):
issue = self.add_issue(score, issue_message, item)
issue.sub_items.append(sub_item)
return issue
|
'Use by save_issue to generate a unique id for an item'
| def _item_list_string(self, issue):
| item_ids = []
for sub_item in issue.sub_items:
item_ids.append(sub_item.id)
item_ids.sort()
return str(item_ids)
|
'Return an override to the hard coded score for an issue being added. This could either
be a general override score for this check method or one that is specific to a particular
field in the account.
:param score: the hard coded score which will be returned back if there is
no applicable override
:param account: The ac... | def _check_for_override_score(self, score, account):
| for override_score in self.override_scores:
if (override_score.method == (((self.current_method_name + ' (') + self.__class__.__name__) + ')')):
account = get_account_by_name(account)
for account_pattern_score in override_score.account_pattern_scores:
if getattr(ac... |
'Add a parent to this role,
and add role itself to the parent\'s children set.
you should override this function if neccessary.'
| def add_parent(self, parent):
| parent.children.add(self)
self.parents.add(parent)
|
'Add parents to this role. Also should override if neccessary.
Example::
editor_of_articles = RoleMixin(\'editor_of_articles\')
editor_of_photonews = RoleMixin(\'editor_of_photonews\')
editor_of_all = RoleMixin(\'editor_of_all\')
editor_of_all.add_parents(editor_of_articles, editor_of_photonews)
:param parents: Parents... | def add_parents(self, *parents):
| for parent in parents:
self.add_parent(parent)
|
'A static method to return the role which has the input name.
:param name: The name of role.'
| @staticmethod
def get_by_name(name):
| return RBACRole.roles[name]
|
'Add allowing rules.
:param role: Role of this rule.
:param method: Method to allow in rule, include GET, POST, PUT etc.
:param resource: Resource also view function.
:param with_children: Allow role\'s children in rule as well
if with_children is `True`'
| def allow(self, role, method, resource, with_children=True):
| if with_children:
for r in role.get_children():
permission = (r.name, method, resource)
if (permission not in self._allowed):
self._allowed.append(permission)
permission = (role.name, method, resource)
if (permission not in self._allowed):
self._allowe... |
'Exempt a view function from being checked permission
:param view_func: The view function exempt from checking.'
| def exempt(self, view_func):
| if (not (view_func in self._exempt)):
self._exempt.append(view_func)
|
'Check whether role is allowed to access resource
:param role: Role to be checked.
:param method: Method to be checked.
:param resource: View function to be checked.'
| def is_allowed(self, role, method, resource):
| return ((role, method, resource) in self._allowed)
|
'Return whether view_func is exempted.
:param view_func: View function to be checked.'
| def is_exempt(self, view_func):
| return (view_func in self._exempt)
|
'Return whether the current user can access the resource.
Example::
@app.route(\'/some_url\', methods=[\'GET\', \'POST\'])
@rbac.allow([\'anonymous\'], [\'GET\'])
def a_view_func():
return Response(\'Blah Blah...\')
If you are not logged.
`rbac.has_permission(\'GET\', \'a_view_func\')` return True.
`rbac.has_permission... | def has_permission(self, method, endpoint, user=None):
| app = self.get_app()
_user = (user or current_user)
roles = _user.get_roles()
view_func = app.view_functions[endpoint]
return self._check_permission(roles, method, view_func)
|
'Decorator: allow roles to access the view func with it.
:param roles: List, each name of roles. Please note that,
`anonymous` is refered to anonymous.
If you add `anonymous` to the rule,
everyone can access the resource,
unless you deny other roles.
:param methods: List, each name of methods.
methods is valid in [\'GE... | def allow(self, roles, methods, with_children=True):
| def decorator(view_func):
_methods = [m.upper() for m in methods]
for (r, m, v) in itertools.product(roles, _methods, [view_func.__name__]):
self.before_acl.append((r, m, v, with_children))
return view_func
return decorator
|
'Decorator function
Exempt a view function from being checked permission.'
| def exempt(self, view_func):
| self.acl.exempt(view_func.__name__)
return view_func
|
'Helper to look up an app.'
| def get_app(self, reference_app=None):
| if (reference_app is not None):
return reference_app
if (self.app is not None):
return self.app
ctx = _app_ctx_stack.top
if (ctx is not None):
return ctx.app
raise RuntimeError('application not registered on rbac instance and no application bound ... |
'Returns the ephemeral paths for each technology.
Note: this data is also in the watcher for each technology.
It is mirrored here simply to assist in the security_monkey rearchitecture.
:param tech: str, name of technology
:return: list of ephemeral paths'
| def ephemeral_paths_for_tech(self, tech=None):
| ephemeral_paths = {'redshift': ['RestoreStatus', 'ClusterStatus', 'ClusterParameterGroups$ParameterApplyStatus', 'ClusterParameterGroups$ClusterParameterStatusList$ParameterApplyErrorDescription', 'ClusterParameterGroups$ClusterParameterStatusList$ParameterApplyStatus', 'ClusterRevisionNumber'], 'securitygroup': ['... |
'Remove all ephemeral paths from the item and return the hash of the new structure.
:param item: dictionary, representing an item tracked in security_monkey
:return: hash of the sorted json dump of the item with all ephemeral paths removed.'
| def durable_hash(self, item, ephemeral_paths):
| durable_item = deepcopy(item)
for path in ephemeral_paths:
try:
dpath.util.delete(durable_item, path, separator='$')
except PathNotFound:
pass
return self.hash_config(durable_item)
|
'Finds the hash for a config.
Calls sub_dict, which is a recursive method which sorts lists which may be buried in the structure.
Dumps the config to json with sort_keys set.
Grabs an MD5 hash.
:param config: dict describing item
:return: 32 character string (MD5 Hash)'
| def hash_config(self, config):
| item = sub_dict(config)
item_str = json.dumps(item, sort_keys=True)
item_hash = hashlib.md5(item_str)
return item_hash.hexdigest()
|
'Returns a list of Items joined with their most recent ItemRevision,
potentially filtered by the criteria above.'
| def get_all_ctype_filtered(self, tech=None, account=None, region=None, name=None, include_inactive=False):
| item_map = {}
query = Item.query
if tech:
query = query.join((Technology, (Item.tech_id == Technology.id))).filter((Technology.name == tech))
if account:
query = query.join((Account, (Item.account_id == Account.id))).filter((Account.name == account))
filter_by = {'region': region, 'n... |
'Returns a list of all revisions for the given item.'
| def get(self, ctype, region, account, name):
| item = self._get_item(ctype, region, account, name)
return item.revisions
|
'Returns a list of ItemAudit objects associated with a given Item.'
| def get_audit_issues(self, ctype, region, account, name):
| item = self._get_item(ctype, region, account, name)
return item.issues
|
'Saves an itemrevision. Create the item if it does not already exist.'
| def store(self, ctype, region, account, name, active_flag, config, arn=None, new_issues=[], ephemeral=False):
| item = self._get_item(ctype, region, account, name)
if arn:
duplicate_arns = Item.query.filter((Item.arn == arn)).all()
for duplicate_item in duplicate_arns:
if (duplicate_item.id != item.id):
duplicate_item.arn = None
app.logger.info('Moving ARN ... |
'Returns the first item with matching parameters.
Creates item if it doesn\'t exist.'
| def _get_item(self, technology, region, account, name):
| account_result = Account.query.filter((Account.name == account)).first()
if (not account_result):
raise Exception('Account with name [{}] not found.'.format(account))
item = Item.query.join((Technology, (Item.tech_id == Technology.id))).join((Account, (Item.account_id == Account.id)))... |
'Orders are always priced in USD'
| def buy(self, amount, price):
| local_currency_price = self.fc.convert(price, 'USD', self.currency)
logging.info(('Buy %f BTC at %f %s (%f USD) @%s' % (amount, local_currency_price, self.currency, price, self.name)))
self._buy(amount, local_currency_price)
|
'Orders are always priced in USD'
| def sell(self, amount, price):
| local_currency_price = self.fc.convert(price, 'USD', self.currency)
logging.info(('Sell %f BTC at %f %s (%f USD) @%s' % (amount, local_currency_price, self.currency, price, self.name)))
self._sell(amount, local_currency_price)
|
'Create a buy limit order'
| def _buy(self, amount, price):
| params = {'amount': amount, 'price': price}
response = self._send_request(self.buy_url, params)
if ('error' in response):
raise TradeException(response['error'])
|
'Create a sell limit order'
| def _sell(self, amount, price):
| params = {'amount': amount, 'price': price}
response = self._send_request(self.sell_url, params)
if ('error' in response):
raise TradeException(response['error'])
|
'Get balance'
| def get_info(self):
| response = self._send_request(self.balance_url)
if response:
self.btc_balance = float(response['btc_available'])
self.usd_balance = float(response['usd_available'])
|
'USD is used as pivot'
| def __init__(self):
| self.__dict__ = self.__shared_state
self.rates = {'USD': 1, 'EUR': 0.77, 'CNY': 6.15, 'SEK': 6.6}
self.update_delay = (60 * 60)
self.last_update = 0
self.bank_fee = 0.007
|
'Validates the given 1-based page number.'
| def validate_number(self, number):
| try:
number = int(number)
except ValueError:
raise PageNotAnInteger('That page number is not an integer')
if (number < 1):
raise EmptyPage('That page number is less than 1')
return number
|
'Returns a Page object for the given 1-based page number.'
| def page(self, number):
| number = self.validate_number(number)
bottom = ((number - 1) * self.per_page)
top = (bottom + self.per_page)
page_items = self.object_list[bottom:top]
if (not page_items):
if ((number == 1) and self.allow_empty_first_page):
pass
else:
raise EmptyPage('That ... |
'Returns the total number of objects, across all pages.'
| def _get_count(self):
| raise NotImplementedError
|
'Returns the total number of pages.'
| def _get_num_pages(self):
| raise NotImplementedError
|
'Returns a 1-based range of pages for iterating through within
a template for loop.'
| def _get_page_range(self):
| raise NotImplementedError
|
'Checks for one more item than last on this page.'
| def has_next(self):
| try:
next_item = self.paginator.object_list[(self.number * self.paginator.per_page)]
except IndexError:
return False
return True
|
'Returns the 1-based index of the last object on this page,
relative to total objects found (hits).'
| def end_index(self):
| return (((self.number - 1) * self.paginator.per_page) + len(self.object_list))
|
'Returns a Page object for the given 1-based page number.'
| def page(self, number):
| number = self.validate_number(number)
page_items = self.object_list[:self.per_page]
return FinitePage(page_items, number, self)
|
'Checks for one more item than last on this page.'
| def has_next(self):
| try:
next_item = self.paginator.object_list[self.paginator.per_page]
except IndexError:
return False
return True
|
'Returns the 1-based index of the first object on this page,
relative to total objects in the paginator.'
| def start_index(self):
| return self.paginator.offset
|
'Saves cracked access point key and info to a file.'
| def save_cracked(self, target):
| self.CRACKED_TARGETS.append(target)
with open('cracked.csv', 'wb') as csvfile:
targetwriter = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
for target in self.CRACKED_TARGETS:
targetwriter.writerow([target.bssid, target.encryption, target.ssid, target.k... |
'Loads info about cracked access points into list, returns list.'
| def load_cracked(self):
| result = []
if (not os.path.exists('cracked.csv')):
return result
with open('cracked.csv', 'rb') as csvfile:
targetreader = csv.reader(csvfile, delimiter=',', quotechar='"')
for row in targetreader:
t = Target(row[0], 0, 0, 0, row[1], row[2])
t.key = row[3]
... |
'Loads info about cracked access points into list, returns list.'
| def load_old_cracked(self):
| result = []
if (not os.path.exists('cracked.txt')):
return result
fin = open('cracked.txt', 'r')
lines = fin.read().split('\n')
fin.close()
for line in lines:
fields = line.split(chr(0))
if (len(fields) <= 3):
continue
tar = Target(fields[0], '', '', '... |
'We may exit the program at any time.
We want to remove the temp folder and any files contained within it.
Removes the temp files/folder and exists with error code "code".'
| def exit_gracefully(self, code=0):
| if os.path.exists(self.temp):
for f in os.listdir(self.temp):
os.remove(os.path.join(self.temp, f))
os.rmdir(self.temp)
self.RUN_ENGINE.disable_monitor_mode()
mac_change_back()
print (((GR + ' [+]') + W) + ' quitting')
print ''
exit(code)
|
'Handles command-line arguments, sets global variables.'
| def handle_args(self):
| set_encrypt = False
set_hscheck = False
set_wep = False
capfile = ''
opt_parser = self.build_opt_parser()
options = opt_parser.parse_args()
try:
if ((not set_encrypt) and (options.wpa or options.wep or options.wps)):
self.WPS_DISABLE = True
self.WPA_DISABLE = ... |
'Options are doubled for backwards compatability; will be removed soon and
fully moved to GNU-style'
| def build_opt_parser(self):
| option_parser = argparse.ArgumentParser()
command_group = option_parser.add_argument_group('COMMAND')
command_group.add_argument('--check', help='Check capfile [file] for handshakes.', action='store', dest='check')
command_group.add_argument('-check', action='store', dest='check', help=argpa... |
'Checks for new version, prompts to upgrade, then
replaces this script with the latest from the repo'
| def upgrade(self):
| try:
print ((((((GR + ' [!]') + W) + ' upgrading requires an ') + G) + 'internet connection') + W)
print (((GR + ' [+]') + W) + ' checking for latest version...')
revision = get_revision()
if (revision == (-1)):
print ((((R + ' [!]') + ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.