示例#1
0
    def mitigation_policy(self, mp_path):
        """Populate Mitigation Policies"""

        print("[*] Populating Mitigation Policies...")
        if mp_path:
            mp_list = glob.glob(mp_path + '*.yml')
        else:
            mp_dir = ATCconfig.get('mitigation_policies_directory')
            mp_list = glob.glob(mp_dir + '/*.yml')

        for mp_file in mp_list:
            try:
                mp = MitigationPolicy(mp_file, apipath=self.apipath,
                               auth=self.auth, space=self.space)
                mp.render_template("confluence")
                confluence_data = {
                    "title": mp.mp_parsed_file["title"],
                    "spacekey": self.space,
                    "parentid": str(ATCutils.confluence_get_page_id(
                        self.apipath, self.auth, self.space,
                        "Mitigation Policies")),
                    "confluencecontent": mp.content,
                }

                res = ATCutils.push_to_confluence(confluence_data, self.apipath,
                                            self.auth)
                if res == 'Page updated':
            	    print("==> updated page: MP '" + mp.mp_parsed_file['title'] + "'")
            except Exception as err:
                print(mp_file + " failed")
                print("Err message: %s" % err)
                print('-' * 60)
                traceback.print_exc(file=sys.stdout)
                print('-' * 60)
        print("[+] Mitigation Policies populated!")
示例#2
0
    def hardening_policy(self, hp_path):
        """Populate Hardening Policies"""

        print("[*] Populating Hardening Policies...")
        if hp_path:
            hp_list = glob.glob(hp_path + '*.yml')
        else:
            hp_dir = ATCconfig.get('hardening_policies_directory')
            hp_list = glob.glob(hp_dir + '/*.yml')

        for hp_file in hp_list:
            try:
                hp = HardeningPolicy(hp_file)
                hp.render_template("confluence")
                confluence_data = {
                    "title": hp.hp_parsed_file["title"],
                    "spacekey": self.space,
                    "parentid": str(ATCutils.confluence_get_page_id(
                        self.apipath, self.auth, self.space,
                        "Hardening Policies")),
                    "confluencecontent": hp.content,
                }

                res = ATCutils.push_to_confluence(confluence_data, self.apipath,
                                            self.auth)
                if res == 'Page updated':
            	    print("==> updated page: HP '" + hp.hp_parsed_file['title'] + "'")
            except Exception as err:
                print(hp_file + " failed")
                print("Err message: %s" % err)
                print('-' * 60)
                traceback.print_exc(file=sys.stdout)
                print('-' * 60)
        print("[+] Hardening Policies populated!")
示例#3
0
    def detection_rule(self, dr_path):
        """Desc"""

        print("[*] Populating Detection Rules...")
        if dr_path:
            dr_list = glob.glob(dr_path + '*.yml')
        else:
            dr_dirs = ATCconfig.get('detection_rules_directories')
            # check if config provides multiple directories for detection rules
            if isinstance(dr_dirs, list):
                dr_list = []
                for directory in dr_dirs:
                    dr_list += glob.glob(directory + '/*.yml')
            elif isinstance(dr_dirs, str):
                dr_list = glob.glob(dr_dirs + '/*.yml')

        for dr_file in dr_list:
            try:
                dr = DetectionRule(dr_file,
                                   apipath=self.apipath,
                                   auth=self.auth,
                                   space=self.space)
                dr.render_template("confluence")

                confluence_data = {
                    "title":
                    dr.fields['title'],
                    "spacekey":
                    self.space,
                    "parentid":
                    str(
                        ATCutils.confluence_get_page_id(
                            self.apipath, self.auth, self.space,
                            "Detection Rules")),
                    "confluencecontent":
                    dr.content,
                }

                res = ATCutils.push_to_confluence(confluence_data,
                                                  self.apipath, self.auth)
                if res == 'Page updated':
                    print("==> updated page: DR '" + dr.fields['title'] +
                          "' (" + dr_file + ")")
                # print("Done: ", dr.fields['title'])
            except Exception as err:
                print(dr_file + " failed")
                print("Err message: %s" % err)
                print('-' * 60)
                traceback.print_exc(file=sys.stdout)
                print('-' * 60)
        print("[+] Detection Rules populated!")
示例#4
0
    def enrichment(self, en_path):
        """Nothing here yet"""

        print("[*] Populating Enrichments...")
        if en_path:
            en_list = glob.glob(en_path + '*.yml')
        else:
            en_dir = ATCconfig.get('enrichments_directory')
            en_list = glob.glob(en_dir + '/*.yml')

        for en_file in en_list:
            try:
                en = Enrichment(en_file,
                                apipath=self.apipath,
                                auth=self.auth,
                                space=self.space)
                en.render_template("confluence")

                confluence_data = {
                    "title":
                    en.en_parsed_file['title'],
                    "spacekey":
                    self.space,
                    "parentid":
                    str(
                        ATCutils.confluence_get_page_id(
                            self.apipath, self.auth, self.space,
                            "Enrichments")),
                    "confluencecontent":
                    en.content,
                }

                res = ATCutils.push_to_confluence(confluence_data,
                                                  self.apipath, self.auth)
                if res == 'Page updated':
                    print("==> updated page: EN '" +
                          en.en_parsed_file['title'] + "'")
                # print("Done: ", en.en_parsed_file['title'])
            except Exception as err:
                print(en_file + " failed")
                print("Err message: %s" % err)
                print('-' * 60)
                traceback.print_exc(file=sys.stdout)
                print('-' * 60)
        print("[+] Enrichments populated!")
