docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Return the offset aligned to the nearest greater given alignment Arguments: - `offset`: An integer - `alignment`: An integer
def align(offset, alignment): if offset % alignment == 0: return offset return offset + (alignment - (offset % alignment))
331,184
Constructor. Arguments: - `value`: A string description.
def __init__(self, value): super(BinaryParserException, self).__init__() self._value = value
331,188
Constructor. Arguments: - `buf`: Byte string containing stuff to parse. - `offset`: The offset into the buffer at which the block starts.
def __init__(self, buf, offset): self._buf = buf self._offset = offset self._implicit_offset = 0
331,190
Declaratively add fields to this block. This method will dynamically add corresponding offset and unpacker methods to this block. Arguments: - `type`: A string. Should be one of the unpack_* types. - `name`: A string. - `offset`: A number. - `length`: (Optional)...
def declare_field(self, type, name, offset=None, length=None): if offset is None: offset = self._implicit_offset if length is None: def no_length_handler(): f = getattr(self, "unpack_" + type) return f(offset) setattr(self, na...
331,191
Returns a little-endian unsigned byte from the relative offset. Arguments: - `offset`: The relative offset from the start of the block. Throws: - `OverrunBufferException`
def unpack_byte(self, offset): o = self._offset + offset try: return struct.unpack_from("<B", self._buf, o)[0] except struct.error: raise OverrunBufferException(o, len(self._buf))
331,192
Applies the little-endian WORD (2 bytes) to the relative offset. Arguments: - `offset`: The relative offset from the start of the block. - `word`: The data to apply.
def pack_word(self, offset, word): o = self._offset + offset return struct.pack_into("<H", self._buf, o, word)
331,193
Returns raw binary data from the relative offset with the given length. Arguments: - `offset`: The relative offset from the start of the block. - `length`: The length of the binary blob. If zero, the empty string zero length is returned. Throws: - `OverrunBufferExcept...
def unpack_binary(self, offset, length=False): if not length: return bytes("".encode("ascii")) o = self._offset + offset try: return bytes(struct.unpack_from("<{}s".format(length), self._buf, o)[0]) except struct.error: raise OverrunBufferExce...
331,194
Returns a string from the relative offset with the given length, where each character is a wchar (2 bytes) Arguments: - `offset`: The relative offset from the start of the block. - `length`: The length of the string. Throws: - `UnicodeDecodeError`
def unpack_wstring(self, offset, length): start = self._offset + offset end = self._offset + offset + 2 * length try: return bytes(self._buf[start:end]).decode("utf16") except AttributeError: # already a 'str' ? return bytes(self._buf[start:end]).decode(...
331,195
Returns a datetime from the DOSDATE and DOSTIME starting at the relative offset. Arguments: - `offset`: The relative offset from the start of the block. Throws: - `OverrunBufferException`
def unpack_dosdate(self, offset): try: o = self._offset + offset return dosdate(self._buf[o:o + 2], self._buf[o + 2:o + 4]) except struct.error: raise OverrunBufferException(o, len(self._buf))
331,196
Returns a datetime from the QWORD Windows SYSTEMTIME timestamp starting at the relative offset. See http://msdn.microsoft.com/en-us/library/ms724950%28VS.85%29.aspx Arguments: - `offset`: The relative offset from the start of the block. Throws: - `OverrunBufferExcepti...
def unpack_systemtime(self, offset): o = self._offset + offset try: parts = struct.unpack_from("<HHHHHHHH", self._buf, o) except struct.error: raise OverrunBufferException(o, len(self._buf)) return datetime(parts[0], parts[1], part...
331,197
Returns a string containing a GUID starting at the relative offset. Arguments: - `offset`: The relative offset from the start of the block. Throws: - `OverrunBufferException`
def unpack_guid(self, offset): o = self._offset + offset try: _bin = bytes(self._buf[o:o + 16]) except IndexError: raise OverrunBufferException(o, len(self._buf)) # Yeah, this is ugly h = [six.indexbytes(_bin, i) for i in range(len(_bin))] ...
331,198
escape the given string such that it can be placed in an XML attribute, like: <foo bar='$value'> Args: s (str): the string to escape. Returns: str: the escaped string.
def escape_attr(s): esc = xml.sax.saxutils.quoteattr(s) esc = esc.encode('ascii', 'xmlcharrefreplace').decode('ascii') esc = RESTRICTED_CHARS.sub('', esc) return esc
331,211
escape the given string such that it can be placed in an XML value location, like: <foo> $value </foo> Args: s (str): the string to escape. Returns: str: the escaped string.
def escape_value(s): esc = xml.sax.saxutils.escape(s) esc = esc.encode('ascii', 'xmlcharrefreplace').decode('ascii') esc = RESTRICTED_CHARS.sub('', esc) return esc
331,212
render the given root node using the given substitutions into XML. Args: root_node (e_nodes.RootNode): the node to render. subs (list[str]): the substitutions that maybe included in the XML. Returns: str: the rendered XML document.
def render_root_node_with_subs(root_node, subs): def rec(node, acc): if isinstance(node, e_nodes.EndOfStreamNode): pass # intended elif isinstance(node, e_nodes.OpenStartElementNode): acc.append("<") acc.append(node.tag_name()) for child in node....
331,213
Generate XML representations of the records in an EVTX chunk. Does not include the XML <?xml... header. Records are ordered by chunk.records() Args: chunk (Evtx.Chunk): the chunk to render. Yields: tuple[str, Evtx.Record]: the rendered XML document and the raw record.
def evtx_chunk_xml_view(chunk): for record in chunk.records(): record_str = evtx_record_xml_view(record) yield record_str, record
331,215
Generate XML representations of the records in an EVTX file. Does not include the XML <?xml... header. Records are ordered by file_header.chunks(), and then by chunk.records() Args: chunk (Evtx.FileHeader): the file header to render. Yields: tuple[str, Evtx.Record]: the rendered XML docum...
def evtx_file_xml_view(file_header): for chunk in file_header.chunks(): for record in chunk.records(): record_str = evtx_record_xml_view(record) yield record_str, record
331,216
Update the cache of all DNS entries and perform checks Args: *args: Optional list of arguments **kwargs: Optional list of keyword arguments Returns: None
def run(self, *args, **kwargs): try: zones = list(DNSZone.get_all().values()) buckets = {k.lower(): v for k, v in S3Bucket.get_all().items()} dists = list(CloudFrontDist.get_all().values()) ec2_public_ips = [x.public_ip for x in EC2Instance.get_all().valu...
331,256
Send notifications (email, slack, etc.) for any issues that are currently open or has just been closed Args: new_issues (`list` of :obj:`DomainHijackIssue`): List of newly discovered issues existing_issues (`list` of :obj:`DomainHijackIssue`): List of existing open issues fi...
def notify(self, new_issues, existing_issues, fixed_issues): if len(new_issues + existing_issues + fixed_issues) > 0: maxlen = max(len(x['properties']['source']) for x in (new_issues + existing_issues + fixed_issues)) + 2 text_tmpl = get_template('domain_hijacking.txt') ...
331,257
Removes the trailing AWS domain from a DNS record to return the resource name e.g bucketname.s3.amazonaws.com will return bucketname Args: record (str): DNS record resource_type: AWS Resource type (i.e. S3 Bucket, Elastic Beanstalk, etc..)
def return_resource_name(self, record, resource_type): try: if resource_type == 's3': regex = re.compile('.*(\.(?:s3-|s3){1}(?:.*)?\.amazonaws\.com)') bucket_name = record.replace(regex.match(record).group(1), '') return bucket_name e...
331,258
Returns a dict representation of the object Args: is_admin (`bool`): If true, include information about the account that should be avaiable only to admins Returns: `dict`
def to_json(self, is_admin=False): if is_admin: return { 'accountId': self.account_id, 'accountName': self.account_name, 'accountType': self.account_type, 'contacts': self.contacts, 'enabled': True if self.enabl...
331,272
Updates the object information based on live data, if there were any changes made. Any changes will be automatically applied to the object, but will not be automatically persisted. You must manually call `db.session.add(object)` on the object. Args: **kwargs (:obj:): AWS API Resourc...
def update(self, **kwargs): updated = False for prop in self.class_properties: key = prop['key'] kwarg_key = to_camelcase(key) if kwarg_key in kwargs: if prop['required'] and not kwargs[kwarg_key]: raise InquisitorError('M...
331,273
Returns the class object identified by `account_id` Args: account (`int`, `str`): Unique ID of the account to load from database Returns: `Account` object if found, else None
def get(account): account = Account.get(account) if not account: return None acct_type = AccountType.get(account.account_type_id).account_type account_class = get_plugin_by_name(PLUGIN_NAMESPACES['accounts'], acct_type) return account_class(account)
331,274
Returns a list of all accounts of a given type Args: include_disabled (`bool`): Include disabled accounts. Default: `True` Returns: list of account objects
def get_all(cls, include_disabled=True): if cls == BaseAccount: raise InquisitorError('get_all on BaseAccount is not supported') account_type_id = db.AccountType.find_one(account_type=cls.account_type).account_type_id qry = db.Account.order_by(desc(Account.enabled), Account...
331,276
Send a message to the `status_queue` to update a job's status. Returns `True` if the message was sent, else `False` Args: object_id (`str`): ID of the job that was executed status (:obj:`SchedulerStatus`): Status of the job Returns: `bool`
def send_status_message(self, object_id, status): try: body = json.dumps({ 'id': object_id, 'status': status }) self.status_queue.send_message( MessageBody=body, MessageGroupId='job_status', ...
331,285
Iterate through all AWS accounts and apply roles and policies from Github Args: *args: Optional list of arguments **kwargs: Optional list of keyword arguments Returns: `None`
def run(self, *args, **kwargs): accounts = list(AWSAccount.get_all(include_disabled=False).values()) self.manage_policies(accounts)
331,287
Returns a list of all the policies currently applied to an AWS Account. Returns a list containing all the policies for the specified scope Args: client (:obj:`boto3.session.Session`): A boto3 Session object scope (`str`): The policy scope to use. Default: Local Returns:...
def get_policies_from_aws(client, scope='Local'): done = False marker = None policies = [] while not done: if marker: response = client.list_policies(Marker=marker, Scope=scope) else: response = client.list_policies(Scope=...
331,292
Returns a list of all the roles for an account. Returns a list containing all the roles for the account. Args: client (:obj:`boto3.session.Session`): A boto3 Session object Returns: :obj:`list` of `dict`
def get_roles(client): done = False marker = None roles = [] while not done: if marker: response = client.list_roles(Marker=marker) else: response = client.list_roles() roles += response['Roles'] ...
331,293
Import templates from disk into database Reads all templates from disk and adds them to the database. By default, any template that has been modified by the user will not be updated. This can however be changed by setting `force` to `True`, which causes all templates to be imported regardless of status ...
def _import_templates(force=False): tmplpath = os.path.join(resource_filename('cloud_inquisitor', 'data'), 'templates') disk_templates = {f: os.path.join(root, f) for root, directory, files in os.walk(tmplpath) for f in files} db_templates = {tmpl.template_name: tmpl for tmpl in db.Template.find()} ...
331,307
Modifies the response object prior to sending it to the client. Used to add CORS headers to the request Args: response (response): Flask response object Returns: `None`
def after_request(response): response.headers.add('Access-Control-Allow-Origin', '*') response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization') response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE') return response
331,310
Register a given authentication system with the framework. Returns `True` if the `auth_system` is registered as the active auth system, else `False` Args: auth_system (:obj:`BaseAuthPlugin`): A subclass of the `BaseAuthPlugin` class to register Returns: `bool`
def register_auth_system(self, auth_system): auth_system_settings = dbconfig.get('auth_system') if auth_system.name not in auth_system_settings['available']: auth_system_settings['available'].append(auth_system.name) dbconfig.set('default', 'auth_system', DBCChoice(auth...
331,314
Registers a views menu items into the metadata for the application. Skip if the item is already present Args: items (`list` of `MenuItem`): A list of `MenuItem`s Returns: `None`
def register_menu_item(self, items): for itm in items: if itm.group in self.menu_items: # Only add the menu item if we don't already have it registered if itm not in self.menu_items[itm.group]['items']: self.menu_items[itm.group]['items']....
331,315
Iterates all entry points for views and auth systems and dynamically load and register the routes with Flask Args: app (`CINQFlask`): CINQFlask object to register views for Returns: `None`
def register_views(self, app): self.add_resource(LoginRedirectView, '/auth/login') self.add_resource(LogoutRedirectView, '/auth/logout') for entry_point in CINQ_PLUGINS['cloud_inquisitor.plugins.auth']['plugins']: cls = entry_point.load() app.available_auth_syst...
331,318
Helper function to interact with the CloudFlare API. Args: account (:obj:`CloudFlareAccount`): CloudFlare Account object path (`str`): URL endpoint to communicate with args (:obj:`dict` of `str`: `str`): A dictionary of arguments for the endpoint to consume Returns:...
def __cloudflare_request(self, *, account, path, args=None): if not args: args = {} if not self.cloudflare_initialized[account.account_id]: self.cloudflare_session[account.account_id] = requests.Session() self.cloudflare_session[account.account_id].headers.u...
331,327
Helper function to list all zones registered in the CloudFlare system. Returns a `list` of the zones Args: account (:obj:`CloudFlareAccount`): A CloudFlare Account object **kwargs (`dict`): Extra arguments to pass to the API endpoint Returns: `list` of `dict`
def __cloudflare_list_zones(self, *, account, **kwargs): done = False zones = [] page = 1 while not done: kwargs['page'] = page response = self.__cloudflare_request(account=account, path='/zones', args=kwargs) info = response['result_info'] ...
331,328
Helper function to list all records on a CloudFlare DNS Zone. Returns a `dict` containing the records and their information. Args: account (:obj:`CloudFlareAccount`): A CloudFlare Account object zoneID (`int`): Internal CloudFlare ID of the DNS zone **kwargs (`dict`)...
def __cloudflare_list_zone_records(self, *, account, zoneID, **kwargs): done = False records = {} page = 1 while not done: kwargs['page'] = page response = self.__cloudflare_request( account=account, path='/zones/{}/dns_re...
331,329
Entry point for the scheduler Args: *args: Optional arguments **kwargs: Optional keyword arguments Returns: None
def run(self, *args, **kwargs): accounts = list(AWSAccount.get_all(include_disabled=False).values()) # S3 Bucket config s3_acl = get_template('cloudtrail_s3_bucket_policy.json') s3_bucket_name = self.dbconfig.get('bucket_name', self.ns) s3_bucket_region = self.dbconfig....
331,330
Given a list of accounts, ensures that the SQS policy allows all the accounts to write to the queue Args: accounts (`list` of :obj:`Account`): List of accounts Returns: `None`
def validate_sqs_policy(self, accounts): sqs_queue_name = self.dbconfig.get('sqs_queue_name', self.ns) sqs_queue_region = self.dbconfig.get('sqs_queue_region', self.ns) sqs_account = AWSAccount.get(self.dbconfig.get('sqs_queue_account', self.ns)) session = get_aws_session(sqs_ac...
331,331
Creates an SNS topic if needed. Returns the ARN if the created SNS topic Args: region (str): Region name Returns: `str`
def create_sns_topic(self, region): sns = self.session.client('sns', region_name=region) self.log.info('Creating SNS topic for {}/{}'.format(self.account, region)) # Create the topic res = sns.create_topic(Name=self.topic_name) arn = res['TopicArn'] # Allow Clo...
331,335
Validates SQS subscription to the SNS topic. Returns `True` if subscribed or `False` if not subscribed or topic is missing Args: region (str): Name of AWS Region Returns: `bool`
def validate_sns_topic_subscription(self, region): sns = self.session.client('sns', region_name=region) arn = 'arn:aws:sns:{}:{}:{}'.format(region, self.account.account_number, self.topic_name) try: data = sns.list_subscriptions_by_topic(TopicArn=arn) except ClientEr...
331,336
Subscribe SQS to the SNS topic. Returns the ARN of the SNS Topic subscribed Args: region (`str`): Name of the AWS region Returns: `str`
def subscribe_sns_topic_to_sqs(self, region): sns = self.session.resource('sns', region_name=region) topic = sns.Topic('arn:aws:sns:{}:{}:{}'.format(region, self.account.account_number, self.topic_name)) topic.subscribe(Protocol='sqs', Endpoint=self.sqs_queue) auditlog( ...
331,337
Creates a new CloudTrail Trail Args: region (str): Name of the AWS region Returns: `None`
def create_cloudtrail(self, region): ct = self.session.client('cloudtrail', region_name=region) # Creating the sns topic for the trail prior to creation self.create_sns_topic(region) ct.create_trail( Name=self.trail_name, S3BucketName=self.bucket_name, ...
331,338
Enable SNS notifications for a Trail Args: region (`str`): Name of the AWS region trailName (`str`): Name of the CloudTrail Trail Returns: `None`
def enable_sns_notification(self, region, trailName): ct = self.session.client('cloudtrail', region_name=region) ct.update_trail(Name=trailName, SnsTopicName=self.topic_name) auditlog( event='cloudtrail.enable_sns_notification', actor=self.ns, data={...
331,339
Turn on logging for a CloudTrail Trail Args: region (`str`): Name of the AWS region name (`str`): Name of the CloudTrail Trail Returns: `None`
def start_logging(self, region, name): ct = self.session.client('cloudtrail', region_name=region) ct.start_logging(Name=name) auditlog( event='cloudtrail.start_logging', actor=self.ns, data={ 'account': self.account.account_name, ...
331,340
Sets the S3 prefix for a CloudTrail Trail Args: region (`str`): Name of the AWS region name (`str`): Name of the CloudTrail Trail Returns: `None`
def set_s3_prefix(self, region, name): ct = self.session.client('cloudtrail', region_name=region) ct.update_trail(Name=name, S3KeyPrefix=self.account.account_name) auditlog( event='cloudtrail.set_s3_prefix', actor=self.ns, data={ 'acc...
331,341
Sets the S3 bucket location for logfile delivery Args: region (`str`): Name of the AWS region name (`str`): Name of the CloudTrail Trail bucketName (`str`): Name of the S3 bucket to deliver log files to Returns: `None`
def set_s3_bucket(self, region, name, bucketName): ct = self.session.client('cloudtrail', region_name=region) ct.update_trail(Name=name, S3BucketName=bucketName) auditlog( event='cloudtrail.set_s3_bucket', actor=self.ns, data={ 'accou...
331,342
Creates the S3 bucket on the account specified as the destination account for log files Args: bucket_name (`str`): Name of the S3 bucket bucket_region (`str`): AWS Region for the bucket bucket_account (:obj:`Account`): Account to create the S3 bucket in template ...
def create_s3_bucket(cls, bucket_name, bucket_region, bucket_account, template): s3 = get_aws_session(bucket_account).client('s3', region_name=bucket_region) # Check to see if the bucket already exists and if we have access to it try: s3.head_bucket(Bucket=bucket_name) ...
331,343
Return the ARN of the IAM Role on the provided account as a string. Returns an `IAMRole` object from boto3 Args: account (:obj:`Account`): Account where to locate the role Returns: :obj:`IAMRole`
def confirm_iam_role(self, account): try: iam = self.session.client('iam') rolearn = iam.get_role(RoleName=self.role_name)['Role']['Arn'] return rolearn except ClientError as e: if e.response['Error']['Code'] == 'NoSuchEntity': se...
331,345
Create a new IAM role. Returns the ARN of the newly created role Args: account (:obj:`Account`): Account where to create the IAM role Returns: `str`
def create_iam_role(self, account): try: iam = self.session.client('iam') trust = get_template('vpc_flow_logs_iam_role_trust.json').render() policy = get_template('vpc_flow_logs_role_policy.json').render() newrole = iam.create_role( Path=...
331,346
Create a new CloudWatch log group based on the VPC Name if none exists. Returns `True` if succesful Args: account (:obj:`Account`): Account to create the log group in region (`str`): Region to create the log group in vpcname (`str`): Name of the VPC the log group is fow ...
def confirm_cw_log(self, account, region, vpcname): try: cw = self.session.client('logs', region) token = None log_groups = [] while True: result = cw.describe_log_groups() if not token else cw.describe_log_groups(nextToken=token) ...
331,347
Create a new VPC Flow log Args: account (:obj:`Account`): Account to create the flow in region (`str`): Region to create the flow in vpc_id (`str`): ID of the VPC to create the flow for iam_role_arn (`str`): ARN of the IAM role used to post logs to the log group ...
def create_vpc_flow_logs(self, account, region, vpc_id, iam_role_arn): try: flow = self.session.client('ec2', region) flow.create_flow_logs( ResourceIds=[vpc_id], ResourceType='VPC', TrafficType='ALL', LogGroupName=...
331,348
Returns a list of contacts for an issue Args: issue (:obj:`RequiredTagsIssue`): Issue record Returns: `list` of `dict`
def get_contacts(self, issue): # If the resources has been deleted, just return an empty list, to trigger issue deletion without notification if not issue.resource: return [] account_contacts = issue.resource.account.contacts try: resource_owners = issue...
331,362
Returns a list of actions to executed Args: issues (`list` of :obj:`RequiredTagsIssue`): List of issues Returns: `list` of `dict`
def get_actions(self, issues): actions = [] try: for issue in issues: action_item = self.determine_action(issue) if action_item['action'] != AuditActions.IGNORE: action_item['owners'] = self.get_contacts(issue) ...
331,363
Determine if we need to trigger an alert Args: action_schedule (`list`): A list contains the alert schedule issue_creation_time (`int`): Time we create the issue last_alert (`str`): Time we sent the last alert Returns: (`None` or `str`) None ...
def determine_alert(self, action_schedule, issue_creation_time, last_alert): issue_age = time.time() - issue_creation_time alert_schedule_lookup = {pytimeparse.parse(action_time): action_time for action_time in action_schedule} alert_schedule = sorted(alert_schedule_lookup.keys()) ...
331,364
Determine the action we should take for the issue Args: issue: Issue to determine action for Returns: `dict`
def determine_action(self, issue): resource_type = self.resource_types[issue.resource.resource_type_id] issue_alert_schedule = self.alert_schedule[resource_type] if \ resource_type in self.alert_schedule \ else self.alert_schedule['*'] action_item = { ...
331,365
Process the actions we want to take Args: actions (`list`): List of actions we want to take Returns: `list` of notifications
def process_actions(self, actions): notices = {} notification_contacts = {} for action in actions: resource = action['resource'] action_status = ActionStatus.SUCCEED try: if action['action'] == AuditActions.REMOVE: ...
331,366
Check whether a tag value is valid Args: key: A tag key value: A tag value Returns: `(True or False)` A boolean indicating whether or not the value is valid
def validate_tag(self, key, value): if key == 'owner': return validate_email(value, self.partial_owner_match) elif key == self.gdpr_tag: return value in self.gdpr_tag_values else: return True
331,367
Check whether a resource is compliance Args: resource: A single resource Returns: `(list, list)` A tuple contains missing tags (if there were any) and notes
def check_required_tags_compliance(self, resource): missing_tags = [] notes = [] resource_tags = {tag.key.lower(): tag.value for tag in resource.tags} # Do not audit this resource if it is not in the Account scope if resource.resource_type in self.alert_schedule: ...
331,368
Send notifications to the recipients provided Args: notices (:obj:`dict` of `str`: `list`): A dictionary mapping notification messages to the recipient. Returns: `None`
def notify(self, notices): tmpl_html = get_template('required_tags_notice.html') tmpl_text = get_template('required_tags_notice.txt') for recipient, data in list(notices.items()): body_html = tmpl_html.render(data=data) body_text = tmpl_text.render(data=data) ...
331,369
Return all Enforcements args: `account_id` : Unique Account Identifier `location` : Region associated with the Resource returns: list of enforcement objects
def get_all(cls, account_id=None, location=None): qry = db.Enforcements.filter() if account_id: qry = qry.filter(account_id == Enforcements.account_id) if location: qry = qry.join(Resource, Resource.location == location) return qry
331,373
Returns the IssueType object for `issue_type`. If no existing object was found, a new type will be created in the database and returned Args: issue_type (str,int,IssueType): Issue type name, id or class Returns: :obj:`IssueType`
def get(cls, issue_type): if isinstance(issue_type, str): obj = getattr(db, cls.__name__).find_one(cls.issue_type == issue_type) elif isinstance(issue_type, int): obj = getattr(db, cls.__name__).find_one(cls.issue_type_id == issue_type) elif isinstance(issue_ty...
331,375
Return issue by ID Args: issue_id (str): Unique Issue identifier issue_type_id (str): Type of issue to get Returns: :obj:`Issue`: Returns Issue object if found, else None
def get(issue_id, issue_type_id): return db.Issue.find_one( Issue.issue_id == issue_id, Issue.issue_type_id == issue_type_id )
331,377
Main execution point for the auditor Args: *args: **kwargs: Returns: `None`
def run(self, *args, **kwargs): self.log.debug('Starting EBSAuditor') data = self.update_data() notices = defaultdict(list) for account, issues in data.items(): for issue in issues: for recipient in account.contacts: notices[Notif...
331,381
Takes a dict of existing volumes missing tags and a dict of existing issues, and finds any new or updated issues. Args: volumes (:obj:`dict` of `str`: `EBSVolume`): Dict of current volumes with issues existing_issues (:obj:`dict` of `str`: `EBSVolumeAuditIssue`): Current list of...
def process_new_issues(self, volumes, existing_issues): new_issues = {} for issue_id, volume in volumes.items(): state = EBSIssueState.DETECTED.value if issue_id in existing_issues: issue = existing_issues[issue_id] data = { ...
331,384
Provided a list of volumes and existing issues, returns a list of fixed issues to be deleted Args: volumes (`dict`): A dictionary keyed on the issue id, with the :obj:`Volume` object as the value existing_issues (`dict`): A dictionary keyed on the issue id, with the :obj:`EBSVolumeAudit...
def process_fixed_issues(self, volumes, existing_issues): fixed_issues = [] for issue_id, issue in list(existing_issues.items()): if issue_id not in volumes: fixed_issues.append(issue) return fixed_issues
331,385
Send notifications to the users via. the provided methods Args: notices (:obj:`dict` of `str`: `dict`): List of the notifications to send Returns: `None`
def notify(self, notices): issues_html = get_template('unattached_ebs_volume.html') issues_text = get_template('unattached_ebs_volume.txt') for recipient, issues in list(notices.items()): if issues: message_html = issues_html.render(issues=issues) ...
331,386
Function to return a boto3 Session based on the account passed in the first argument. Args: account (:obj:`Account`): Account to create the session object for Returns: :obj:`boto3:boto3.session.Session`
def get_aws_session(account): from cloud_inquisitor.config import dbconfig from cloud_inquisitor.plugins.types.accounts import AWSAccount if not isinstance(account, AWSAccount): raise InquisitorError('Non AWSAccount passed to get_aws_session, got {}'.format(account.__class__.__name__)) # ...
331,400
Load a list of AWS regions from the AWS static data. Args: force (`bool`): Force fetch list of regions even if we already have a cached version Returns: :obj:`list` of `str`
def get_aws_regions(*, force=False): from cloud_inquisitor.config import dbconfig global __regions if force or not __regions: logger.debug('Loading list of AWS regions from static data') data = requests.get('https://ip-ranges.amazonaws.com/ip-ranges.json').json() rgx = re.compi...
331,401
Returns a dict containing the tags for a CloudFront distribution Args: client (botocore.client.CloudFront): Boto3 CloudFront client object arn (str): ARN of the distribution to get tags for Returns: `dict`
def __get_distribution_tags(self, client, arn): return { t['Key']: t['Value'] for t in client.list_tags_for_resource( Resource=arn )['Tags']['Items'] }
331,416
Return all resource records for a specific Route53 zone Args: zone_id (`str`): Name / ID of the hosted zone Returns: `dict`
def __fetch_route53_zone_records(self, zone_id): route53 = self.session.client('route53') done = False nextName = nextType = None records = {} try: while not done: if nextName and nextType: response = route53.list_resourc...
331,418
Return a dict with the tags for the zone Args: zone_id (`str`): ID of the hosted zone Returns: :obj:`dict` of `str`: `str`
def __fetch_route53_zone_tags(self, zone_id): route53 = self.session.client('route53') try: return { tag['Key']: tag['Value'] for tag in route53.list_tags_for_resource( ResourceType='hostedzone', ResourceId=zon...
331,419
Returns the last ten digits of the sha256 hash of the combined arguments. Useful for generating unique resource IDs Args: zone_name (`str`): The name of the DNS Zone the record belongs to record (`dict`): A record dict to generate the hash from Returns: `str...
def _get_resource_hash(zone_name, record): record_data = defaultdict(int, record) if type(record_data['GeoLocation']) == dict: record_data['GeoLocation'] = ":".join(["{}={}".format(k, v) for k, v in record_data['GeoLocation'].items()]) args = [ zone_name, ...
331,420
Returns datapoints from cloudwatch for bucket statistics. Args: bucket_name `(str)`: The name of the bucket statistic `(str)`: The statistic you want to fetch from days `(int)`: Sample period for the statistic
def _get_bucket_statistics(self, bucket_name, bucket_region, storage_type, statistic, days): cw = self.session.client('cloudwatch', region_name=bucket_region) # gather cw stats try: obj_stats = cw.get_metric_statistics( Namespace='AWS/S3', ...
331,421
Returns the ResourceType object for `resource_type`. If no existing object was found, a new type will be created in the database and returned Args: resource_type (str): Resource type name Returns: :obj:`ResourceType`
def get(cls, resource_type): if isinstance(resource_type, str): obj = getattr(db, cls.__name__).find_one(cls.resource_type == resource_type) elif isinstance(resource_type, int): obj = getattr(db, cls.__name__).find_one(cls.resource_type_id == resource_type) eli...
331,424
Return account by ID and type Args: account_id (`int`, `str`): Unique Account identifier account_type_id (str): Type of account to get Returns: :obj:`Account`: Returns an Account object if found, else None
def get(account_id, account_type_id=None): if type(account_id) == str: args = {'account_name': account_id} else: args = {'account_id': account_id} if account_type_id: args['account_type_id'] = account_type_id return db.Account.find_one(**arg...
331,442
Check if a user has access to view information for the account Args: user (:obj:`User`): User object to check Returns: True if user has access to the account, else false
def user_has_access(self, user): if ROLE_ADMIN in user.roles: return True # Non-admin users should only see active accounts if self.enabled: if not self.required_roles: return True for role in self.required_roles: if ...
331,443
Process an audit action for a resource, if possible Args: resource (:obj:`Resource`): A resource object to perform the action on action (`str`): Type of action to perform (`kill` or `stop`) action_issuer (`str`): The issuer of the action Returns: `ActionStatus`
def process_action(resource, action, action_issuer='unknown'): from cinq_collector_aws import AWSRegionCollector func_action = action_mapper[resource.resource_type][action] extra_info = {} action_status = ActionStatus.UNKNOWN if func_action: if action_mapper[resource.resource_type]['s...
331,458
Stop an EC2 Instance This function will attempt to stop a running instance. Args: client (:obj:`boto3.session.Session.client`): A boto3 client object resource (:obj:`Resource`): The resource object to stop Returns: `ActionStatus`
def stop_ec2_instance(client, resource): instance = EC2Instance.get(resource.id) if instance.state in ('stopped', 'terminated'): return ActionStatus.IGNORED, {} client.stop_instances(InstanceIds=[resource.id]) return ActionStatus.SUCCEED, {'instance_type': resource.instance_type, 'public_i...
331,459
Terminate an EC2 Instance This function will terminate an EC2 Instance. Args: client (:obj:`boto3.session.Session.client`): A boto3 client object resource (:obj:`Resource`): The resource object to terminate Returns: `ActionStatus`
def terminate_ec2_instance(client, resource): # TODO: Implement disabling of TerminationProtection instance = EC2Instance.get(resource.id) if instance.state == 'terminated': return ActionStatus.IGNORED, {} client.terminate_instances(InstanceIds=[resource.id]) return ActionStatus.SUCCEED...
331,460
Delete an S3 bucket This function will try to delete an S3 bucket Args: client (:obj:`boto3.session.Session.client`): A boto3 client object resource (:obj:`Resource`): The resource object to terminate Returns: `ActionStatus`
def delete_s3_bucket(client, resource): if dbconfig.get('enable_delete_s3_buckets', NS_AUDITOR_REQUIRED_TAGS, False): client.delete_bucket(Bucket=resource.id) return ActionStatus.SUCCEED, resource.metrics()
331,462
Returns the class object identified by `resource_id` Args: resource_id (str): Unique EC2 Instance ID to load from database Returns: EC2 Instance object if found, else None
def get(cls, resource_id): res = Resource.get(resource_id) return cls(res) if res else None
331,465
Return a named property for a resource, if available. Will raise an `AttributeError` if the property does not exist Args: name (str): Name of the property to return Returns: `ResourceProperty`
def get_property(self, name): for prop in self.resource.properties: if prop.name == name: return prop raise AttributeError(name)
331,470
Create or set the value of a property. Returns `True` if the property was created or updated, or `False` if there were no changes to the value of the property. Args: name (str): Name of the property to create or update value (any): Value of the property. This can be any type of ...
def set_property(self, name, value, update_session=True): if type(value) == datetime: value = value.isoformat() else: value = value try: prop = self.get_property(name) if prop.value == value: return False prop...
331,471
Return a tag by key, if found Args: key (str): Name/key of the tag to locate case_sensitive (bool): Should tag keys be treated case-sensitive (default: true) Returns: `Tag`,`None`
def get_tag(self, key, *, case_sensitive=True): key = key if case_sensitive else key.lower() for tag in self.resource.tags: if not case_sensitive: if tag.key.lower() == key: return tag elif key == tag.key: return tag ...
331,472
Create or set the value of the tag with `key` to `value`. Returns `True` if the tag was created or updated or `False` if there were no changes to be made. Args: key (str): Key of the tag value (str): Value of the tag update_session (bool): Automatically add the chang...
def set_tag(self, key, value, update_session=True): existing_tags = {x.key: x for x in self.tags} if key in existing_tags: tag = existing_tags[key] if tag.value == value: return False tag.value = value else: tag = Tag() ...
331,473
Removes a tag from a resource based on the tag key. Returns `True` if the tag was removed or `False` if the tag didn't exist Args: key (str): Key of the tag to delete update_session (bool): Automatically add the change to the SQLAlchemy session. Default: True Returns:
def delete_tag(self, key, update_session=True): existing_tags = {x.key: x for x in self.tags} if key in existing_tags: if update_session: db.session.delete(existing_tags[key]) self.tags.remove(existing_tags[key]) return True return F...
331,474
Save the resource to the database Args: auto_commit (bool): Automatically commit the transaction. Default: `False` Returns: `None`
def save(self, *, auto_commit=False): try: db.session.add(self.resource) if auto_commit: db.session.commit() except SQLAlchemyError as ex: self.log.exception('Failed updating resource: {}'.format(ex)) db.session.rollback()
331,475
Removes a resource from the database Args: auto_commit (bool): Automatically commit the transaction. Default: `False` Returns: `None`
def delete(self, *, auto_commit=False): try: db.session.delete(self.resource) if auto_commit: db.session.commit() except SQLAlchemyError: self.log.exception('Failed deleting resource: {}'.format(self.id)) db.session.rollback()
331,476
Updates the object information based on live data, if there were any changes made. Any changes will be automatically applied to the object, but will not be automatically persisted. You must manually call `db.session.add(instance)` on the object. Args: data (:obj:): AWS API Resource ...
def update(self, data): # If the instance was terminated, remove it if data.state['Name'] == 'terminated': self.delete(auto_commit=False) return True updated = self.set_property('launch_date', to_utc_date(data.launch_time).isoformat()) updated |= self.se...
331,479
Returns the name of an instance if existant, else return the instance id Args: with_id (bool): Include the instance ID even if the name is found (default: False) Returns: Name and/or instance ID of the instance object
def get_name_or_instance_id(self, with_id=False): name = self.get_tag('Name', case_sensitive=False) if name and len(name.value.strip()) > 0: return '{0} ({1})'.format(name.value, self.id) if with_id else name.value return self.id
331,480
Updates the object information based on live data, if there were any changes made. Any changes will be automatically applied to the object, but will not be automatically persisted. You must manually call `db.session.add(ami)` on the object. Args: data (bunch): Data fetched from AWS ...
def update(self, data): updated = self.set_property('description', data.description) updated |= self.set_property('state', data.state) tags = {x['Key']: x['Value'] for x in data.tags or {}} existing_tags = {x.key: x for x in self.tags} # Check for new tags for ...
331,484
Remove a DNSRecord Args: record (:obj:`DNSRecord`): :obj:`DNSRecord` to remove Returns: `None`
def delete_record(self, record): self.children.remove(record.resource) record.delete()
331,485
Take an event type argument and return a python logging format In order to properly format the syslog messages to current standard, load the template and perform necessary replacements and return the string. Args: event_type (str): Event type name Returns: `str`
def _get_syslog_format(event_type): syslog_format_template = get_template('syslog_format.json') fmt = syslog_format_template.render( event_type=event_type, host=dbconfig.get('instance_name', default='local') ) # Load and redump string, to get rid of any extraneous whitespaces r...
331,499
Generate and insert a new event Args: event (`str`): Action performed actor (`str`): Actor (user or subsystem) triggering the event data (`dict`): Any extra data necessary for describing the event level (`str` or `int`): Log level for the message. Uses standard python logging level ...
def auditlog(*, event, actor, data, level=logging.INFO): try: entry = AuditLog() entry.event = event entry.actor = actor entry.data = data db.session.add(entry) db.session.commit() _AUDIT_LOGGER.log( logging.getLevelName(level) if type(level...
331,501
Persist a record into the database Args: record (`logging.Record`): The logging.Record object to store Returns: `None`
def emit(self, record): # Skip records less than min_level if record.levelno < logging.getLevelName(self.min_level): return evt = LogEvent() evt.level = record.levelname evt.levelno = record.levelno evt.timestamp = datetime.fromtimestamp(record.creat...
331,502
Exports the object to a JSON friendly dict Args: include_body (bool): Include the body of the message in the output Returns: Dict representation of object type
def to_json(self, include_body=False): message = { 'emailId': self.email_id, 'timestamp': isoformat(self.timestamp), 'subsystem': self.subsystem, 'subject': self.subject, 'sender': self.sender, 'recipients': self.recipients, ...
331,505
Fetch an item by namespace and key Args: ns (str): Namespace prefix key (str): Item key Returns: :obj:`Configitem`: Returns config item object if found, else `None`
def get(cls, ns, key): return getattr(db, cls.__name__).find_one( ConfigItem.namespace_prefix == ns, ConfigItem.key == key )
331,507
Return object based on JSON / dict input Args: data (dict): Dictionary containing a serialized Role object Returns: :obj:`Role`: Role object representing the data
def from_json(cls, data): role = cls() role.role_id = data['roleId'] role.name = data['name'] role.color = data['color'] return role
331,509
Map roles for user in database Args: user (User): User to add roles to roles ([Role]): List of roles to add Returns: None
def add_role(user, roles): def _add_role(role): user_role = UserRole() user_role.user_id = user.user_id user_role.role_id = role.role_id db.session.add(user_role) db.session.commit() [_add_role(role) for role in roles]
331,511
Return object based on JSON / dict input Args: data (dict): Dictionary containing a serialized User object Returns: :obj:`User`: User object representing the data
def from_json(cls, data): user = cls() user.user_id = data['userId'] user.username = data['username'] user.auth_system = data['authSystem'] user.roles = data['roles'] return user
331,512
Generate and insert a new event Args: event (str): Action performed actor (str): Actor (user or subsystem) triggering the event data (dict): Any extra data necessary for describing the event Returns: `None`
def log(cls, event=None, actor=None, data=None): from cloud_inquisitor.log import auditlog auditlog(event=event, actor=actor, data=data)
331,514