<?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 Thalyson Sousa on Medium]]></title>
        <description><![CDATA[Stories by Thalyson Sousa on Medium]]></description>
        <link>https://medium.com/@thalysonz?source=rss-e26bcce559d8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZDddY8-TtG7Tipxuj7zIVw.jpeg</url>
            <title>Stories by Thalyson Sousa on Medium</title>
            <link>https://medium.com/@thalysonz?source=rss-e26bcce559d8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 02:19:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thalysonz/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[From Fragment Injection to Account Takeover in Android Apps]]></title>
            <link>https://medium.com/@thalysonz/from-fragment-injection-to-account-takeover-in-android-apps-2413d995a5b0?source=rss-e26bcce559d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/2413d995a5b0</guid>
            <dc:creator><![CDATA[Thalyson Sousa]]></dc:creator>
            <pubDate>Thu, 18 Jun 2026 18:56:11 GMT</pubDate>
            <atom:updated>2026-06-18T18:56:55.451Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction</strong></h3><p>Android applications commonly use exported activities, intents, fragments, and WebViews to compose internal flows. These primitives are powerful, but when they are connected without trust boundaries, a component that was meant to be generic can become a primitive for account takeover.</p><p>During an Android security assessment of a [REDACTED] application, I identified a Fragment Injection vulnerability that allowed a malicious third-party app installed on the same device to open an internal fragment with attacker-controlled parameters.</p><p>The vulnerable flow was especially interesting because the injectable fragment could be a WebView fragment. Once the attacker controlled the URL loaded in that WebView, exposed JavaScript interfaces made it possible to request login data and receive authentication tokens in JavaScript, leading to Account Takeover (ATO).</p><h4><strong>What is Fragment Injection?</strong></h4><p>Fragment Injection happens when an app allows untrusted input to decide which Android <strong><em>`Fragment`</em></strong> class should be instantiated and which arguments should be passed to it.</p><p>In a safe design, external intents should map to a small set of validated routes. The caller might request an action such as `open_booking_details`, but the app should decide which internal fragment implements that action.</p><p>In the vulnerable design, the external caller could provide a serialized object containing:</p><ul><li>The fragment class name</li><li>A bundle of fragment arguments</li><li>Values later consumed by the target fragment</li></ul><p>This turns a generic navigation activity into a gadget that can instantiate internal app screens on behalf of another application.</p><h4><strong>The Vulnerability</strong></h4><p>The vulnerable component was an exported <strong><em>`GenericFragmentActivity`</em></strong>.</p><p>[Screenshot redacted: exported <strong><em>`GenericFragmentActivity`</em></strong> manifest entry.]</p><p>This activity received an external `Intent`, extracted a `FragmentInfo` parcelable from it, and used that object to instantiate a fragment.</p><p>The vulnerable flow can be summarized as:</p><p>1.<strong><em>`GenericFragmentActivity`</em></strong> receives an external intent</p><p>2. The activity extracts <strong><em>`FragmentInfo`</em></strong> using <strong><em>`getParcelableExtra`</em></strong></p><p>3. The fragment class name and arguments are passed to <strong><em>`FragmentFactory`</em></strong></p><p>4. <strong><em>`FragmentFactory`</em></strong> resolves the class dynamically and instantiates it</p><p>5. An attacker can select an internal fragment, including <strong><em>`WebViewFragment`</em></strong></p><p>6. The attacker controls initialization arguments such as the loaded URI</p><h3><strong>Detailed Vulnerable Flow</strong></h3><h4><strong>1. GenericFragmentActivity</strong></h4><p>The activity starts by reading the intent that launched it. If there is no saved state, it calls <strong><em>`createFragmentFromFragmentInfo(intent)`</em></strong> and immediately places the returned fragment into the activity container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iwPZQaZ5Ifb-iIGd_xLOug.png" /></figure><p>The dangerous part is not the fragment transaction itself. The issue is that the fragment is derived from caller-controlled intent data.</p><h4><strong>2. createFragmentFromFragmentInfo</strong></h4><p>The helper method retrieves the <strong><em>`FragmentInfo`</em></strong> object and passes it to <strong><em>`FragmentFactory`</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j5LqxnCsuAHtxWjBcCDdCw.png" /></figure><p>There was no validation that the caller was trusted, no allowlist of safe fragment classes, and no validation that the supplied arguments were safe for the selected fragment.</p><h4><strong>3. FragmentInfo from getParcelableExtra</strong></h4><p>The <strong><em>`FragmentInfo`</em></strong> object was obtained directly from the received intent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q-AsEg9LQSVC8BwDGGAE2Q.png" /></figure><p>Accepting complex parcelables from another app is dangerous when the parcelable controls internal navigation or component instantiation. In this case, it controlled both.</p><h4><strong>4. FragmentFactory</strong></h4><p>The factory used the class name stored inside <strong><em>`FragmentInfo`</em></strong>, resolved it, created a new fragment instance, and applied the supplied arguments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*9c0mUOFpTuoiuyP5kIV0Dw.png" /><figcaption>FragmentFactory creating fragments from FragmentInfo</figcaption></figure><p>The relevant behavior was equivalent to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3u2uEUgJahNdyubFwZSArg.png" /></figure><p>At this point, the bug becomes a powerful internal navigation primitive. If an attacker can find a useful fragment already present in the app, they can instantiate it with controlled arguments.</p><h3><strong>Finding an Exploitable Fragment</strong></h3><p>After confirming arbitrary fragment creation, I looked for fragments that could turn this primitive into account compromise or code execution.</p><p>The useful target was:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*DvXtK0lIa3g2q4ZiBm5DQA.png" /></figure><p>The choice of <strong><em>WebViewFragment</em></strong> was not random. A few days before this report, I had reported another ATO chain in the same private program, involving an unsafe WebView intent. In that previous issue, a public deep link reached a bottom-sheet WebView activity that accepted attacker-controlled extras equivalent to <strong><em>`URL`</em></strong> and <strong><em>`ENCODED_HTML`</em></strong>. Those values were preserved through the dispatch flow and eventually controlled both the WebView’s apparent first-party URL and the HTML rendered inside it.</p><p>That earlier bug proved three important things about this WebView surface:</p><ul><li>The app had WebView flows where attacker-controlled HTML could run in a first-party-looking context</li><li>Some WebView implementations exposed JavaScript bridge functionality to the loaded page</li><li>The WebView context could become useful for session or token extraction when origin and content controls were confused</li></ul><p>So, after confirming that <strong><em>`GenericFragmentActivity`</em></strong> could instantiate arbitrary fragments, I searched for fragments connected to that same WebView feature area. <strong><em>`WebViewFragment`</em></strong> was a strong candidate because it inherited from the common WebView base class and exposed JavaScript events and bridge commands reachable from content loaded inside the WebView.</p><p>This Fragment Injection report was still a different vulnerability chain. The previous issue abused a deep link and WebView-specific extras to reach a bottom-sheet WebView. This issue abused an exported generic fragment host, injected `WebViewFragment` directly through <strong><em>`FragmentInfo`</em></strong>, and supplied the WebView initialization arguments through the fragment bundle.</p><p>Because the attacker controlled the WebView initialization URI, the malicious app could load attacker-controlled HTML inside the target application’s WebView context.</p><h4><strong>Proof of Concept</strong></h4><p>To reproduce the vulnerability, I created a separate Android application that launched the exported activity with a crafted <strong><em>`FragmentInfo`</em></strong>.</p><p>The PoC did the following:</p><p>1. Built a <strong><em>`Bundle`</em></strong> containing the WebView URI argument</p><p>2. Created a <strong><em>`FragmentInfo`</em></strong> object for <strong><em>`WebViewFragment`</em></strong></p><p>3. Created an explicit intent targeting <strong><em>`GenericFragmentActivity`</em></strong></p><p>4. Attached the crafted <strong><em>`FragmentInfo`</em></strong> as an extra</p><p>5. Started the activity from the malicious application</p><p>Simplified PoC:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KgGeG7BN0xg7gXOVL1aQfw.png" /></figure><p>When the victim opened the exploit app and clicked the button, the target app launched its own <strong><em>`GenericFragmentActivity`</em></strong>, instantiated <em>`WebViewFragment`</em>, and loaded the attacker-controlled page.</p><h3><strong>Exploitation Anatomy</strong></h3><p>The ATO chain had two possible paths.</p><h4><strong>Path 1: showBottomSheetWithContent</strong></h4><p>One JavaScript interface exposed a method named <strong><em>`showBottomSheetWithContent`</em></strong>. It allowed JavaScript to pass HTML content and a base URL, causing the application to open a bottom-sheet WebView.</p><p>The idea was:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BbW5QSpDzU_wk5U6G_mcuQ.png" /></figure><p>This was useful because it created another WebView surface controlled by JavaScript. However, this path could be considered close to a previous WebView issue, so the stronger chain used the login bridge.</p><h4><strong>Path 2: LoginJavascriptCommand</strong></h4><p>The second path used the login JavaScript command exposed by the WebView bridge.</p><p>The attacker-controlled page registered a listener for the login completion event, triggered the login command through the native JavaScript interface, and received token data in the event payload after login completed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AAuYPeBNQXF7ES4Oq8Ibzw.png" /></figure><p>The critical issue is that authentication material was delivered into a WebView controlled by an external app through fragment injection. Once the token was available to JavaScript, it could be sent to a remote server and used to authenticate as the victim.</p><p>After obtaining the token, an attacker could use it as a bearer token against authenticated APIs, resulting in account takeover.</p><h3><strong>Impact</strong></h3><p>The impact was severe because a malicious app installed on the same device could abuse an exported activity in the target app to:</p><ul><li>Instantiate internal fragments that were not intended to be externally reachable</li><li>Load attacker-controlled content inside an internal WebView</li><li>Access JavaScript bridge functionality exposed by the app</li><li>Trigger login-related native functionality</li><li>Receive authentication tokens in JavaScript</li><li>Exfiltrate tokens and perform authenticated API requests as the victim</li></ul><p>This leads to Account Takeover because the attacker obtains valid session material for the logged-in user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*DOsLPrtUwR8QLonMmFXapA.png" /></figure><h3><strong>References</strong></h3><p>- Previous write-up: <a href="https://thalysonz.com/exploiting-intent-hijacking-in-android-apps-to-ato-6ac2d76fc761">https://thalysonz.com/exploiting-intent-hijacking-in-android-apps-to-ato-6ac2d76fc761</a></p><p>- Android Developers — `&lt;activity&gt;` and `android:exported`: <a href="https://developer.android.com/guide/topics/manifest/activity-element#exported">https://developer.android.com/guide/topics/manifest/activity-element#exported</a></p><p>- Android Developers — `WebView.addJavascriptInterface`: <a href="https://developer.android.com/reference/android/webkit/WebView#addJavascriptInterface(java.lang.Object,%20java.lang.String)">https://developer.android.com/reference/android/webkit/WebView#addJavascriptInterface(java.lang.Object,%20java.lang.String)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2413d995a5b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploiting Intent Hijacking in Android Apps (to ATO)]]></title>
            <link>https://medium.com/@thalysonz/exploiting-intent-hijacking-in-android-apps-to-ato-6ac2d76fc761?source=rss-e26bcce559d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ac2d76fc761</guid>
            <dc:creator><![CDATA[Thalyson Sousa]]></dc:creator>
            <pubDate>Tue, 25 Mar 2025 13:41:34 GMT</pubDate>
            <atom:updated>2026-05-12T04:33:53.602Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QEduTl_-McRlSwvR" /></figure><h3>Introduction</h3><p>Android uses a messaging system called Intents for communication between different application components. When implemented incorrectly, this mechanism can create significant security vulnerabilities, allowing attackers to manipulate the application’s behavior in ways not intended by developers.</p><p>Recently, during a security assessment of a popular food delivery application, we identified a critical “Intent Hijacking” vulnerability that allowed unauthorized access to protected components of the application.<a href="https://seanpesce.github.io/WebView-Analyzer/">a</a></p><h3>What is Intent Hijacking?</h3><p>Intent Hijacking is a security vulnerability that occurs when an application improperly handles Intents. Intents are messages used for communication between components such as activities, services, or broadcast receivers.</p><p>When an application passes unvalidated or unsafe data (like extras in an Intent), an attacker can exploit this vulnerability to manipulate the application’s behavior, accessing components that should be protected.</p><h3>The Vulnerability</h3><p>During our analysis, we identified a chain of vulnerable components that create an intent hijacking condition. The vulnerable flow involves the ExportedActivity, which receives an Intent with an unvalidated extra called &quot;EXTRA_TARGET&quot;, and passes it to the ProcessPhoenix component, which then executes these Intents without any security checks.</p><p>This flaw made it possible to hijack and initiate any activity within the application, including unexported ones (which normally wouldn’t be accessible externally).</p><p>By exploiting this flaw, we were able to:</p><ul><li>Access internal content providers</li><li>Retrieve cached files</li><li>Obtain session tokens stored in the application’s context</li></ul><h3>Detailed Vulnerable Flow</h3><p>The vulnerability occurs in a chain of calls that include three main components:</p><p><strong>1. ExportedActivity</strong></p><pre>// ExportedActivity.java<br>@Override<br>protected void onCreate(Bundle savedInstanceState) {<br>    r.b(this, null, null, 3, null);<br>    super.onCreate(savedInstanceState);<br>    W().a(this, (Intent) getIntent().getParcelableExtra(&quot;EXTRA_TARGET&quot;));<br>}</pre><p>The ExportedActivity extracts a parcelable extra called &quot;EXTRA_TARGET&quot; from the received Intent and passes it to the a() method of the AppRestarter class (accessed via the W() method).</p><p><strong>2. AppRestarter</strong></p><pre>// AppRestarter.java<br>public final void a(androidx.appcompat.app.d activity, Intent initialIntentAfterRestart) {<br>    s.j(activity, &quot;activity&quot;);<br>    if (initialIntentAfterRestart == null) {<br>        initialIntentAfterRestart = this.splashDispatcher.a(activity);<br>        initialIntentAfterRestart.addFlags(536870912);<br>        initialIntentAfterRestart.addFlags(67108864);<br>    }<br>    ProcessPhoenix.b(activity, initialIntentAfterRestart);<br>}</pre><p>The AppRestarter receives the extracted Intent (or creates a new one if null) and passes it to the b() method of the ProcessPhoenix class.</p><p><strong>3. ProcessPhoenix</strong></p><pre>// ProcessPhoenix.java<br>public static void b(Context context, Intent... intentArr) {<br>    Intent intent = new Intent(context, ProcessPhoenix.class);<br>    intent.addFlags(268435456);<br>    intent.putParcelableArrayListExtra(&quot;phoenix_restart_intents&quot;, new ArrayList&lt;&gt;(Arrays.asList(intentArr)));<br>    context.startActivity(intent);<br>    if (context instanceof Activity) {<br>        ((Activity) context).finish();<br>    }<br>    Runtime.getRuntime().exit(0);<br>}<br><br>@Override<br>protected void onCreate(Bundle bundle) {<br>    super.onCreate(bundle);<br>    ArrayList parcelableArrayListExtra = getIntent().getParcelableArrayListExtra(&quot;phoenix_restart_intents&quot;);<br>    startActivities((Intent[]) parcelableArrayListExtra.toArray(new Intent[parcelableArrayListExtra.size()]));<br>    finish();<br>    Runtime.getRuntime().exit(0);<br>}</pre><p>The ProcessPhoenix packages the received Intents into an ArrayList and inserts them as an extra called &quot;phoenix_restart_intents&quot; in a new Intent directed to the ProcessPhoenix class itself. When ProcessPhoenix is started, it extracts these Intents and executes them via startActivities() without any validation.</p><p>This chain of calls creates a critical vulnerability: any Intent injected into the “EXTRA_TARGET” of ExportedActivity will eventually be executed by ProcessPhoenix without validation. Since ProcessPhoenix uses startActivities(), it can launch any activity within the application, including unexported ones.</p><h3>Proof of Concept (PoC)</h3><p>To demonstrate this vulnerability, we created an exploit application with the following steps:</p><ol><li>Install the exploit application</li><li>Set up a URL callback to receive intercepted data</li><li>Click “Start Exploit”</li></ol><h3>Exploitation Anatomy</h3><p>The attack is executed in two sequential stages, leveraging the chain of vulnerabilities:</p><p><strong>Stage 1: WebView Access</strong></p><ul><li>The malicious application creates an Intent targeted at the target application’s ExportedActivity</li><li>This Intent contains an “EXTRA_TARGET” extra configured to open an internal WebView of the application (unexported component)</li></ul><p><strong>Stage 2: Content Provider Access</strong></p><ul><li>After the first exploitation, the attacker sends a second Intent</li><li>This new Intent is configured to access the application’s internal Content Providers</li><li>Through the Content Provider, the attacker can access directories such as /cache/Cookies</li><li>The extracted data, including authentication tokens and session cookies, are sent to the attacker’s server via the callback URL</li></ul><p>This two-stage exploitation allows the attacker not only to access normally protected components but also to extract sensitive data stored locally on the victim’s device.</p><p>The intercepted data may include authentication tokens, which can be used to make authenticated requests:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*qr5wYDXTUbhxvsSVKFDf2g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*GoxtoJtkmGnYvO2f3_F6iQ.png" /></figure><p>After obtaining the token from the webview cookies, we can use it in the api</p><pre>GET /consumer HTTP/2<br>Host: api.example.com<br>User-Agent: [APP-NAME/10.48.1.1610004161/Android - SM-G9600 - 11 (API 30)]<br>Application-Id: 4<br>Application-Version: 10.48.1.1610004161<br>X-Session-Id: null<br>Accept-Language: en-GB<br>Accept-Charset: utf-8<br>Accept-Tenant: UK<br>Accept: application/json,text/json<br>Accept-Version: 2<br>X-Auser: 08e1da21-daaa-44a8-b651-c5e54bec5a07<br>Authorization: Bearer {{TOKEN}}<br>Accept-Encoding: gzip, deflate, br<br>X-Conversation: 7d1ec97f-9d37-4978-896c-a99c70ce9e68</pre><h3>Impact</h3><p>The impact of this vulnerability is severe, allowing:</p><ul><li><strong>Access to sensitive data</strong>: An attacker can access unexported activities that may contain user data, authentication tokens, and other confidential information.</li><li><strong>State manipulation</strong>: The attacker can alter the application state, potentially causing unexpected behavior.</li><li><strong>Privilege escalation</strong>: In some cases, this can lead to privilege escalation within the application.</li></ul><h3>Mitigation</h3><p>To mitigate this type of vulnerability, we recommend:</p><ul><li><strong>Validate all Intent data</strong>: Always validate any data received via Intent before using it to start new components.</li><li><strong>Implement origin checks</strong>: Verify that the Intent comes from a trusted source.</li><li><strong>Limit component exposure</strong>: Don’t unnecessarily export components and use permission protection.</li><li><strong>Sanitize parcelable data</strong>: Never trust unvalidated parcelable data, especially when used to start new components.</li><li><strong>Implement specific Intent filters</strong>: Define specific Intent filters to limit which Intents the component can receive.</li></ul><h3>Fixed Code</h3><p>A fixed version of the vulnerable code could implement security checks:</p><pre>protected void onCreate(Bundle savedInstanceState) {<br>    super.onCreate(savedInstanceState);<br>    <br>    // Validate Intent origin<br>    if (!isIntentFromTrustedSource(getIntent())) {<br>        Log.e(TAG, &quot;Intent from untrusted source, ignoring&quot;);<br>        finish();<br>        return;<br>    }<br>    <br>    // Validate extra content<br>    Intent targetIntent = getIntent().getParcelableExtra(&quot;EXTRA_TARGET&quot;);<br>    if (targetIntent != null &amp;&amp; isAllowedComponent(targetIntent.getComponent())) {<br>        startActivity(targetIntent);<br>    }<br>    <br>    finish();<br>}<br><br>private boolean isIntentFromTrustedSource(Intent intent) {<br>    // Implement logic to verify Intent origin<br>    // For example, check digital signature of the caller<br>    return true; // Placeholder<br>}<br><br>private boolean isAllowedComponent(ComponentName component) {<br>    // Whitelist of allowed components<br>    List&lt;String&gt; allowedComponents = Arrays.asList(<br>        &quot;com.example.app.SafeActivity&quot;,<br>        &quot;com.example.app.OtherSafeActivity&quot;<br>    );<br>    <br>    return component != null &amp;&amp; <br>           allowedComponents.contains(component.getClassName());<br>}</pre><h3>Conclusion</h3><p>Intent Hijacking is a critical vulnerability that remains present in many popular Android applications. Developers should be aware of the security implications when using Android’s Intent system and implement proper checks and validations.</p><p>This case demonstrates how seemingly simple flaws in Intent handling can lead to significant security compromises, allowing access to protected components and sensitive data.</p><h3>References</h3><ul><li><a href="https://blog.oversecured.com/Android-Access-to-app-protected-components/">Android Access to app protected components</a></li><li><a href="https://developer.android.com/topic/security/best-practices">Android Developer Documentation — Security</a></li><li><a href="https://owasp.org/www-project-mobile-top-10/">OWASP Mobile Top 10: M1 — Improper Platform Usage</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ac2d76fc761" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring mTLS in Mobile Applications]]></title>
            <link>https://medium.com/@thalysonz/exploring-mtls-in-mobile-applications-044e52494b3a?source=rss-e26bcce559d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/044e52494b3a</guid>
            <dc:creator><![CDATA[Thalyson Sousa]]></dc:creator>
            <pubDate>Wed, 12 Feb 2025 00:19:05 GMT</pubDate>
            <atom:updated>2025-02-12T00:19:05.929Z</atom:updated>
            <content:encoded><![CDATA[<h3>Exploring mTLS in Mobile Applications</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IxZ0HBbC6VjBfspp-YDr-Q.png" /></figure><p>Today, I will present a case study on mTLS that I conducted in a private bug bounty program.</p><p>**mTLS** (Mutual TLS) is a method of mutual authentication that ensures both parties in a network connection are who they claim to be. In an mTLS connection, the server verifies the client’s certificate, and the client verifies the server’s certificate. If a proxy like Burp Suite were used in this connection, the server would reject the connection.</p><h4>### What is mTLS?</h4><p>Mutual TLS (mTLS) is a security protocol used in network communications to provide an enhanced level of security. In a standard TLS setup, only the server is authenticated, while the client remains unauthenticated. This means that while the client can trust the server, the reverse isn’t necessarily true.</p><p>In contrast, mTLS adds an extra layer of security by requiring both the client and the server to authenticate themselves to each other before establishing a secure connection. This is achieved through the use of digital certificates on both ends. When a client attempts to connect to a server using mTLS, the following steps typically occur:</p><p>1. The client presents its certificate to the server.<br>2. The server verifies the client’s certificate.<br>3. The server presents its certificate to the client.<br>4. The client verifies the server’s certificate.</p><h4>How Does the Client Certificate Verification Flow Work?</h4><p>In the case of this application, a request containing a Certificate Signing Request (CSR) certificate was sent to the server. The server’s response was a CA (Certificate Authority) certificate signed by the company.</p><h4>### Certificate Signing Request (CSR) in mTLS</h4><p>A crucial component in the mTLS process is the Certificate Signing Request (CSR). Let’s break down what a CSR is and its role in mTLS:</p><p>- A CSR is one of the initial steps in obtaining an SSL/TLS certificate.<br>- It’s generated on the server where you plan to install the certificate.<br>- The CSR contains essential information such as the common name, organization, and country.<br>- It also includes the public key that will be part of your certificate.<br>- The CSR is signed with the corresponding private key.</p><h4>### PKCS #12: Bundling Cryptographic Objects</h4><p>PKCS #12 is an archive file format used for storing multiple cryptography objects in a single file. It’s commonly used to:</p><p>- Bundle a private key with its X.509 certificate<br>- Bundle all members of a chain of trust</p><p>This format plays a crucial role in managing the various certificates and keys used in mTLS.</p><h4>#### CSR Request and CA Response</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*PHXBzazlYOZrqlqAGM6SmQ.png" /></figure><p>In the image above, we have a section of the application code responsible for creating the CSR certificate that will be sent to the server.</p><h4>#### Hooking Process</h4><p>Using Frida, I converted my keys (public and private) to the format expected by the `generateCertificateSigningRequest(args)`.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*yTJH8I0LLP1kXtQOF-Jakg.png" /></figure><p>We can then hook the generateCertificateSigningRequest(args) function and alter the public and private keys used in the CSR creation process. Now the application will send the CSR certificate containing the new keys and generate a CA that we can use to create a pkcs12 file and import it into Burp Suite.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*ME0HQovHdDGk2zLLUCOqlQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*lkQdRVt6AjmeRlk4-UEoHQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*LHu7Psz_2UZLdFC8BgO3Zw.png" /></figure><h4>#### PKCS#12 Import in Burp Suite</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*J6azIAinTn-sqqTSvI40JQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*5aQ2OTRY5QNC_nLKody3ow.png" /></figure><h4>#### Conclusion</h4><p>Mutual TLS provides a robust method of ensuring secure and authenticated communication between clients and servers. In the context of a bug bounty program, understanding and exploiting mTLS can be crucial for identifying potential security flaws and vulnerabilities.</p><p>For more detailed information on mTLS and related topics, you can refer to the following resources:</p><p>- [Cloudflare: What is Mutual TLS?](<a href="https://www.cloudflare.com/pt-br/learning/access-management/what-is-mutual-tls/">https://www.cloudflare.com/pt-br/learning/access-management/what-is-mutual-tls/</a>)<br>- [GlobalSign: What is a Certificate Signing Request (CSR)?](<a href="https://www.globalsign.com/pt-br/blog/what-is-a-certificate-signing-request-csr">https://www.globalsign.com/pt-br/blog/what-is-a-certificate-signing-request-csr</a>)<br>- [Hostinger: What is SSL/TLS?](<a href="https://www.hostinger.com.br/tutoriais/o-que-e-ssl-tls-https">https://www.hostinger.com.br/tutoriais/o-que-e-ssl-tls-https</a>)</p><p>Happy securing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=044e52494b3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DeepLink Misconfiguration: Accessing PIX and Account Data]]></title>
            <link>https://medium.com/@thalysonz/deeplink-misconfiguration-accessing-pix-and-account-data-b0db1217257d?source=rss-e26bcce559d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0db1217257d</guid>
            <dc:creator><![CDATA[Thalyson Sousa]]></dc:creator>
            <pubDate>Thu, 09 May 2024 22:10:15 GMT</pubDate>
            <atom:updated>2025-10-06T15:06:09.814Z</atom:updated>
            <content:encoded><![CDATA[<h3>Exploiting Webview JS Bridges: Accessing PIX and Account Data</h3><p>While analyzing an application, I noticed that some deeplink calls contained the “path” parameter, and this parameter was being used to define the path of the WebView that the application was accessing.</p><h4>### Controlling the Path with Deeplinks</h4><p>So, we could control the path that the WebView was loading, but what if there was an “@” in the path parameter?</p><p>If we try to put an “@” in the path parameter, we can control the site that will be loaded in the application’s WebView because instead of accessing `<a href="https://help-webview.com`/">https://help-webview.com`</a>, the WebView will load whatever comes after the “@”.</p><p>When a browser encounters a URL with an “@” symbol, such as <a href="https://legit.com@evil.com/">https://legit.com@evil.com</a>, it interprets the part before the “@” (in this case, legit.com) as the user credentials (username) for authentication. The actual URL that the browser will navigate to is the part after the “@” (in this case, evil.com).</p><p>Therefore, when you enter <a href="https://legit.com@evil.com/">https://legit.com@evil.com</a> in the browser, it ignores legit.com and navigates to <a href="https://evil.com/">https://evil.com</a>. This behavior can be exploited to create deceptive links that appear to lead to a trusted site but actually redirect to a different, potentially malicious site.</p><p>For example:</p><p>• URL entered: <a href="https://legit.com@evil.com/">https://legit.com@evil.com</a><br> • URL loaded: <a href="https://evil.com/">https://evil.com</a></p><h4>### Open Redirect in WebView</h4><p>Now, in summary, we would have an open redirect in the WebView. However, since it is a financial application, I would like to find a way to further impact this vulnerability. Analyzing the WebView that the application was supposed to load, I found in the libs that the page loads a WebView-bridge, which is essentially a bridge for communication/interaction between the page and the application.</p><h4>### Custom Bridge Implementation</h4><p>I think you can see where this is going, right?</p><p>If we redirect the application to our own server where we have implemented a custom bridge, we can control some calls that the application has implemented. I started rewriting the WebView-bridge library on a web page on my server. In the image below, I show some of the code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/0*5vI-LOSqlvxABLIe" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/0*Iq20r9SukA5FuQuD.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/0*lnniOvzb2GHi9uDc.png" /></figure><h4>### JavaScript Bridge</h4><p>A JavaScript bridge acts as a communication channel for bidirectional data exchange between web content and the native application. iOS and Android WebViews support communication through JS bridges.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*R4vskKQ-oh7SsxuY.png" /></figure><h4>### Exploration</h4><p>Given this information, I created a POC (Proof of Concept) to exploit this vulnerability. Here are the steps:</p><p>1. **Set up a server**: I set up a server to host my custom WebView-bridge.<br>2. **Redirect the application**: By modifying the deeplink path to include `<a href="http://twitter.com/my">@my</a>-custom-server.com`, I redirected the WebView to load my server instead of the intended URL.<br>3. **Implement the custom bridge**: On my server, I implemented a custom WebView-bridge that mimicked the original bridge but with added capabilities to intercept and control the communication between the web content and the application.<br>4. **Test the vulnerability**: With the custom bridge in place, I tested various interactions to see what data I could access and what actions I could perform.</p><h4>### Results</h4><p>The custom bridge allowed me to intercept sensitive information and perform actions that should not have been possible, demonstrating a significant security vulnerability in the application.</p><p>1. **user data**: We can use the javascript bridge to get the user data, we can easily save this data by sending it to our server and storing it. As a visual example, I gave an Alert() on the data received from the javascript bridge</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/0*Sjho3VcqIwTmzeUT.png" /></figure><p>2. **PIX transfers**: To make it even more critical, I decided to use the application’s API, which we could interact with to request a transfer in the background after loading the page. It required a second implementation in the bridge we had developed, but in the end, it was possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/0*-bGF1MXalWmgzRZy.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/0*A5q9k7NSgcdsnzU2.png" /></figure><h4>### Conclusion</h4><p>This vulnerability highlights the importance of proper validation and security measures when handling deeplinks and WebViews in financial applications. Developers should ensure that all parameters are properly sanitized and that WebViews are configured to prevent such exploits.</p><p>For more information, you can check my profile: (<a href="http://twitter.com/thalyson">@thalyson</a>.sec)(<a href="https://medium.com/@thalyson.sec">https://medium.com/@thalyson.sec</a>)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0db1217257d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Race condition ???]]></title>
            <link>https://medium.com/@thalysonz/race-condition-598b260ab3f0?source=rss-e26bcce559d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/598b260ab3f0</guid>
            <dc:creator><![CDATA[Thalyson Sousa]]></dc:creator>
            <pubDate>Thu, 09 May 2024 20:53:58 GMT</pubDate>
            <atom:updated>2025-02-12T00:24:33.206Z</atom:updated>
            <content:encoded><![CDATA[<h3>Race Condition: Some Real Cases</h3><h3>## Race condition</h3><blockquote>Race conditions are a common type of vulnerability closely related to business <a href="https://portswigger.net/web-security/logic-flaws">logic flaws</a>. They occur when websites process requests concurrently without adequate safeguards. This can lead to multiple distinct threads interacting with the same data at the same time, resulting in a “collision” that causes unintended behavior in the application. A race condition attack uses carefully timed requests to cause intentional collisions and exploit this unintended behavior for malicious purposes.</blockquote><p>Para saber mais sobre race condition ou ate mesmo praticar em alguns laboratórios -&gt;&gt;&gt;</p><p><a href="https://portswigger.net/web-security/race-conditions">Race conditions | Web Security Academy</a></p><h3>## Introdu<strong>ção</strong></h3><p>Tentei listar alguns cenários de race condition ou similares que encontrei durante bug bounty em 2023/2024 após ler a pesquisa do <a href="https://twitter.com/albinowax">@albinowax</a> .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*05rAAVNpoPrNQkp5GGk68A.png" /><figcaption>race condition bountys</figcaption></figure><h3>## 1.</h3><p>O cenário abaixo foi a vulnerabilidade mais critica e permitiria que eu explorasse a aplicação para abusar da feature de estorno.</p><p>Primeiro foi necessário assinar um serviço, haviam dois planos disponíveis um no valor de R$ 49,00 e outro no valor de R$ 450 reais, após assinado se o cliente solicitasse o reembolso ele teria o valor pago estornado em sua conta.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*n0YtGsG1EQmXBCHTlsksZw.png" /></figure><p>Enviando a requisição de cancelamento para o turbo intruder(selecione race condition) podemos ver que tivemos varias solicitações com o status 200 indicando sucesso na requisição.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*RW1BVcjB85vPGup8HxGZHw.png" /><figcaption>Turbo intruder request</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*yBGcjXVdquA3hX7kAwb2lQ.png" /><figcaption>Turbo intruder response</figcaption></figure><p>Abaixo podemos ver o primeiro deposito que fiz no valor de R$ 50 reais e a assinatura do serviço sendo cobrada no valor de R$ 49,00 e logo após podemos ver vários depósitos de estorno sendo enviados para a conta.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*Bb13lPMc2gFmbQILlZKSIQ.png" /><figcaption>account image 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*4R5Z25PQEBTWzOnOeTlV0A.png" /><figcaption>account image 2</figcaption></figure><p>No final ficamos com o saldo de R$ 981 reais.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*i5cMpgDCccpbI583M2W0VA.png" /></figure><p>Explorando outro endpoint da aplicação tivemos outro cenário parecido, onde foi necessário assinar um serviço e cancelar para abusar da feature de estorno. Nesse caso tivemos menos requisições com o status de sucesso porem ainda sim conseguimos explorar a aplicação e conseguimos vários estornos referentes ao mesmo serviço.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*Y7ES0NRfvS2BE8M5Gbxtsw.png" /><figcaption>request</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*rbkzJFoT9VR3yneBgAIA1g.png" /><figcaption>turbo intruder</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*jc9QbolLh8oCoDLd4w9Ciw.png" /><figcaption>account image 3</figcaption></figure><h3>## 2.</h3><p>Esse segundo cenário foi um caso que não me rendeu nenhuma premiação pois a empresa decidiu que não representava risco por se tratar de uma aplicação sandbox, porem quis trazer para demostrar um maior numero de exemplos para exploração.</p><p>Nessa aplicação existia um limite de deposito de $1000 dolares por dia, como indica na imagem abaixo. Porem explorando a requisição com o turbo intruder fomos capaz de bypassar esse limite, como demostrado abaixo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*16-D3t55FxZVhZVIsHRREQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*FV8SdB8yhwU_tvXGqa2yyw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*iGsbwuSQ5v91UNSES9tHHg.png" /></figure><p>Abaixo demostro outras tentativas que havia feito em outras contas, demostrando a possibilidade de bypass.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*MSjsGV_KzLDgs1-sb-svHA.png" /></figure><p>Ao tentar depositar depois de atingirmos o limite diário recebemos a imagem abaixo, porem como demostrado acima podemos bypassar esse limite.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*A5RdR2dKeIzPxErKx1RRwA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=598b260ab3f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web Cache Deception: Some Real Cases]]></title>
            <link>https://medium.com/@thalysonz/web-cache-deception-wcd-55f0b39b5830?source=rss-e26bcce559d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/55f0b39b5830</guid>
            <dc:creator><![CDATA[Thalyson Sousa]]></dc:creator>
            <pubDate>Fri, 29 Dec 2023 15:46:27 GMT</pubDate>
            <atom:updated>2023-12-29T15:48:28.487Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>## Web Cache Deception (WCD)</strong></p><p>Web Cache Deception (WCD) is an attack in which an attacker tricks a cache proxy into improperly storing private information sent over the Internet, gaining unauthorized access to these cached data. It was proposed by Omer Gil, a security researcher, in 2017.</p><p><strong>## Introduction</strong></p><p>Many are already aware of what Web Cache Deception is and how its exploitation works, so today I wanted to bring something different and show some real scenarios that I reported in 2023 in bug bounty programs.</p><p><strong>### 1. Search Feature</strong></p><p>Our first case concerns a web application, most likely Laravel, where it was possible to exploit WCD by abusing the text search feature of the API. The PATH was something like <strong>**/v2/search/{WORD}**</strong> where {WORD} would be our search term. Changing the PATH to <strong>**/v2/search/anything;.css**</strong> led the server to respond to our request with the <strong>**MISS**</strong> Header, and subsequent requests with the <strong>**HIT**</strong> Header.</p><p>Below is an example of the response:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*oFGa6-jZE1-P150tfVwCrw.png" /></figure><p>In this scenario, we just had to send <strong>**https://edited.com/v2/search/VICTIM;.css**</strong> to a user, and their cookie would be saved in the page’s response. We achieved a high impact with this vulnerability.</p><p><strong>### 2. Ignoring Content</strong></p><p>This second case was quite similar to the first, but here the exploitation occurred because the application ignored everything that came after “;” in a specific version of the API. This application used the route /v4/me to obtain authenticated user data, but it still had older versions in production (such as v2 and v3) and in v2 specifically, everything after “;” was ignored. Therefore, we could exploit this application by sending <strong>**https://edited.com/v2/me;anything.css?params**</strong> to a user, and after clicking, their data, which were returned in the page response, would be stored in the cache.</p><figure><img alt="IMG1" src="https://cdn-images-1.medium.com/proxy/1*y8g2zslj6uC0ENHN_uxNQg.png" /></figure><figure><img alt="IMG1" src="https://cdn-images-1.medium.com/proxy/1*hyaCCBE9E_9LW4dxyGiEfA.png" /></figure><p><strong>### 3. Abusing Other Functionalities, no ATO</strong></p><p>In this scenario, I wanted to bring something different from account theft to show other horizons of exploitation. In this application, we also managed to make a part of the passed path be ignored by the application. While testing some scenarios, I noticed that the application returned a 404 and the path I tried to access, and when using some special characters in URL Encoding, it returned the output decoding. With this, when trying to access API paths passing <strong>**%0a-anytext**</strong> (\n in URL Encoding), it returned a 200 status code. So, it was just a matter of changing to <strong>**/api/user%0a-anytext.css**</strong> for us to have our response stored in cache.</p><figure><img alt="IMG1" src="https://cdn-images-1.medium.com/proxy/1*PSZ4AMaLutHmgwAq7oNIVg.png" /></figure><p>However, unlike the previous applications, we couldn’t exploit an Account Takeover (ATO) in a straightforward manner, as we were not dealing with cookies that were passed and returned in the same request simply. The application used Authorization Bearer, where the token is usually stored in local storage. Therefore, we couldn’t just send an API link to a user and have their data saved in the cache, because it’s the front-end of the application that constructs the requests for the API and adds the authorization header. As a result, our report was downgraded to a medium impact.</p><figure><img alt="IMG1" src="https://cdn-images-1.medium.com/proxy/1*jKFfVY7fB-gM1oR5Wh2sMQ.png" /></figure><p>Focusing on high and critical impact reports, I moved on to another exploitation scenario where I attempted to use WCD to exploit features of the application. One such feature was the invitation to rooms where a user can create an invitation to their room/group and then destroy/deactivate it, making it no longer possible to enter through that invitation.</p><p>To exploit this feature, we first created an invitation and used WCD to save the content of this invitation in the cache <strong>**/api/invite/INVITE%0a-randomtext.css**</strong>. With its content now cached, we can destroy this invitation, but we still have the cached version, allowing us to access the group from a destroyed invitation.</p><p>Destroyed invitation, response not found.</p><figure><img alt="IMG1" src="https://cdn-images-1.medium.com/proxy/1*tnLvJqBa-kckni_w6obD8g.png" /></figure><p>Destroyed Invitation, Response Found</p><figure><img alt="IMG1" src="https://cdn-images-1.medium.com/proxy/1*GgTNEKqolWuJs_sO-6JDfw.png" /></figure><p>After sending it to the program’s team, we got our result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*viV79ObpnNqY_7m1hUdHmQ.png" /></figure><p>Original → https://thalysonz.github.io</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55f0b39b5830" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Uma alternativa gratuita para sua VPS ?]]></title>
            <link>https://medium.com/@thalysonz/uma-alternativa-gratuita-para-sua-vps-c5686d4a751f?source=rss-e26bcce559d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5686d4a751f</guid>
            <dc:creator><![CDATA[Thalyson Sousa]]></dc:creator>
            <pubDate>Mon, 24 Jul 2023 08:19:22 GMT</pubDate>
            <atom:updated>2023-07-24T08:19:22.743Z</atom:updated>
            <content:encoded><![CDATA[<h2>Uma alternativa gratuita para sua VPS ?</h2><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*xd2KZ-1EdLZmmYqAYTE_MA.png" /></figure><p>Algum tempo atrás, acabei perdendo minha VPS por falta de pagamento (tenho uma memória bem curta, às vezes). Então, nesse meio tempo, decidi tentar utilizar o Google Colaboratory para executar algumas ferramentas que me auxiliam em bug bounty e suprir a falta que a VPS me fez hahaha.</p><h3><strong>O que é o Google Colaboratory ?</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/0*doKocVKH7n-Vmy0w.png" /></figure><blockquote>“O Colaboratory ou “Colab” é um produto do Google Research, área de pesquisas científicas do Google. O Colab permite que qualquer pessoa escreva e execute código Python arbitrário pelo navegador e é especialmente adequado para aprendizado de máquina, análise de dados e educação. Mais tecnicamente, o Colab é um serviço de notebooks hospedados do Jupyter que não requer nenhuma configuração para usar e oferece acesso sem custo financeiro a recursos de computação como GPUs.”</blockquote><p><a href="https://research.google.com/colaboratory/intl/pt-BR/faq.html">Google Colab</a></p><h3>Vamos lá</h3><p>Como vimos, o Google Colab é um produto da Google que nos permite trabalhar com Python diretamente do nosso navegador. Na imagem abaixo, temos a estrutura inicial do nosso Colab assim que iniciamos um novo bloco.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1U07eqKvd5kciG5Q-ByLtA.png" /></figure><p>Temos a opção de adicionar <strong>código </strong>ou <strong>texto</strong>, sendo o código a parte de programação que queremos executar, e a parte de texto sendo algum conteúdo que desejamos adicionar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lngk470NEXi2iGm_2yTm4g.png" /></figure><p>Porém, a chave para trabalharmos com o Colab, utilizando-o para executar ferramentas como recon, exploits, etc., é que além de código Python, podemos utilizá-lo como se estivéssemos em uma VPS. Ao utilizar o caractere “!” no começo de cada bloco de código, podemos executar comandos como se estivéssemos em um terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*-lNPGcdvAfn0Tc8CNMq_gw.png" /></figure><p>Acho que já ficou claro o ponto, não é? Com isso, podemos usar o Colab para instalar e executar nossas ferramentas sem precisar usar nossa máquina local ou uma VPS. Abaixo, um exemplo simples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-0sWXJfv4v94-PzEXpMSxw.png" /></figure><p>No exemplo acima, temos três blocos responsáveis por instalar o GO e a ferramenta Nuclei, e após isso, mover o Nuclei para a pasta “bin”. Após isso, podemos usar a ferramenta Nuclei.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cjf8Fem0pF_rELGL3aZraA.png" /></figure><p>A partir desse exemplo, podemos seguir para casos mais complexos, onde podemos instalar uma série de ferramentas e preparar o Colab para executar uma sequência de comandos diferentes para nos auxiliar. Claro que com uma VPS, podemos ter uma liberdade muito maior, <strong>mas queria trazer aqui uma alternativa gratuita para quem ainda não conhecia</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5686d4a751f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PixPirate: Malware do Pix]]></title>
            <link>https://medium.com/@thalysonz/pixpirata-malware-do-pix-b53927159bc3?source=rss-e26bcce559d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/b53927159bc3</guid>
            <dc:creator><![CDATA[Thalyson Sousa]]></dc:creator>
            <pubDate>Fri, 24 Feb 2023 21:41:35 GMT</pubDate>
            <atom:updated>2023-02-24T21:52:44.582Z</atom:updated>
            <content:encoded><![CDATA[<h3>Resumo</h3><ul><li><em>Nome do pacote</em>: com.dam.ninth</li><li><em>SHA256 hash</em>: 911fa473f75d48e28384023b4a008d6d0877ad0fa58f9ebf38da1b02a1481314</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/0*JlxcoyQTN0YkYLc-.png" /></figure><p>Pixpirate é uma família de malware mobile que começou a ficar mais famosa entre o primeiro e segundo semestre de 2022. Ele faz uso das funções de acessibilidade do Android para obter informações do dispositivo, mapeando teclas e processos abertos. Entre as diversas funções desse novo malware, destacam-se as seguintes:</p><ul><li>Observar/interagir com SMS;</li><li>Observar/interagir com notificações;</li><li>Evitar desinstalação;</li><li>Observar aplicativos em execução no dispositivo;</li><li>Uso das funções de acessibilidade;</li><li>Etc.</li></ul><h3>Inicio</h3><p>Vamos comecar pelo arquivo AndroidManifest.xml que é obrigatório em todos os aplicativos Android. Nele são descritas informações básicas do aplicativo, como nome do pacote, versão do aplicativo, permissões necessárias, entre outras informações.</p><p>A documentação oficial de desenvolvimento sobre o Android Manifest pode ser encontrada aqui, mas resumindo, neste arquivo conseguimos ter uma noção sobre como o aplicativo vai funcionar. Podemos visualizar quais eventos ele está escutando e como responde a eles, quais serviços ele roda em segundo plano e também observar se existe alguma classe que ele chamou mas não está sendo carregada na análise estática.</p><p>Para quem não conhece muito de desenvolvimento Android, pode ter ficado confuso como tudo isso acontece. Vou tentar explicar de uma maneira um pouco mais clara.</p><p>No sistema Android, temos o modelo pub/sub (publicação/assinatura) para comunicação, onde é possível que aplicativos comuniquem informações uns com os outros sem que precisem estar em execução simultaneamente. Isso é possível por causa de um recurso chamado Broadcasts, que são basicamente mensagens enviadas entre aplicativos. Com isso, um aplicativo pode se registrar, usando um elemento chamado Receiver, definido no AndroidManifest.xml, para receber um broadcast e definir tarefas para serem executadas quando ouvirem esse broadcast.</p><p>No AndroidManifest, também temos os Services e os Providers, onde o primeiro é responsável por executar tarefas em segundo plano e o outro por permitir que o aplicativo compartilhe dados com outros.</p><p>Observando tudo isso nesse arquivo conseguimos ter uma nocao inicial sobre como o aplicativo vai funcionar ao ser instalado e ter uma nocao do fluxo de codigo dele.</p><h3>Permissões:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/0*atwm-8GCK-4S675O.png" /></figure><p>Aqui temos a lista de permissoes que aplicativo pede ao usuario, abaixo listei algumas que nao sao tao comuns e podem ser prejudiciais ao usuario.</p><p>Aqui um link da documentacao do android a respeito das permissoes: <a href="https://developer.android.com/guide/topics/permissions/overview">https://developer.android.com/guide/topics/permissions/overview</a></p><ul><li>QUERY_ALL_PACKAGES:</li><li>permite que um aplicativo obtenha informações sobre todos os outros aplicativos instalados no dispositivo, incluindo detalhes como o nome do pacote, a versão e a data de instalação</li><li><em>Essa permissão é considerada uma permissão perigosa e, portanto, deve ser usada com cautela. Isso ocorre porque, se um aplicativo mal-intencionado obtiver essa permissão, poderá coletar informações pessoais ou confidenciais dos usuários, como as informações de login salvas em outros aplicativos. Por esse motivo, os usuários devem tomar cuidado ao conceder essa permissão a um aplicativo.</em></li><li>READ_INSTALL_SESSIONS:</li><li>permite que um aplicativo leia as informações sobre sessões de instalação de outros aplicativos.</li><li><em>Uma sessão de instalação é criada quando um usuário inicia o processo de instalação de um aplicativo na Google Play Store ou por meio de outros meios, como o download de um arquivo de instalação APK. Essa permissão permite que um aplicativo obtenha informações sobre as sessões de instalação em andamento, incluindo o estado da instalação, como progresso e status de conclusão.</em></li><li>READ_SYNC_SETTINGS:</li><li>permite que um aplicativo leia as configurações de sincronização da conta do usuário. A sincronização é o processo pelo qual os dados da conta do usuário são transferidos entre o dispositivo Android e os servidores da conta na nuvem, para garantir que as informações do usuário estejam atualizadas e disponíveis em todos os dispositivos.</li><li><em>é importante notar que, se um aplicativo malicioso obtiver essa permissão, ele poderá ler informações confidenciais da conta do usuário, como senhas e informações pessoais. Por esse motivo, os usuários devem conceder essa permissão apenas a aplicativos confiáveis.</em></li><li>AUTHENTICATE_ACCOUNTS:</li><li>permite que um aplicativo solicite ao usuário que autentique uma conta. Ela é usada por aplicativos que precisam de acesso a uma conta do usuário para fornecer recursos ou funcionalidades personalizadas.</li><li>Essa permissão é considerada uma permissão perigosa e, portanto, deve ser usada com cuidado. Isso ocorre porque, se um aplicativo mal-intencionado obtiver essa permissão, poderá solicitar ao usuário que autentique uma conta falsa, com o objetivo de roubar informações pessoais ou destruir dados.</li><li>Os aplicativos que desejam acessar essa permissão devem declará-la explicitamente em seu manifesto e solicitar a permissão do usuário em tempo de execução. Além disso, a partir do Android 6.0 (nível de API 23), essa permissão é protegida por um modelo de permissão mais restritivo, chamado de “permissão de tempo de execução”. Isso significa que os usuários precisam conceder a permissão explicitamente em tempo de execução para que o aplicativo possa acessá-la.</li><li>WRITE_SYNC_SETTINGS:</li><li>permite que um aplicativo altere as configurações de sincronização da conta do usuário. A sincronização é o processo pelo qual os dados da conta do usuário são transferidos entre o dispositivo Android e os servidores da conta na nuvem, para garantir que as informações do usuário estejam atualizadas e disponíveis em todos os dispositivos.</li><li>Essa permissão é considerada uma permissão normal e não é particularmente perigosa por si só. Ela é usada por aplicativos que precisam alterar as configurações de sincronização para permitir que o usuário controle as configurações de sincronização da conta.</li><li>No entanto, é importante notar que, se um aplicativo malicioso obtiver essa permissão, ele poderá alterar as configurações de sincronização sem o conhecimento do usuário, o que pode resultar em perda de dados ou outras consequências indesejadas. Por esse motivo, os usuários devem conceder essa permissão apenas a aplicativos confiáveis.</li></ul><h3>Acessibilidade(Arquivo XML):</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aKMomWmY_J7SyJ8M.png" /></figure><p>Explicando um pouco sobre, aqui esta sendo definido um servico a respeito das questoes de acessibilidade como a permissao BIND_ACCESSIBILITY_SERVICE, e o arquivo xml com as opcoes de acessibildiade que a aplicacao vai usar.</p><p>Segundo a documentacao do android, usando um arquivo de configuracao xml conseguimos definir uma gama maior de opcoes de acessibilidade para a aplicacao. Assim o malware utiliza disso para definir o que vai ser usado, abaixo expliquei tudo que foi definido no xml config do malware.</p><ul><li>android:description: Define a descrição do serviço de acessibilidade. Geralmente é usado para informar aos usuários sobre as funções e permissões do serviço.</li><li>android:accessibilityFlags: Define as configurações adicionais para o serviço de acessibilidade. flagRetrieveInteractiveWindows indica que o serviço pode recuperar janelas interativas, flagRequestFilterKeyEvents indica que o serviço pode filtrar eventos de teclado, flagReportViewIds indica que o serviço pode relatar IDs de visualização, flagRequestEnhancedWebAccessibility indica que o serviço pode solicitar recursos aprimorados de acessibilidade da Web e flagIncludeNotImportantViews indica que o serviço pode incluir visualizações não importantes.</li></ul><h3>Analise estatica #1</h3><p>O malware possui uma forte ofuscação, o que dificulta uma análise inicial e pode ser assustador à primeira vista. No entanto, seguindo alguns passos já mencionados, é possível ter sucesso na compreensão do fluxo do aplicativo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/0*8VC6ogUzljSx6OW9.png" /></figure><p>Quase todas as strings importantes do malware foram modificadas utilizando uma operação XOR, mas é possível recuperar facilmente o valor original usando o “decode” que a aplicação chama e executando-o em alguma plataforma adequada.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mzqKoEF2sCM0yh9S.png" /></figure><p>Abaixo temos a classe responsável por inserir algumas das classes da aplicação na engine JS. Ao lado, comentei o significado de cada string.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Bp5vzHoQTpVEMRrp.png" /></figure><p>Abaixo temos uma interface responsável por alguns endpoints do C2, que posteriormente o AutoJS irá interagir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F1nZGpEgg6Ui9-L0.png" /></figure><p>Boa parte do código é utilizado para descompactar o arquivo project.zip, que contém o projeto JavaScript do AutoJS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/0*duC0jbhpHC6IjuB8.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JayEEG9JIZjPE9uO.png" /></figure><h3>Analise estatica #2 (Javascript)</h3><p>Utilizando o AutoJS, o malware consegue realizar uma série de atividades de forma furtiva, como observar as aplicações que o usuário utiliza (visualizando aplicativos que são abertos, aplicativos que estão abertos no modo janela, aplicativo na tela atual), observar e interagir com SMS e notificações que o aparelho recebe e verificar o status da SafeNet.</p><p>Abaixo está uma explicação sobre o que é o AutoJS:</p><ul><li>O AutoJS é uma ferramenta que permite a automação de tarefas em dispositivos Android. Ela foi projetada para permitir que os usuários criem scripts personalizados que podem ser executados em seus dispositivos para automatizar várias tarefas.</li><li>Com o AutoJS, é possível escrever scripts que automatizam interações com aplicativos Android, como abrir e fechar aplicativos, preencher formulários, clicar em botões e até mesmo interagir com o sistema operacional do dispositivo. Esses scripts podem ser executados automaticamente em um horário agendado ou por meio de gatilhos específicos, como quando o dispositivo é conectado a uma rede Wi-Fi específica.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/0*WpnuYlqO_k_JOIW4.png" /></figure><p>Na imagem acima, temos a ordem de funcionamento do malware, retirado do arquivo main.js.</p><p>O script começa verificando as permissões de acessibilidade, algo obrigatório devido às funções do malware. Após isso, são chamados alguns eventos que o malware utiliza para verificar as aplicações e eventos em execução.</p><p>Em seguida, o malware executa algumas funções para verificar permissões em geral e também acessar eventos do dispositivo, ou fechar aplicativos de acordo com uma lista de strings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/0*zL2wzP66bznuNm2A.png" /></figure><p>Também podemos observar uma função chamada antiRemove, responsável por evitar remoções e paradas na execução do malware.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/0*_qMTwcv1DM1a4HQ8.png" /></figure><p>As duas últimas funções, <strong>startHijarkSms</strong> e <strong>startBank</strong>, o malware utiliza para acessar e interagir com o dispositivo permitem, desde acessar e excluir SMS e notificações até interagir com as aplicações bancárias.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-EEjZQRC_E3mm7eL.png" /></figure><p>Aqui temos a função responsável pelo SMS. Podemos observar a chamada ao serviço de acessibilidade logo no início do arquivo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/246/0*zQvIkebBZDJYnaoe.png" /></figure><p>Este arquivo é responsável por observar, acessar, filtrar e excluir SMS do dispositivo da vítima.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZtKMaWqfj5saXwn-.png" /></figure><p>A função chamada “annihilateSms” é a responsável por excluir os SMS.</p><p>O malware suporta vários bancos, como podemos ver na lista de arquivos abaixo. Ao analisarmos um desses arquivos, podemos entender um pouco mais sobre como o malware atua.</p><p><em>Arquivo: BrazilBank.js</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/0*5hSn0zlau93Nd0W4.png" /><figcaption>Lista de bancos suportados</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/0*hP8TCbz_z3WvFxNP.png" /><figcaption>Brazilbank.js</figcaption></figure><p>Aqui podemos ver que no início do arquivo é definido o banco que a vítima está usando.</p><p>A seguir, vou listar algumas funções com o comportamento do malware.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*U2MVJsx9v3aqM5-b.png" /><figcaption>obter saldo da vitima</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/0*rldvDb0ng1rghGXH.png" /><figcaption>Iniciar Pix</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UImyBk1_d-fGPcpN.png" /><figcaption>Esperar senha e iniciar GetCreds</figcaption></figure><ul><li>GleanBalance: responsável por coletar o saldo da vítima, utilizando um filtro disponível nas funções do AutoJS, onde filtra pelo valor de “Saldo disponível”.</li><li>Transfer: chama a função sendBalance, responsável por iniciar o processo de PIX na interface do usuário.”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F3hX3bKD_kklhR9K.png" /></figure><p>Aqui, o malware faz algumas verificações antes de prosseguir. Primeiro, ele verifica se o valor do saldo é válido.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/0*OX6G8ov4ANl25f0L.png" /></figure><p>Após isso, é feita uma verificação sobre o saldo da vítima, onde o malware verifica se o saldo é maior que o Teto (provavelmente o malware estabeleceu um limite máximo para as transações PIX a fim de evitar bloqueios por valores muito altos), sendo o valor do Teto definido como 4777.</p><p>Em seguida, podemos verificar que o malware multiplica o valor do saldo por 0.95, possivelmente uma outra medida de segurança para evitar bloqueios nas transações PIX.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/0*Km4lIDBZYvzmT5oi.png" /></figure><p>Após isso, o malware interage com a classe C2C, que foi mencionada na importação no código nativo da aplicação.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Gjm7WIH33e_qLkoI.png" /></figure><p>Essa interação é responsável por salvar o valor do saldo no servidor C2 do malware. Essa será a requisição que o malware executará, passando os valores em formato JSON.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/0*O5QWhSYjZHM4f-dk.png" /></figure><p>A seguir, o malware realiza outra interação com a classe C2C. Nessa requisição, o malware envia o valor do saldo da conta da vítima, o nome do banco da vítima e um ID associado ao dispositivo da vítima.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/0*BbyLcZnj5esTRwec.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/0*_RONnyfjPkWFM0Wj.png" /></figure><p>Além de tudo isso, o malware possui um arquivo para armazenar as credenciais do usuário, como mencionado em uma das imagens acima.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/0*weB_8_i8QNwZn9w9.png" /></figure><p>Novamente fazendo uso da acessibilidade o malware filtra os eventos de acordo com cada banco e inicia o processo de salvar as credenciais do usuario.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tTWmSwaLnzVWJoWU.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kQHbe8dDl5L3GkJF.png" /></figure><p>Na versão mais recente do malware foi implementada uma nova função para WebSocket, porém ainda não parei para analisar bem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/0*vypF0mfjueIUcqIg.png" /><figcaption>WebSocket</figcaption></figure><h3>Credenciais HardCoded</h3><pre>user:logy password:qwertyuiop </pre><pre>user:logz password:4ddc69691</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dhq15DD5wmqowIHf.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/0*_gzabkIUCx6TXG9x.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/0*_oKD92_UOJrY8FzN.png" /></figure><h3>Servidores</h3><p>Analisando as requisições do malware, foi possível obter o servidor de atualizações que é utilizado para obter a versão mais recente do código JavaScript.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JcmyForOONlFzoIK.png" /></figure><p>O endereço “ <a href="https://down883%5B.%5Doss-us-east-1%5B.%5Daliyuncs%5B.%5Dcom">https://down883[.]oss-us-east-1[.]aliyuncs[.]com</a>&quot; é utilizado para o versionamento do código JavaScript. Analisando essas versões, podemos ver que o malware está em constante atualização.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/0*mX_1h9ygeSFnozxn.png" /></figure><p>Sendo a mais recente de 22 de fevereiro de 2023, a mais antiga que consegui acesso foi de 25 de novembro de 2022. O malware também utiliza alguns servidores Elasticsearch para gravar alguns logs de uso de cada dispositivo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xJGVedhVndiTbNVs.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/0*VQt08XZHKD0uRV8A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/0*5Sz38Vjv3buJQxJ3.png" /></figure><ul><li>camera[.]applebalanyou[.]com</li><li>orange[.]applebalanyou[.]com</li><li>wc[.]werichcash[.]com</li></ul><p>Servidor C2, utilizado para obter informações de pagamentos, salvar dados e interagir com o dispositivo infectado pelo malware.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JP-DVnh99j9v2Xzr.png" /></figure><p>O endereço desse servidor é atualizado dinamicamente pela aplicação, que recebe o endereço e salva no “prefs” do dispositivo junto com algumas outras informações. Então, esse valor sempre tem alguma atualização.</p><p>Abaixo estão algumas versões que já foram usadas:</p><p>Também foi possível obter acesso aos dados de transações salvos no C2. Foi observada uma quantidade expressiva de transações salvas, um total de 33.127 até a data de hoje.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/0*F6zVpj8ceZVXIEwf.png" /></figure><h3>Links</h3><ul><li>Malware: <a href="https://bazaar.abuse.ch/sample/911fa473f75d48e28384023b4a008d6d0877ad0fa58f9ebf38da1b02a1481314/">https://bazaar.abuse.ch/sample/911fa473f75d48e28384023b4a008d6d0877ad0fa58f9ebf38da1b02a1481314/</a></li><li>JADX: <a href="https://github.com/skylot/jadx">https://github.com/skylot/jadx</a></li></ul><p><em>Originally published at </em><a href="https://gist.github.com/thalysonsousa/d9c4d5d4ed684b2d14569b92efcd087b"><em>http://github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b53927159bc3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dicas para análise de código ofuscado]]></title>
            <link>https://medium.com/@thalysonz/dicas-para-an%C3%A1lise-de-c%C3%B3digo-obfuscado-ed3edd5e7913?source=rss-e26bcce559d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed3edd5e7913</guid>
            <dc:creator><![CDATA[Thalyson Sousa]]></dc:creator>
            <pubDate>Thu, 23 Feb 2023 03:18:58 GMT</pubDate>
            <atom:updated>2023-12-29T13:44:35.445Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GWZv7nO5EqwGKzWNLJCJ8Q.jpeg" /></figure><p>Finalizei minha análise estática no código do malware PixPirate. Uma parte significativa desse período foi dedicada a desofuscar os arquivos JavaScript utilizados pelo malware, que se empenhou bastante em dificultar a análise por parte de terceiros.</p><p>Como pode ser visto nas imagens abaixo, todos os arquivos presentes em <em>*”project.zip”*</em>, que é executado pelo malware usando o AutoJS (ferramenta responsável por cuidar da automação JS), estão ofuscados. Então, decidi aproveitar que estou focado nisso e trazer algumas dicas que podem ajudar caso vocês se deparem com algum código JavaScript obfuscado de agora em diante.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*H1U5znQyzgslZECB.png" /><figcaption>Main.Js</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oUI_Jx6F-fhbsqff.png" /><figcaption>BrazilBank.Js</figcaption></figure><p>A ofuscação de código é o processo de torná-lo menos legível para humanos. Ela complica a compreensão das funcionalidades do código, dificultando a sua cópia ou alteração. Isso é alcançado por meio da aplicação de técnicas de ofuscação, que englobam a renomeação de variáveis, modificação da estrutura do código, inserção de código desnecessário ou irrelevante e a remoção de comentários.</p><p>Nosso trabalho aqui é tornar esse código acima legível novamente, para que possamos entender como o <em>*malware*</em> atua. Então, vamos lá.</p><h3>1<strong>. Formatando o código</strong></h3><p>Nas imagens acima, os três arquivos estão basicamente ilegíveis. Porém, formatar ou reestruturar o código já ajudaria muito nosso processo, pois assim conseguimos identificar onde função termina ou começa, separar funções, e assim, facilitar os próximos passos.</p><p>Abaixo, segue um exemplo de um dos arquivos antes e depois da formatação.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eSw5f1W4ejdxkLib.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VbPWBj-w8vcsHB95.png" /></figure><h3>2. <strong>Alterando os nomes</strong></h3><p>O próximo passo será alterar os nomes das funções / classes / variáveis / interfaces (ou seja lá o que encontrarmos pela frente) de algo estranho para algo que possamos facilmente identificar.</p><p>No exemplo a seguir, apresentamos algumas variáveis, constantes e funções, entre outros elementos, com nomes em hexadecimal ou valores aleatórios, visando dificultar a compreensão do código.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*r3KG0kugsPm4OZyjCcQ3eA.png" /></figure><p>Aqui temos uma função que basicamente retorna um array de strings, então vamos começar alterando o nome da função de a1_0x13b5 para mw_FunctionReturnStrings. No <strong>**VS CODE**</strong> apertando o botão direito do mouse e depois “Change all references”, alteramos todas as referências a essa função.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*PPkedJg0CioISgRWsfWORA.png" /></figure><p>Podemos seguir renomeando o código de acordo com seu funcionamento e vamos ter algo como as imagens abaixo no final.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*LW_Ol5LGvj5QS0bGZooZ2A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*vn9Abi_ECIKsHzwah_tBYA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*psNRDAaco-Jt1QcY.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/0*ozB6hWO2b4SMg_qK.png" /></figure><h3><strong>3. Entendendo o código</strong></h3><p>Agora que temos um código legível só precisamos entender o que todo esse código está fazendo. Para isso, podemos seguir as chamadas de funções pela aplicação. Na imagem abaixo, utilizei o [playcode.io](https://playcode.io) para visualizar o resultado da chamada desse array, que é um elemento importante desse código.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tehhaJXOk_vtyXF17CnHvg.png" /></figure><h3>4. Fluxo da aplicação</h3><p>Este é um processo demorado em que você vai juntar tudo o que foi escrito aqui e tentar entender o fluxo como um todo, percebendo que um arquivo pode chamar outro arquivo e assim por diante. Em alguns casos, vamos encontrar código que é apenas lixo, afinal estamos falando de ofuscação. Mas com as dicas acima, todo o entendimento dos próximos arquivos ofuscados que você pegar será mais fácil.</p><p>Na imagem abaixo demonstro o final do nosso código JS, onde basicamente todo este código foi usado para chamar o arquivo “permission/empower.js”. Assim, demonstro que saímos de algo ilegível para um código muito mais legível e conseguimos entender o fluxo que a aplicação faz com este código. Agora, só precisamos fazer isso com o restante do código.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CsffVrvvv_vRJ9NB.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed3edd5e7913" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>