示例#5
0
    def data_needed(self, dn_path):
        """Desc"""

        print("[*] Populating Data Needed...")
        if dn_path:
            dn_list = glob.glob(dn_path + '*.yml')
        else:
            dn_dir = ATCconfig.get('data_needed_dir')
            dn_list = glob.glob(dn_dir + '/*.yml')

        for dn_file in dn_list:
            try:
                dn = DataNeeded(dn_file,
                                apipath=self.apipath,
                                auth=self.auth,
                                space=self.space)
                dn.render_template("confluence")
                confluence_data = {
                    "title":
                    dn.dn_fields["title"],
                    "spacekey":
                    self.space,
                    "parentid":
                    str(
                        ATCutils.confluence_get_page_id(
                            self.apipath, self.auth, self.space,
                            "Data Needed")),
                    "confluencecontent":
                    dn.content,
                }

                res = ATCutils.push_to_confluence(confluence_data,
                                                  self.apipath, self.auth)
                if res == 'Page updated':
                    print("==> updated page: DN '" + dn.dn_fields['title'] +
                          "'")
                # print("Done: ", dn.dn_fields['title'])
            except Exception as err:
                print(dn_file + " failed")
                print("Err message: %s" % err)
                print('-' * 60)
                traceback.print_exc(file=sys.stdout)
                print('-' * 60)
        print("[+] Data Needed populated!")
示例#6
0
    def usecases(self, uc_path):
        """Nothing here yet"""

        print("[+] Populating UseCases...")
        if uc_path:
            uc_list = glob.glob(uc_path + '*.yml')
        else:
            uc_dir = ATCconfig.get('usecases_directory')
            uc_list = glob.glob(uc_dir + '/*.yml')

        for uc_file in uc_list:
            try:
                uc = Usecase(uc_file,
                             apipath=self.apipath,
                             auth=self.auth,
                             space=self.space)
                uc.render_template("confluence")

                confluence_data = {
                    "title":
                    uc.title,
                    "spacekey":
                    self.space,
                    "parentid":
                    str(
                        ATCutils.confluence_get_page_id(
                            self.apipath, self.auth, self.space, "Use Cases")),
                    "confluencecontent":
                    uc.content
                }

                res = ATCutils.push_to_confluence(confluence_data,
                                                  self.apipath, self.auth)
                if res == 'Page updated':
                    print("==> updated page: UC '" + uc.usecase_name + "'")
                # print("Done: ", cu.title)
            except Exception as err:
                print(uc_file + " failed")
                print("Err message: %s" % err)
                print('-' * 60)
                traceback.print_exc(file=sys.stdout)
                print('-' * 60)
        print("[+] UseCases populated!")
示例#7
0
    def customer(self, cu_path):
        """Nothing here yet"""

        print("[+] Populating Customers...")
        if cu_path:
            cu_list = glob.glob(cu_path + '*.yml')
        else:
            cu_dir = ATCconfig.get('customers_directory')
            cu_list = glob.glob(cu_dir + '/*.yml')

        for cu_file in cu_list:
            try:
                cu = Customer(cu_file,
                              apipath=self.apipath,
                              auth=self.auth,
                              space=self.space)
                cu.render_template("confluence")

                confluence_data = {
                    "title":
                    cu.customer_name,
                    "spacekey":
                    self.space,
                    "parentid":
                    str(
                        ATCutils.confluence_get_page_id(
                            self.apipath, self.auth, self.space, "Customers")),
                    "confluencecontent":
                    cu.content
                }

                res = ATCutils.push_to_confluence(confluence_data,
                                                  self.apipath, self.auth)
                if res == 'Page updated':
                    print("==> updated page: CU '" + cu.customer_name + "'")
                # print("Done: ", cu.title)
            except Exception as err:
                print(cu_file + " failed")
                print("Err message: %s" % err)
                print('-' * 60)
                traceback.print_exc(file=sys.stdout)
                print('-' * 60)
        print("[+] Customers populated!")
示例#8
0
    def triggers(self, tg_path):
        """Populate Triggers"""

        print("[*] Populating Triggers...")
        if tg_path:
            tg_list = glob.glob(tg_path + '*.yml')
        else:
            tg_list = glob.glob(
                ATCconfig.get("triggers_directory") + '/T*/*.yaml')

        for tg_file in tg_list:
            try:
                tg = Triggers(tg_file)
                tg.render_template("confluence")
                title = tg.fields["attack_technique"] + ": " + \
                    te_mapping.get(tg.fields["attack_technique"])
                confluence_data = {
                    "title":
                    title,
                    "spacekey":
                    self.space,
                    "parentid":
                    str(
                        ATCutils.confluence_get_page_id(
                            self.apipath, self.auth, self.space, "Triggers")),
                    "confluencecontent":
                    tg.content,
                }

                res = ATCutils.push_to_confluence(confluence_data,
                                                  self.apipath, self.auth)
                if res == 'Page updated':
                    print("==> updated page: TR '" + title + "'")
                # print("Done: ", tg.fields["attack_technique"])
            except Exception as err:
                print(tg_file + " failed")
                print("Err message: %s" % err)
                print('-' * 60)
                traceback.print_exc(file=sys.stdout)
                print('-' * 60)

        print("[+] Triggers populated!")
