<jupyter_start><jupyter_text>Execution - Scheduled Task running from unusual folder Author: <NAME>Task Scheduler is a useful Windows tool to schedule frequently used program, with certain conditions. You used it? Yeah me neither. This is particularly useful if you're working on same thing everyday and already has a "habit" of using the same thing. But, because it is scheduled, it's also a place for malware to schedule their "update" against the machine. Roger Grimes said on PCWorld, and I quote, "I've seen malware hunters struggle to find out how the malicious code 'keeps re-infecting their clean system.' Answer: Check the Task Scheduler." Use CaseIn this use case, we're hunting a suspicious program from scheduled task. The program, for it to be hidden, placed itself in unusual directory. Sample Use Case Unusual Folder location used by threat actor :1. Temporary Folder2. User Directory FolderAny common person would not place their scheduled program on Temp, because it's their most common program to use, why would you place it in an obscure place? ObjectiveIdentify a suspicious program injected to Task Scheduler. This can be done by filtering Windows Security Auditing log for EventID 4698, which is "created a new scheduled task", and see what files are used in the scheduled task. If it was placed in an abnormal folder, with optional characteristic of obfuscated executable name, it should be audited. Log requirementsMicrosoft Windows Security Auditing Event Log Characteristics and Behaviour| No | Characteristic | Note | Why||----|----------------|------|---||  1 | A scheduled task was made| Initiation | Even though it's rarely used by common person, it might be a legitimate task ||2   | The scheduled task's program was placed in unusual folder ||Uncommon place for a usual task||3   | The scheduled task's name was obfuscated|Optional|| Referenceshttps://attack.mitre.org/techniques/T1053/[PCWorld Article](https://www.pcworld.com/article/244769/malware_using_windows_task_scheduler.html) SampleDataset acquired from [EVTX-ATTACK-SAMPLES](https://github.com/sbousseaden/EVTX-ATTACK-SAMPLES), with "The Unusual Folder" is `%windir%\Temp\`.<jupyter_code>import Evtx.Evtx as evtx
import Evtx.Views as e_views
import xml.dom.minidom as minidom
from xml.etree.ElementTree import XML
from bs4 import BeautifulSoup as bs
        
def get_events(input_file, parse_xml=False):
    """Opens a Windows Event Log and returns XML information from
    the event record.

    Arguments:
        input_file (str): Path to evtx file to open
        parse_xml (bool): If True, return an lxml object, otherwise a string

    Yields:
        (generator): XML information in object or string format

    Examples:
        >>> for event_xml in enumerate(get_events("System.evtx")):
        >>>     print(event_xml)

    """
    with evtx.Evtx(input_file) as event_log:
        for record in event_log.records():
            if parse_xml:
                yield record.lxml()
            else:
                yield record.xml()


# all of the above is just to parse the EVTX file as XML

filename = "logs/Execution/temp_scheduled_task_4698_4699.evtx"
xmloutput = ""
for event_xml in enumerate(get_events(filename)):
    if "4698</EventID>" in event_xml[1]:                           #Check if scheduled task (EventID 4698) was made
        parsedxml = minidom.parseString(event_xml[1])
        prettyxml = parsedxml.toprettyxml()
        #print(event_xml[0], prettyxml)                            #Print this if you want to see all the scheduled task made
        bs_content = bs(prettyxml, 'lxml')
        result = bs_content.find("data", {"name":"TaskContent"})   #What task were made
        result = str(result).replace("&lt;", "<")
        result = result.replace("&gt;", ">")
        bs_content_child = bs(result, 'lxml')
        print(bs_content_child.find("actions"))                    #Check what executable are used for each event<jupyter_output><actions context="LocalSystem">
<exec>
<command>cmd.exe</command>
<arguments>/C tasklist &amp;gt; %windir%\Temp\CYAlyNSS.tmp 2&amp;gt;&amp;amp;1</arguments>
</exec>
</actions>
{'fraction_non_alphanumeric': 0.08919506889050036, 'fraction_numerical': 0.009910563210055595, 'mean_word_length': 3.6080178173719375, 'pattern_counts': {'":': 1, '<': 15, '<?xml version=': 0, '>': 21, 'https://': 3, 'lorem ipsum': 0, 'www.': 1, 'xml': 23}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '231066', 'license': 'Apache-2.0', 'n_tokens_mistral': 1167, 'n_tokens_neox': 1100, 'n_words': 465, 'path': 'Endpoint/Execution - Scheduled Task running from unusual folder.ipynb', 'repo_name': 'MII-Cybersec/Threat-Hunting-Notebook', 'size': '4151'}