示例#1
0
 def notify_approval_team(self, org_id, org_name):
     slack_msg = f"Organization with org_id {org_id} is submitted for approval"
     mail_template = get_org_approval_mail(org_id, org_name)
     utils.send_slack_notification(slack_msg=slack_msg, slack_url=SLACK_HOOK['hostname'] + SLACK_HOOK['path'],
                                   slack_channel=SLACK_CHANNEL_FOR_APPROVAL_TEAM)
     utils.send_email_notification([EMAILS["ORG_APPROVERS_DLIST"]], mail_template["subject"],
                                   mail_template["body"], NOTIFICATION_ARN, self.boto_utils)
 def notify_approval_team(self, service_id, service_name, org_id, org_name):
     slack_msg = f"Service {service_id} under org_id {org_id} is submitted for approval"
     utils.send_slack_notification(
         slack_msg=slack_msg,
         slack_url=SLACK_HOOK['hostname'] + SLACK_HOOK['path'],
         slack_channel=SLACK_CHANNEL_FOR_APPROVAL_TEAM)
     mail = get_service_approval_mail_template(service_id, service_name,
                                               org_id, org_name)
     send_email_notification([EMAILS["SERVICE_APPROVERS_DLIST"]],
                             mail["subject"], mail["body"],
                             NOTIFICATION_ARN, boto_util)
示例#3
0
 def handle_errors(cls, fun, **kwargs):
     """ Execute provided function, while handling all common errors, and returning a formatted response """
     # pylint: disable=too-many-return-statements
     try:
         return fun(**kwargs)
     except ApplicationException as exc:
         return exc.format_exception()
     # TODO: Can this disclose any information ? Should we provide generic response message ?
     except DataError as exc:
         return cls.format_exception(str(exc), 400)
     except InvalidArgumentException as exc:
         return cls.format_exception(str(exc), 400)
     except ReadOnlyModeException as exc:
         return cls.format_exception(str(exc), 503)
     except ApiStatusTimeoutException as exc:
         return cls.format_exception(str(exc), 408)
     except Exception:  # pylint: disable=broad-except
         send_slack_notification('ISE in manager\nEndpoint: {}\nAccount: {}\nkwargs: {}\n{}'
                                 .format(cls._endpoint_name, connexion.context['user'], kwargs, traceback.format_exc()))
         LOGGER.exception('Unhandled exception: ')
         return cls.format_exception('Internal server error', 500)
示例#4
0
def sync(tmpdirname, content_version, playbooks_version):  # pylint: disable=too-many-branches, too-many-statements
    """Sync from dirs function"""

    content_git = f"{tmpdirname}/{CONTENT_GIT_NAME}"
    playbooks_git = f"{tmpdirname}/{PLAYBOOKS_GIT_NAME}"
    securiry_rules_dir = '{}/content'.format(content_git)
    playbooks_dir = '{}/playbooks/security'.format(playbooks_git)
    for git_dir in (securiry_rules_dir, playbooks_dir):
        if not os.path.isdir(git_dir):
            LOGGER.error("%s directory does not exist", git_dir)
            return

    risk_map = resolution_risk_map(
        os.path.join(content_git, 'content/config.yaml'))
    impact_map = impact_string_map(
        os.path.join(content_git, 'content/config.yaml'))

    conn = get_conn()

    cves_names = {}

    # pylint: disable=too-many-nested-blocks
    for file_name in os.listdir(securiry_rules_dir):
        dir_name = '{}/{}'.format(securiry_rules_dir, file_name)
        if os.path.isdir(dir_name):
            try:
                with open(os.path.join(dir_name, 'plugin.yaml'),
                          'r') as stream:
                    plugin_info = yaml.safe_load(stream)

                to_import = {}
                all_keys_cves = set()
                for nested_file in os.listdir(dir_name):
                    full_nested_path = os.path.join(dir_name, nested_file)
                    if os.path.isdir(full_nested_path):
                        with open(
                                os.path.join(full_nested_path,
                                             'metadata.yaml'), 'r') as stream:
                            metadata = yaml.safe_load(stream)
                        rule_playbook_dir = os.path.join(
                            playbooks_dir, file_name, nested_file, 'rhel_host')
                        playbooks = []
                        if os.path.isdir(rule_playbook_dir):
                            for play in os.listdir(rule_playbook_dir):
                                if play.endswith('_fixit.yml'):
                                    with open(
                                            os.path.join(
                                                rule_playbook_dir,
                                                play)) as play_stream:
                                        playbooks.append({
                                            'play':
                                            play_stream.read(),
                                            'version':
                                            playbooks_version
                                        })
                        rule = {
                            'active':
                            metadata.get('status') == 'active',
                            'change_risk':
                            risk_map.get(metadata.get('resolution_risk'), 1),
                            'cves':
                            metadata.get('cves'),
                            'description':
                            plugin_info.get('name') + ': ' +
                            metadata.get('description'),
                            'id':
                            '{}|{}'.format(file_name, nested_file),
                            'kbase_node_id':
                            plugin_info.get('node_id')
                            if plugin_info.get('node_id') else None,
                            'playbook_count':
                            len(playbooks),
                            'playbooks':
                            playbooks,
                            'publish_date':
                            datetime.strptime(metadata['publish_date'],
                                              '%Y-%m-%d %H:%M:%S')
                            if 'publish_date' in metadata else None,
                            'reboot_required':
                            plugin_info.get('reboot_required'),
                            'rule_impact':
                            impact_map.get(metadata.get('severity'), 1)
                        }
                        for cve in metadata.get('cves'):
                            all_keys_cves.add(cve)

                        for info_file, attribute in [
                            ('summary.md', 'summary'), ('reason.md', 'reason'),
                            ('resolution.md', 'resolution'),
                            ('more_info.md', 'more_info')
                        ]:
                            if os.path.exists(
                                    os.path.join(full_nested_path, info_file)):
                                with open(
                                        os.path.join(full_nested_path,
                                                     info_file)) as file_desc:
                                    rule[attribute] = file_desc.read()
                            else:
                                with open(os.path.join(
                                        dir_name, info_file)) as file_desc:
                                    rule[attribute] = file_desc.read()
                        to_import[rule['id']] = rule

                # create overall rule only without errorkey to store pass data
                rule_only = {}
                is_any_active = reduce(
                    lambda was, rule: was if was else rule["active"],
                    list(to_import.values()), False)
                rule_only["active"] = is_any_active
                rule_only["cves"] = list(all_keys_cves)
                rule_only["id"] = file_name
                import_into_db(conn, to_import, {rule_only["id"]: rule_only})
                for cve in all_keys_cves:
                    if plugin_info.get('name') is not None:
                        cves_names[cve] = plugin_info.get('name')

            except Exception:  # pylint: disable=broad-except
                LOGGER.exception('Error during rule parsing: ')
                send_slack_notification('Error in rules_git_sync: {}'.format(
                    traceback.format_exc()))

    store_versions(conn, content_version, playbooks_version)
    import_cves_names(conn, cves_names)
    conn.close()
 def send_slack_message(self, slack_msg):
     slack_url = SLACK_HOOK['hostname'] + SLACK_HOOK['path']
     utils.send_slack_notification(
         slack_msg=slack_msg,
         slack_url=slack_url,
         slack_channel=SLACK_CHANNEL_FOR_APPROVAL_TEAM)