示例#9
0
    def logging_policy(self, lp_path):
        """Desc"""

        print("[*] Populating Logging Policies...")
        if lp_path:
            lp_list = glob.glob(lp_path + '*.yml')
        else:
            lp_dir = ATCconfig.get('logging_policies_dir')
            lp_list = glob.glob(lp_dir + '/*.yml')

        for lp_file in lp_list:
            try:
                lp = LoggingPolicy(lp_file)
                lp.render_template("confluence")
                confluence_data = {
                    "title":
                    lp.fields["title"],
                    "spacekey":
                    self.space,
                    "parentid":
                    str(
                        ATCutils.confluence_get_page_id(
                            self.apipath, self.auth, self.space,
                            "Logging Policies")),
                    "confluencecontent":
                    lp.content,
                }

                res = ATCutils.push_to_confluence(confluence_data,
                                                  self.apipath, self.auth)
                if res == 'Page updated':
                    print("==> updated page: LP '" + lp.fields['title'] + "'")
                # print("Done: ", lp.fields['title'])
            except Exception as err:
                print(lp_file + " failed")
                print("Err message: %s" % err)
                print('-' * 60)
                traceback.print_exc(file=sys.stdout)
                print('-' * 60)
        print("[+] Logging Policies populated!")
    def render_template(self, template_type):
        """Render template with data in it
        template_type:
            - "markdown"
            - "confluence"
        """

        if template_type not in ["markdown", "confluence"]:
            raise Exception(
                "Bad template_type. Available values: " +
                "[\"markdown\", \"confluence\"]")

        # Get proper template
        if template_type == "markdown":
            template = env.get_template(
                'markdown_alert_template.md.j2')

            # Read raw sigma rule
            sigma_rule = ATCutils.read_rule_file(self.yaml_file)

            # Put raw sigma rule into fields var
            self.fields.update({'sigma_rule': sigma_rule})

            # Define which queries we want from Sigma
            #queries = ["es-qs", "xpack-watcher", "graylog", "splunk", "logpoint", "grep", "fieldlist"]
            queries = ATCconfig.get('detection_queries').split(",")

            # dict to store query key + query values
            det_queries = {}

            # Convert sigma rule into queries (for instance, graylog query)
            for query in queries:
                # prepare command to execute from shell
                # (yes, we know)
                if query == "powershell":
                    cmd = ATCconfig.get('sigmac_path') + " -t " + query + \
                        " --config  " + ATCconfig.get('powershell_sigma_config') + \
                        " --ignore-backend-errors " + self.yaml_file
                elif query == "es-qs":
                    cmd = ATCconfig.get('sigmac_path') + " -t " + query + \
                        " --config  " + ATCconfig.get('es-qs_sigma_config') + \
                        " --ignore-backend-errors " + self.yaml_file
                elif query == "xpack-watcher":
                    cmd = ATCconfig.get('sigmac_path') + " -t " + query + \
                        " --config  " + ATCconfig.get('xpack-watcher_sigma_config') + \
                        " --ignore-backend-errors " + self.yaml_file
                elif query == "splunk":
                    cmd = ATCconfig.get('sigmac_path') + " -t " + query + \
                        " --config  " + ATCconfig.get('splunk_sigma_config') + \
                        " --ignore-backend-errors " + self.yaml_file
                elif query == "logpoint":
                    cmd = ATCconfig.get('sigmac_path') + " -t " + query + \
                        " --config  " + ATCconfig.get('logpoint_sigma_config') + \
                        " --ignore-backend-errors " + self.yaml_file
                else:
                    cmd = ATCconfig.get('sigmac_path') + ' --shoot-yourself-in-the-foot -t "' + \
                        query + '" --ignore-backend-errors "' + self.yaml_file + '"'
                        #query + " --ignore-backend-errors " + self.yaml_file + \
                        #" 2> /dev/null"
                
                #p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
                query2 = subprocess.getoutput(cmd)

                # Wait for date to terminate. Get return returncode
                # p_status = p.wait()
                #p.wait()

                """ Had to remove '-' due to problems with
                Jinja2 variable naming,
                e.g es-qs throws error 'no es variable'
                """
                det_queries[query] = str(query2)#[2:-3]

            # Update detection rules
            self.fields.update({"det_queries": det_queries})
            self.fields.update({"queries": queries})

            # Data Needed
            data_needed = ATCutils.main_dn_calculatoin_func(self.yaml_file)

            # if there is only 1 element in the list, print it as a string,
            # without quotes
            # if isistance(data_needed, list) and len(data_needed) == 1:
            #     [data_needed] = data_needed

            # print("%s || Dataneeded: \n%s\n" %
            #       (self.fields.get("title"), data_needed))

            self.fields.update({'data_needed': sorted(data_needed)})

            # Enrichments
            enrichments = self.fields.get("enrichment")

            if isinstance(enrichments, str):
                enrichments = [enrichments]

            self.fields.update({'enrichment': enrichments})

            # MITRE ATT&CK Tactics and Techniques
            tactic = []
            tactic_re = re.compile(r'attack\.\w\D+$')
            technique = []
            technique_re = re.compile(r'(?:attack\.t\d{4}$|attack\.t\d{4}\.\d{3}$)')
            # AM!TT Tactics and Techniques
            amitt_tactic = []
            amitt_tactic_re = re.compile(r'amitt\.\w\D+$')
            amitt_technique = []
            amitt_technique_re = re.compile(r'amitt\.t\d{1,5}$')

            other_tags = []

            if self.fields.get('tags'):
                for tag in self.fields.get('tags'):
                    if tactic_re.match(tag):
                        if ta_mapping.get(tag):
                            tactic.append(ta_mapping.get(tag))
                        else:
                            other_tags.append(tag)
                    elif amitt_tactic_re.match(tag):
                        if amitt_tactic_mapping.get(tag):
                            amitt_tactic.append(amitt_tactic_mapping.get(tag))
                        else:
                            other_tags.append(tag)
                    elif technique_re.match(tag):
                        te = tag.upper()[7:]
                        technique.append((te_mapping.get(te), te))
                    elif amitt_technique_re.match(tag):
                        te = tag.upper()[6:]
                        amitt_technique.append((amitt_technique_mapping.get(te), te))
                    else:
                        other_tags.append(tag)

                if len(tactic):
                    self.fields.update({'tactics': tactic})
                if len(technique):
                    self.fields.update({'techniques': technique})
                if len(amitt_tactic):
                    self.fields.update({'amitt_tactics': amitt_tactic})
                if len(amitt_technique):
                    self.fields.update({'amitt_techniques': amitt_technique})
                if len(other_tags):
                    self.fields.update({'other_tags': other_tags})

            triggers = []

            for trigger in technique:
                if trigger is "None":
                    continue
                trigger_name, trigger_id = trigger
                # Check if a directory for a technique exists in atomic red team repo
                if os.path.isdir(ATCconfig.get('triggers_directory') + '/' + trigger_id):
                    triggers.append(trigger)

                else:
                    print(trigger_id + ": No atomics trigger for this technique")
                    """
                    triggers.append(
                        trigger + ": No atomics trigger for this technique"
                    )
                    """

            self.fields.update(
                {'description': self.fields.get('description').strip()})
            self.fields.update({'triggers': triggers})

        elif template_type == "confluence":
            template = env.get_template(
                'confluence_alert_template.html.j2')

            self.fields.update(
                {'confluence_viewpage_url': ATCconfig.get('confluence_viewpage_url')})

            sigma_rule = ATCutils.read_rule_file(self.yaml_file)
            self.fields.update({'sigma_rule': sigma_rule})

            #outputs = ["es-qs", "xpack-watcher", "graylog"]

            queries = ATCconfig.get('detection_queries').split(",")

            # dict to store query key + query values
            det_queries = {}

            for output in queries:
                if output == "powershell":
                    cmd = ATCconfig.get('sigmac_path') + " -t " + output + \
                        " --config  " + ATCconfig.get('powershell_sigma_config') + \
                        " --ignore-backend-errors " + self.yaml_file
                elif output == "es-qs":
                    cmd = ATCconfig.get('sigmac_path') + " -t " + output + \
                        " --config  " + ATCconfig.get('es-qs_sigma_config') + \
                        " --ignore-backend-errors " + self.yaml_file
                elif output == "xpack-watcher":
                    cmd = ATCconfig.get('sigmac_path') + " -t " + output + \
                        " --config  " + ATCconfig.get('xpack-watcher_sigma_config') + \
                        " --ignore-backend-errors " + self.yaml_file
                elif output == "splunk":
                    cmd = ATCconfig.get('sigmac_path') + " -t " + output + \
                        " --config  " + ATCconfig.get('splunk_sigma_config') + \
                        " --ignore-backend-errors " + self.yaml_file
                elif output == "logpoint":
                    cmd = ATCconfig.get('sigmac_path') + " -t " + output + \
                        " --config  " + ATCconfig.get('logpoint_sigma_config') + \
                        " --ignore-backend-errors " + self.yaml_file
                else:
                    cmd = ATCconfig.get('sigmac_path') + ' --shoot-yourself-in-the-foot -t "' + \
                        output + '" --ignore-backend-errors "' + self.yaml_file + '"'

                p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
                (query, err) = p.communicate()
                # Wait for date to terminate. Get return returncode ##
                # p_status = p.wait()
                p.wait()
                # have to remove '-' due to problems with
                # Jinja2 variable naming,e.g es-qs throws error
                # 'no es variable'
                #self.fields.update({output.replace("-", ""): str(query)[2:-3]})
                det_queries[output] = str(query)[2:-3].replace("\\n", "\n")
                
            # Update detection rules
            self.fields.update({"det_queries": det_queries})
            self.fields.update({"queries": queries})

            # Data Needed
            data_needed = ATCutils.main_dn_calculatoin_func(self.yaml_file)

            data_needed_with_id = []

            for data in sorted(data_needed):
                data_needed_id = str(ATCutils.confluence_get_page_id(
                    self.apipath, self.auth, self.space, data))
                data = (data, data_needed_id)
                data_needed_with_id.append(data)

            self.fields.update({'data_needed': data_needed_with_id})

            # Enrichments
            enrichments = self.fields.get("enrichment")

            enrichments_with_page_id = []

            if isinstance(enrichments, str):
                enrichments = [enrichments]

            if enrichments:
                for enrichment_name in enrichments:
                    enrichment_page_id = str(ATCutils.confluence_get_page_id(
                        self.apipath, self.auth, self.space, enrichment_name))
                    enrichment_data = (enrichment_name, enrichment_page_id)
                    enrichments_with_page_id.append(enrichment_data)

            self.fields.update({'enrichment': enrichments_with_page_id})

            # MITRE ATT&CK Tactics and Techniques
            tactic = []
            tactic_re = re.compile(r'attack\.\w\D+$')
            technique = []
            technique_re = re.compile(r'attack\.t\d{1,5}(\.\d{3})?$')
            # AM!TT Tactics and Techniques
            amitt_tactic = []
            amitt_tactic_re = re.compile(r'amitt\.\w\D+$')
            amitt_technique = []
            amitt_technique_re = re.compile(r'amitt\.t\d{1,5}$')

            other_tags = []

            if self.fields.get('tags'):
                for tag in self.fields.get('tags'):
                    if tactic_re.match(tag):
                        if ta_mapping.get(tag):
                            tactic.append(ta_mapping.get(tag))
                        else:
                            other_tags.append(tag)
                    elif amitt_tactic_re.match(tag):
                        if amitt_tactic_mapping.get(tag):
                            amitt_tactic.append(amitt_tactic_mapping.get(tag))
                        else:
                            other_tags.append(tag)
                    elif technique_re.match(tag):
                        te = tag.upper()[7:]
                        technique.append((te_mapping.get(te), te))
                    elif amitt_technique_re.match(tag):
                        te = tag.upper()[6:]
                        amitt_technique.append((amitt_technique_mapping.get(te), te))
                    else:
                        other_tags.append(tag)

                if len(tactic):
                    self.fields.update({'tactics': tactic})
                if len(technique):
                    self.fields.update({'techniques': technique})
                if len(amitt_tactic):
                    self.fields.update({'amitt_tactics': amitt_tactic})
                if len(technique):
                    self.fields.update({'amitt_techniques': amitt_technique})
                if len(other_tags):
                    self.fields.update({'other_tags': other_tags})

            triggers = []

            for trigger_name, trigger_id in technique:
                if trigger_id is "None":
                    continue


                try:
                    page_name = trigger_id + ": " + trigger_name
                    trigger_page_id = str(ATCutils.confluence_get_page_id(
                        self.apipath, self.auth, self.space, page_name))

                    trigger = (trigger_name, trigger_id, trigger_page_id)

                    triggers.append(trigger)
                except FileNotFoundError:
                    print(trigger + ": No atomics trigger for this technique")

            self.fields.update({'triggers': triggers})

        self.content = template.render(self.fields)
        # Need to convert ampersand into HTML "save" format
        # Otherwise confluence throws an error
        # self.content = self.content.replace("&", "&")
        # Done in the template itself

        return True
