def playbookCreatePlay(sigma_raw, sigma_dict):
    """
    Process incoming Sigma Yaml.
    
    """
    play_data = playbook.play_create(sigma_raw, sigma_dict)

    return jsonify(play_data)
def playbookWebhook(webhook_content):
    """
    Process incoming playbook webhook.
    
    """
    action = webhook_content['payload']['action']
    issue_tracker_name = webhook_content['payload']['issue']['tracker']['name']
    issue_id = webhook_content['payload']['issue']['id']
    issue_status_name = webhook_content['payload']['issue']['status']['name']

    if action == 'opened' and issue_tracker_name == 'Sigma Import':
        playbook.play_create(str(issue_id))
    elif action == 'updated' and issue_tracker_name == 'Play':
        journal_details = webhook_content['payload']['journal']['details']
        detection_updated = False
        for item in journal_details:
            # Check to see if the Sigma field has changed
            if item['prop_key'] == '21':
                # Sigma field updated --> Call function - Update Play metadata
                playbook.play_update(issue_id)
                # Create/Update ElastAlert config
                if issue_status_name == "Active" and not detection_updated:
                    detection_updated = True
                    playbook.elastalert_update(issue_id)
                    playbook.navigator_update()
                    playbook.thehive_casetemplate_update(issue_id)
                elif issue_status_name == "Inactive" and not detection_updated:
                    detection_updated = True
                    playbook.elastalert_disable(issue_id)
                    playbook.navigator_update()

            # Check to see if the Play status has changed to Active or Inactive
            elif item['prop_key'] == 'status_id' and not detection_updated:
                if item['value'] == '3':
                    # Status = Active --> Enable EA & TheHive
                    detection_updated = True
                    playbook.elastalert_update(issue_id)
                    playbook.navigator_update()
                    playbook.thehive_casetemplate_update(issue_id)
                elif item['value'] == '4':
                    # Status = Inactive --> Disable EA
                    detection_updated = True
                    playbook.elastalert_disable(issue_id)
                    playbook.navigator_update()
    return "success"
def update_play(raw_sigma, repo_sigma, ruleset, ruleset_group, filename): 
    sigma_url = filename.replace('/SOCtopus/sigma/', 'https://github.com/Security-Onion-Solutions/sigma/tree/master/')
    for play in plays:
        if repo_sigma['id'] == play['sigma_id']: # Match sigma UUID
            repo_hash = hashlib.sha256(
                str(repo_sigma).encode('utf-8')).hexdigest()
            playbook_hash = hashlib.sha256(
                str(play['sigma_dict']).encode('utf-8')).hexdigest()
            if repo_hash != playbook_hash: # Check if hashes match
                    file = filename[filename.rfind('/')+1:]
                    backup_path = "/SOCtopus/custom/sigma/" + file
                    
                    if os.path.exists(backup_path): # Does the sigma file exist in /SOCtopus/custom/sigma/? If yes, this means Auto-Update is disabled
                        try:
                            with open(backup_path, encoding="utf-8") as fpi2:
                                raw = fpi2.read()
                            backup_rule = yaml.load(raw)
                            backup_hash = hashlib.sha256(str(backup_rule).encode('utf-8')).hexdigest()
                            
                        except Exception as e:
                            print('Error - Unable to load backup copy' + str(e))

                        if repo_hash != backup_hash: # Does the sigma repo hash match the backup hash? If not, then an update is available
                            play_status = "available"
                            update_payload = {"issue": {"subject": repo_sigma['title'], "project_id": 1, "tracker": "Play", "custom_fields": [ 
                                {"id": 31, "name": "Update Available", "value": "1"}]}} 
                            url = f"{playbook_url}/issues/{play['issue_id']}.json"
                            r = requests.put(url, data=json.dumps(
                                update_payload), headers=playbook_headers, verify=False)
                            playbook.play_template_backup(play['issue_id'])
                        else:
                            play_status = "nop"
                    else:
                        play_status = "updated"
                        formatted_sigma = f'{{{{collapse(View Sigma)\n<pre><code class="yaml">\n\n{raw_sigma}\n</code></pre>\n}}}}'
                        update_payload = {"issue": {"subject": repo_sigma['title'], "project_id": 1, "status": "Disabled", "tracker": "Play", "custom_fields": [ 
                            {"id": 9, "name": "Sigma", "value": formatted_sigma.strip()}, \
                            {"id": 28, "name": "Sigma URL", "value": sigma_url.strip()}, \
                            {"id": 27, "name": "Sigma File", "value": filename.strip()}]}} 
                        url = f"{playbook_url}/issues/{play['issue_id']}.json"
                        r = requests.put(url, data=json.dumps(
                            update_payload), headers=playbook_headers, verify=False)
            else:
                play_status = "nop"
            break

    else:
        print('No Current Play - Create New Play in Playbook')
        play_status = "new"
        creation_status = playbook.play_create(raw_sigma, repo_sigma,"community", ruleset, ruleset_group, "DRL-1.0", filename, sigma_url)
        print (creation_status)

    return play_status
def update_play(raw_sigma, repo_sigma, ruleset):
    for play in plays:
        if repo_sigma['id'] == play['sigma_id']:
            repo_hash = hashlib.sha256(
                str(repo_sigma).encode('utf-8')).hexdigest()
            playbook_hash = hashlib.sha256(
                str(play['sigma_dict']).encode('utf-8')).hexdigest()
            if repo_hash != playbook_hash:
                play_status = "updated"
                formatted_sigma = f'{{{{collapse(View Sigma)\n<pre><code class="yaml">\n\n{raw_sigma}\n</code></pre>\n}}}}'
                update_payload = {
                    "issue": {
                        "subject":
                        repo_sigma['title'],
                        "project_id":
                        1,
                        "status":
                        "Disabled",
                        "tracker":
                        "Play",
                        "custom_fields": [{
                            "id": 21,
                            "name": "Sigma",
                            "value": formatted_sigma.strip()
                        }]
                    }
                }
                url = f"{playbook_url}/issues/{play['issue_id']}.json"
                r = requests.put(url,
                                 data=json.dumps(update_payload),
                                 headers=playbook_headers,
                                 verify=False)
            else:
                play_status = "nop"
            break

    else:
        print('No Current Play - Create New Play in PB')
        play_status = "new"
        creation_status = playbook.play_create(raw_sigma, repo_sigma,
                                               "community", ruleset)
        print(creation_status)

    return play_status