示例#11
0
    def render_template(self, template_type):
        """Description
        template_type:
            - "markdown"
            - "confluence"
        """

        if template_type not in ["markdown", "confluence"]:
            raise Exception("Bad template_type. Available values:" +
                            " [\"markdown\", \"confluence\"]")

        # Get proper template
        if template_type == "markdown":
            template = env.get_template('markdown_enrichments_template.md.j2')

            self.en_parsed_file.update({
                'description':
                self.en_parsed_file.get('description').strip()
            })
        elif template_type == "confluence":
            template = env.get_template(
                'confluence_enrichments_template.html.j2')

            self.en_parsed_file.update({
                'confluence_viewpage_url':
                ATCconfig.get('confluence_viewpage_url')
            })

            data_needed = self.en_parsed_file.get('data_needed')
            if data_needed:
                data_needed_with_id = []
                for dn in data_needed:
                    data_needed_id = str(
                        ATCutils.confluence_get_page_id(
                            self.apipath, self.auth, self.space, dn))
                    dn = (dn, data_needed_id)
                    data_needed_with_id.append(dn)

                self.en_parsed_file.update(
                    {'data_needed': data_needed_with_id})

            data_to_enrich = self.en_parsed_file.get('data_to_enrich')
            if data_to_enrich:
                data_to_enrich_with_id = []
                for de in data_to_enrich:
                    data_to_enrich_id = str(
                        ATCutils.confluence_get_page_id(
                            self.apipath, self.auth, self.space, de))
                    de = (de, data_to_enrich_id)
                    data_to_enrich_with_id.append(de)

                self.en_parsed_file.update(
                    {'data_to_enrich': data_to_enrich_with_id})

            requirements = self.en_parsed_file.get('requirements')
            if requirements:
                requirements_with_id = []
                for req in requirements:
                    requirements_id = str(
                        ATCutils.confluence_get_page_id(
                            self.apipath, self.auth, self.space, req))
                    req = (req, requirements_id)
                    requirements_with_id.append(req)

                self.en_parsed_file.update(
                    {'requirements': requirements_with_id})

            self.en_parsed_file.update({
                'description':
                self.en_parsed_file.get('description').strip()
            })
        # Render
        self.content = template.render(self.en_parsed_file)
示例#12
0
    def render_template(self, template_type):
        """Description
        template_type:
            - "markdown"
            - "confluence"
        """

        if template_type not in ["markdown", "confluence"]:
            raise Exception("Bad template_type. Available values:" +
                            " [\"markdown\", \"confluence\"]")

        # Get proper template
        if template_type == "markdown":
            template = env.get_template(
                'markdown_mitigationpolicies_template.md.j2')

            platform = self.mp_parsed_file.get("platform")

            if isinstance(platform, str):
                platform = [platform]

            self.mp_parsed_file.update({'platform': platform})

            minimum_version = self.mp_parsed_file.get("minimum_version")

            if isinstance(minimum_version, str):
                minimum_version = [minimum_version]

            self.mp_parsed_file.update({'minimum_version': minimum_version})

            mitigation_systems = self.mp_parsed_file.get("mitigation_system")

            if isinstance(mitigation_systems, str):
                mitigation_systems = [mitigation_systems]

            self.mp_parsed_file.update(
                {'mitigation_system': mitigation_systems})

            self.mp_parsed_file.update({
                'configuration':
                self.mp_parsed_file.get('configuration').strip()
            })
            self.mp_parsed_file.update({
                'description':
                self.mp_parsed_file.get('description').strip()
            })

            # MITRE ATT&CK Tactics and Techniques
            tactic = []
            tactic_re = re.compile(r'attack\.\w\D+$')
            technique = []
            technique_re = re.compile(r'attack\.t\d{1,5}$')
            # AM!TT Tactics and Techniques
            amitt_tactic = []
            amitt_tactic_re = re.compile(r'amitt\.\w\D+$')
            amitt_technique = []
            amitt_technique_re = re.compile(r'amitt\.t\d{1,5}$')

            # MITRE ATT&CK Mitigation
            mitigation = []
            mitigation_re = re.compile(r'attack\.m\d{1,5}$')
            # AM!TT Mitigation
            amitt_mitigation = []
            amitt_mitigation_re = re.compile(r'amitt\.m\d{1,5}$')

            other_tags = []

            if self.mp_parsed_file.get('tags'):
                for tag in self.mp_parsed_file.get('tags'):
                    if tactic_re.match(tag):
                        if ta_mapping.get(tag):
                            tactic.append(ta_mapping.get(tag))
                        else:
                            other_tags.append(tag)
                    elif amitt_tactic_re.match(tag):
                        if amitt_tactic_mapping.get(tag):
                            amitt_tactic.append(amitt_tactic_mapping.get(tag))
                        else:
                            other_tags.append(tag)
                    elif technique_re.match(tag):
                        te = tag.upper()[7:]
                        technique.append((te_mapping.get(te), te))
                    elif amitt_technique_re.match(tag):
                        te = tag.upper()[6:]
                        technique.append((amitt_technique_mapping.get(te), te))
                    elif mitigation_re.match(tag):
                        mi = tag.upper()[7:]
                        mitigation.append((mi_mapping.get(mi), mi))
                    elif amitt_mitigation_re.match(tag):
                        te = tag.upper()[6:]
                        mitigation.append(
                            (amitt_mitigation_mapping.get(te), te))
                    else:
                        other_tags.append(tag)

                    if not tactic_re.match(tag) and not \
                            technique_re.match(tag) and not \
                            mitigation_re.match(tag):
                        other_tags.append(tag)

                if len(tactic):
                    self.mp_parsed_file.update({'tactics': tactic})
                if len(technique):
                    self.mp_parsed_file.update({'techniques': technique})
                if len(amitt_tactic):
                    self.mp_parsed_file.update({'amitt_tactics': amitt_tactic})
                if len(amitt_technique):
                    self.mp_parsed_file.update(
                        {'amitt_techniques': amitt_technique})
                if len(mitigation):
                    self.mp_parsed_file.update({'mitigations': mitigation})
                if len(amitt_mitigation):
                    self.mp_parsed_file.update(
                        {'amitt_mitigations': amitt_mitigation})
                if len(other_tags):
                    self.mp_parsed_file.update({'other_tags': other_tags})

        elif template_type == "confluence":
            template = env.get_template(
                'confluence_mitigationpolicies_template.html.j2')

            self.mp_parsed_file.update({
                'confluence_viewpage_url':
                ATCconfig.get('confluence_viewpage_url')
            })

            self.mp_parsed_file.update({
                'description':
                self.mp_parsed_file.get('description').strip()
            })

            platform = self.mp_parsed_file.get("platform")

            if isinstance(platform, str):
                platform = [platform]

            self.mp_parsed_file.update({'platform': platform})

            minimum_version = self.mp_parsed_file.get("minimum_version")

            if isinstance(minimum_version, str):
                minimum_version = [minimum_version]

            self.mp_parsed_file.update({'minimum_version': minimum_version})

            mitigation_systems = self.mp_parsed_file.get("mitigation_system")

            if isinstance(mitigation_systems, str):
                mitigation_systems = [mitigation_systems]

            if not mitigation_systems:
                mitigation_systems = [
                    "None",
                ]

            mitigation_systems_with_id = []

            if mitigation_systems:
                for ms in mitigation_systems:
                    mitigation_systems_id = str(
                        ATCutils.confluence_get_page_id(
                            self.apipath, self.auth, self.space, ms))
                    ms = (ms, mitigation_systems_id)
                    mitigation_systems_with_id.append(ms)

            self.mp_parsed_file.update(
                {'mitigation_system': mitigation_systems_with_id})

            # MITRE ATT&CK Tactics and Techniques
            tactic = []
            tactic_re = re.compile(r'attack\.\w\D+$')
            technique = []
            technique_re = re.compile(r'attack\.t\d{1,5}$')
            # AM!TT Tactics and Techniques
            amitt_tactic = []
            amitt_tactic_re = re.compile(r'amitt\.\w\D+$')
            amitt_technique = []
            amitt_technique_re = re.compile(r'amitt\.t\d{1,5}$')

            # MITRE ATT&CK Mitigation
            mitigation = []
            mitigation_re = re.compile(r'attack\.m\d{1,5}$')
            # AM!TT Mitigation
            amitt_mitigation = []
            amitt_mitigation_re = re.compile(r'amitt\.m\d{1,5}$')

            other_tags = []

            if self.mp_parsed_file.get('tags'):
                for tag in self.mp_parsed_file.get('tags'):
                    if tactic_re.match(tag):
                        if ta_mapping.get(tag):
                            tactic.append(ta_mapping.get(tag))
                        else:
                            other_tags.append(tag)
                    elif amitt_tactic_re.match(tag):
                        if amitt_tactic_mapping.get(tag):
                            amitt_tactic.append(amitt_tactic_mapping.get(tag))
                        else:
                            other_tags.append(tag)
                    elif technique_re.match(tag):
                        te = tag.upper()[7:]
                        technique.append((te_mapping.get(te), te))
                    elif amitt_technique_re.match(tag):
                        te = tag.upper()[6:]
                        technique.append((amitt_technique_mapping.get(te), te))
                    elif mitigation_re.match(tag):
                        mi = tag.upper()[7:]
                        mitigation.append((mi_mapping.get(mi), mi))
                    elif amitt_mitigation_re.match(tag):
                        te = tag.upper()[6:]
                        mitigation.append(
                            (amitt_mitigation_mapping.get(te), te))
                    else:
                        other_tags.append(tag)

                    if not tactic_re.match(tag) and not \
                           technique_re.match(tag) and not \
                           mitigation_re.match(tag):
                        other_tags.append(tag)

                if len(tactic):
                    self.mp_parsed_file.update({'tactics': tactic})
                if len(technique):
                    self.mp_parsed_file.update({'techniques': technique})
                if len(amitt_tactic):
                    self.mp_parsed_file.update({'amitt_tactics': amitt_tactic})
                if len(amitt_technique):
                    self.mp_parsed_file.update(
                        {'amitt_techniques': amitt_technique})
                if len(mitigation):
                    self.mp_parsed_file.update({'mitigations': mitigation})
                if len(amitt_mitigation):
                    self.mp_parsed_file.update(
                        {'amitt_mitigations': amitt_mitigation})
                if len(other_tags):
                    self.mp_parsed_file.update({'other_tags': other_tags})

        # Render
        self.content = template.render(self.mp_parsed_file)
示例#13
0
    def render_template(self, template_type):
        """Render template with data in it
        template_type:
            - "markdown"
            - "confluence"
        """

        if template_type not in ["markdown", "confluence"]:
            raise Exception("Bad template_type. Available values: " +
                            "[\"markdown\", \"confluence\"]")

        self.cu_fields.update({'description': self.description.strip()})

        # Transform variables to arrays if not provided correctly in yaml

        if isinstance(self.data_needed, str):
            self.cu_fields.update({'dataneeded': [self.data_needed]})

        if isinstance(self.logging_policies, str):
            self.cu_fields.update({'loggingpolicy': [self.logging_policies]})

        detectionrule_with_path = []

        for title in self.detection_rules:
            if title is not None:
                name = rules_by_title.get(title)[1]
            else:
                name = ''
            dr = (title, name)
            detectionrule_with_path.append(dr)

        self.cu_fields.update({'detectionrule': detectionrule_with_path})

        # Get proper template
        if template_type == "markdown":
            template = env\
                .get_template('markdown_customer_template.md.j2')

        elif template_type == "confluence":
            template = env.get_template('confluence_customer_template.html.j2')

            self.cu_fields.update({
                'confluence_viewpage_url':
                ATCconfig.get('confluence_viewpage_url')
            })

            if not self.logging_policies:
                self.logging_policies = [
                    "None",
                ]

            logging_policies_with_id = []

            for lp in self.logging_policies:
                if lp != "None" and self.apipath and self.auth and self.space:
                    logging_policies_id = str(
                        ATCutils.confluence_get_page_id(
                            self.apipath, self.auth, self.space, lp))
                else:
                    logging_policies_id = ""
                lp = (lp, logging_policies_id)
                logging_policies_with_id.append(lp)

            self.cu_fields.update({'loggingpolicy': logging_policies_with_id})

            if not self.data_needed:
                self.data_needed = [
                    "None",
                ]

            data_needed_with_id = []

            for dn in self.data_needed:
                if dn != "None" and self.apipath and self.auth and self.space:
                    data_needed_id = str(
                        ATCutils.confluence_get_page_id(
                            self.apipath, self.auth, self.space, dn))
                else:
                    data_needed_id = ""
                dn = (dn, data_needed_id)
                data_needed_with_id.append(dn)

            self.cu_fields.update({'data_needed': data_needed_with_id})

            detection_rules_with_id = []

            for dn in self.detection_rules:
                if dn != "None" and self.apipath and self.auth and self.space:
                    detection_rules_id = str(
                        ATCutils.confluence_get_page_id(
                            self.apipath, self.auth, self.space, dn))
                else:
                    detection_rules_id = ""
                dn = (dn, detection_rules_id)
                detection_rules_with_id.append(dn)

            self.cu_fields.update({'detectionrule': detection_rules_with_id})

        self.content = template.render(self.cu_fields)

        return True
示例#14
0
    def render_template(self, template_type):
        """Description
        template_type:
            - "markdown"
            - "confluence"
        """

        if template_type not in ["markdown", "confluence"]:
            raise Exception("Bad template_type. Available values:" +
                            " [\"markdown\", \"confluence\"]")

        # Get proper template
        if template_type == "markdown":
            template = env\
                .get_template('markdown_dataneeded_template.md.j2')

            logging_policies = self.dn_fields.get("loggingpolicy")

            if isinstance(logging_policies, str):
                logging_policies = [logging_policies]

            self.dn_fields.update({'loggingpolicy': logging_policies})

            mitigation_policy = self.dn_fields.get("mitigation_policy")

            if isinstance(mitigation_policy, str):
                mitigation_policy = [mitigation_policy]

            self.dn_fields.update({'mitigation_policy': mitigation_policy})

            self.dn_fields.update(
                {'description': self.dn_fields.get('description').strip()})

            refs = self.dn_fields.get("references")

            if isinstance(refs, str):
                self.dn_fields.update({'references': [refs]})

        elif template_type == "confluence":
            template = env\
                .get_template('confluence_dataneeded_template.html.j2')

            self.dn_fields.update({
                'confluence_viewpage_url':
                ATCconfig.get('confluence_viewpage_url')
            })

            self.dn_fields.update(
                {'description': self.dn_fields.get('description').strip()})

            logging_policies = self.dn_fields.get("loggingpolicy")

            if not logging_policies:
                logging_policies = [
                    "None",
                ]

            logging_policies_with_id = []

            for lp in logging_policies:
                if lp != "None" and self.apipath and self.auth and self.space:
                    logging_policies_id = str(
                        ATCutils.confluence_get_page_id(
                            self.apipath, self.auth, self.space, lp))
                else:
                    logging_policies_id = ""
                lp = (lp, logging_policies_id)
                logging_policies_with_id.append(lp)

            self.dn_fields.update({'loggingpolicy': logging_policies_with_id})

            mitigation_policies = self.dn_fields.get("mitigation_policy")

            if not mitigation_policies:
                mitigation_policies = [
                    "None",
                ]

            mitigation_policies_with_id = []

            for mp in mitigation_policies:
                if mp != "None" and self.apipath and self.auth and self.space:
                    mitigation_policies_id = str(
                        ATCutils.confluence_get_page_id(
                            self.apipath, self.auth, self.space, mp))
                else:
                    mitigation_policies_id = ""
                mp = (mp, mitigation_policies_id)
                mitigation_policies_with_id.append(mp)

            self.dn_fields.update(
                {'mitigation_policy': mitigation_policies_with_id})

            refs = self.dn_fields.get("references")

            if isinstance(refs, str):
                self.dn_fields.update({'references': [refs]})

        self.content = template.render(self.dn_fields)

        return True
示例#15
0
def main(c_auth=None):

    try:
        ATCconfig = ATCutils.load_config("config.yml")
        confluence_space_name = ATCconfig.get('confluence_space_name')
        confluence_space_home_page_name = ATCconfig.get(
            'confluence_space_home_page_name')
        confluence_rest_api_url = ATCconfig.get('confluence_rest_api_url')
        confluence_name_of_root_directory = ATCconfig.get(
            'confluence_name_of_root_directory')

    except Exception as e:
        raise e
        pass

    if not c_auth:
        mail = input("Login: "******""

    print("[*] Creating ATC root page...")

    data = {
        "title":
        confluence_name_of_root_directory,
        "spacekey":
        confluence_space_name,
        "parentid":
        str(
            ATCutils.confluence_get_page_id(url, auth, confluence_space_name,
                                            confluence_space_home_page_name)),
        "confluencecontent":
        content,
    }

    if not ATCutils.push_to_confluence(data, url, auth):
        raise Exception("[-] Could not create or update the page. " +
                        "Is the parent name correct?")

    pages = [
        "Detection Rules", "Logging Policies", "Data Needed", "Triggers",
        "Enrichments", "Customers", "Mitigation Systems",
        "Mitigation Policies", "Hardening Policies", "Use Cases"
    ]

    page_contents = {
        "Customers":
        "<p><ac:structured-macro ac:name=\"detailssummary\" ac:schema-version=\"2\" ><ac:parameter ac:name=\"cql\">label = &quot;atc_customer&quot; and space = currentSpace()</ac:parameter></ac:structured-macro></p>",
        "Use Cases":
        "<p><ac:structured-macro ac:name=\"detailssummary\" ac:schema-version=\"2\" ><ac:parameter ac:name=\"cql\">label = &quot;atc_usecases&quot; and space = currentSpace()</ac:parameter></ac:structured-macro></p>",
    }

    for page in pages:
        print("Creating %s..." % page)
        data = {
            "title":
            page,
            "spacekey":
            confluence_space_name,
            "parentid":
            str(
                ATCutils.confluence_get_page_id(
                    url, auth, confluence_space_name,
                    confluence_name_of_root_directory)),
            "confluencecontent":
            page_contents.get(page, content),
        }

        if not ATCutils.push_to_confluence(data, url, auth):
            raise Exception("[-] Could not create or update the page. " +
                            "Is the parent name correct?")
    print("[+] Initial Confluence page structure created!")
    return True
示例#16
0
def main(c_auth=None):

    try:
        ATCconfig = ATCutils.load_config("config.yml")
        confluence_space_name = ATCconfig.get('confluence_space_name')
        confluence_space_home_page_name = ATCconfig.get(
            'confluence_space_home_page_name')
        confluence_rest_api_url = ATCconfig.get('confluence_rest_api_url')
        confluence_name_of_root_directory = ATCconfig.get(
            'confluence_name_of_root_directory')

    except Exception as e:
        raise e
        pass

    if not c_auth:
        mail = input("Login: "******""

    print("[*] Creating ATC root page...")

    data = {
        "title":
        confluence_name_of_root_directory,
        "spacekey":
        confluence_space_name,
        "parentid":
        str(
            ATCutils.confluence_get_page_id(url, auth, confluence_space_name,
                                            confluence_space_home_page_name)),
        "confluencecontent":
        content,
    }

    if not ATCutils.push_to_confluence(data, url, auth):
        raise Exception("[-] Could not create or update the page. " +
                        "Is the parent name correct?")

    pages = ["Logging Policies", "Data Needed", "Enrichments"]

    for page in pages:
        print("Creating %s..." % page)
        data = {
            "title":
            page,
            "spacekey":
            confluence_space_name,
            "parentid":
            str(
                ATCutils.confluence_get_page_id(
                    url, auth, confluence_space_name,
                    confluence_name_of_root_directory)),
            "confluencecontent":
            content,
        }

        if not ATCutils.push_to_confluence(data, url, auth):
            raise Exception("[-] Could not create or update the page. " +
                            "Is the parent name correct?")
    print("[+] Initial Confluence page structure created!")
    return True