<?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 Myth on Medium]]></title>
        <description><![CDATA[Stories by Myth on Medium]]></description>
        <link>https://medium.com/@myth7672?source=rss-0f351da37421------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MjAKsfS3Lq3ePowDikLR8w.png</url>
            <title>Stories by Myth on Medium</title>
            <link>https://medium.com/@myth7672?source=rss-0f351da37421------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 06:25:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@myth7672/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[How Machine Learning Detects Unusual File Modifications on Your System]]></title>
            <link>https://medium.com/@myth7672/how-machine-learning-detects-unusual-file-modifications-on-your-system-7e1d1d45021e?source=rss-0f351da37421------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e1d1d45021e</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[information-security]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Myth]]></dc:creator>
            <pubDate>Fri, 28 Nov 2025 13:30:40 GMT</pubDate>
            <atom:updated>2025-11-28T13:30:40.169Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Objective :</strong></p><p>To create a smart file monitoring system that:</p><ol><li>Tracks file changes in real time.</li><li>Labels file importance using rule-based AI logic.</li><li>Applies Machine Learning (KMeans Clustering) to detect unusual file behavior based on change time and file type.</li><li>Generates alerts for critical anomalies and visualizes data.</li><li>Demonstrates AI + ML usage to assist blue teams in daily incident response.</li></ol><h4><strong>Tools Required:</strong></h4><ol><li>Python 3.10+</li></ol><p>2. Libraries:</p><ul><li>watchdog → to detect real-time filesystem changes (AI logic trigger)</li><li>pandas → for data handling</li><li>scikit-learn → for ML clustering (unsupervised anomaly detection)</li><li>matplotlib → for anomaly visualization</li></ul><p><strong>Prerequisites:</strong></p><ul><li>Python and pip must be installed.</li><li>Folder path: D:\ai &amp; ml\test\monitored_files</li><li>Add some test files: .txt, .py, .config, .ini, etc.</li><li>Install required libraries:</li></ul><p><strong>Command :</strong></p><p>pip install watchdog pandas scikit-learn matplotlib</p><h4>Step 1: Mock File Creation Logic (Real-World Simulation)</h4><p>In real organizations:</p><ul><li>Applications, configuration files, and secrets change often.</li><li>Hackers may also change these files to do bad things.</li><li>So, <strong>we need to monitor file changes</strong> to spot suspicious behavior.</li></ul><p>But in our practice PoC, we don’t have a real company system running.</p><p>So we simulate it by <strong>creating and modifying some fake files</strong> in a folder.</p><p>It gives us sample data to test file monitoring and understand which file is important.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*NJ6VsLzAN9YFtWdgZuB7rA.png" /></figure><p>If these get changed at <strong>odd times</strong> (like 3 AM), or too frequently, we may <strong>detect a possible threat</strong>.</p><h4>Step 2 : Real-Time Monitoring Script (file_monitor.py)</h4><p>→ Detect any changes to files and save a log.</p><p>→ Real-time logging is the first requirement of any forensic monitoring system. This lets you know “what changed when” — just like an audit tool.</p><p>→ Uses watchdog to detect file changes instantly</p><p>→ Labels each file:</p><ul><li>config, secret → critical</li><li>.py, .sh → sensitive</li><li>Others → low</li></ul><p>→ Also calculates SHA-256 hash of file content</p><p>→ Saves everything to file_changes.csv</p><p><strong>Code :</strong></p><pre>import time<br>import hashlib<br>import pandas as pd<br>from watchdog.observers import Observer<br>from watchdog.events import FileSystemEventHandler<br>from datetime import datetime<br>import os<br># Set correct folder path<br>monitored_folder = r&quot;D:\ai &amp; ml\test\monitored_files&quot;<br>log_file = os.path.join(monitored_folder, &quot;file_changes.csv&quot;) # Save CSV in same folder<br># Function to calculate hash<br>def get_sha256(path):<br>try:<br>with open(path, &quot;rb&quot;) as f:<br>return hashlib.sha256(f.read()).hexdigest()<br>except:<br>return &quot;DELETED&quot;<br># File classification logic<br>def classify_file(path):<br>if &quot;config&quot; in path.lower() or &quot;secret&quot; in path.lower():<br>return &quot;critical&quot;<br>elif path.endswith(&quot;.py&quot;) or path.endswith(&quot;.sh&quot;):<br>return &quot;sensitive&quot;<br>else:<br>return &quot;low&quot;<br># Store log entries<br>log_data = []<br># Watchdog event handler<br>class ChangeHandler(FileSystemEventHandler):<br>def on_modified(self, event):<br>if not event.is_directory:<br>filepath = event.src_path<br># ✅ Skip logging if the file being modified is the log file itself<br>if os.path.abspath(filepath) == os.path.abspath(log_file):<br>return<br>hash_val = get_sha256(filepath)<br>label = classify_file(filepath)<br>timestamp = datetime.now().strftime(&quot;%Y-%m-%d %H:%M:%S&quot;)<br>print(f&quot;[+] Modified: {filepath}&quot;)<br>log_data.append({<br>&quot;timestamp&quot;: timestamp,<br>&quot;file&quot;: filepath,<br>&quot;label&quot;: label,<br>&quot;sha256&quot;: hash_val<br>})<br># Save log<br>df = pd.DataFrame(log_data)<br>df.to_csv(log_file, index=False)<br>print(f&quot;[✔] Logged to: {log_file}&quot;)<br># Start observer<br>observer = Observer()<br>handler = ChangeHandler()<br>observer.schedule(handler, monitored_folder, recursive=True)<br>observer.start()<br>print(f&quot;[✓] Monitoring folder: {monitored_folder}&quot;)<br>print(&quot;[⌛] Keep this window open. Press Ctrl+C to stop.&quot;)<br>try:<br>while True:<br>time.sleep(1)<br>except KeyboardInterrupt:<br>observer.stop()<br>observer.join()<br>print(&quot;[✔] Monitoring stopped.&quot;)</pre><p><strong>AI-style logic used here:</strong></p><ul><li><strong>critical</strong>: System files, secrets.</li><li><strong>sensitive</strong>: Scripts or potentially executable logic.</li><li><strong>low</strong>: Notes, README, docs.</li></ul><p><strong>Key Functions:</strong></p><ul><li>watchdog detects file change</li><li>SHA-256 hash verifies content change</li><li>Appends details to file_changes.csv</li></ul><p><strong>Run this:</strong></p><p><strong>Command :</strong></p><p>python file_monitor.py</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*oWK6dDKwcy8ZlpzJh1VyJA.png" /></figure><p>→ Keep the terminal open. Now go and modify any file in monitored_files. It will log changes instantly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*lSmoVz40B80aOmEc41kQRA.png" /></figure><p>→ go back to you vs code and check run code again you can see alert is generated after modifying file and csv file also generated with information.</p><p>→ Output: file_changes.csv</p><p>→ Output: file_changes.csv with columns: timestamp, file path, file label, sha256</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EsIbKqLJm7p4-zxVApdtYw.png" /></figure><h4>Step 3: (Optional) Generate Fake Logs for ML Testing</h4><ul><li>Adds 5 fake logs with different times and file types</li><li>To test machine learning without waiting for real-time file changes.</li><li>Adds realistic-looking file changes to the CSV so we can test the next steps.</li></ul><p><strong>Script :</strong></p><p>mock_file_data_generator.py</p><pre>import pandas as pd<br>from datetime import datetime, timedelta<br>import random<br># Path to existing log file<br>csv_file = r&quot;D:\ai &amp; ml\test\monitored_files\file_changes.csv&quot;<br># Labels and fake files<br>labels = [&quot;low&quot;, &quot;sensitive&quot;, &quot;critical&quot;]<br>files = [<br>r&quot;D:\ai &amp; ml\test\monitored_files\notes.txt&quot;,<br>r&quot;D:\ai &amp; ml\test\monitored_files\config.ini&quot;,<br>r&quot;D:\ai &amp; ml\test\monitored_files\app.py&quot;,<br>r&quot;D:\ai &amp; ml\test\monitored_files\secret_keys.txt&quot;,<br>r&quot;D:\ai &amp; ml\test\monitored_files\readme.md&quot;<br>]<br># Generate timestamps<br>now = datetime.now()<br>timestamps = [now - timedelta(hours=i*2) for i in range(5)]<br># SHA256 placeholders<br>fake_hash = lambda: &#39;&#39;.join(random.choices(&quot;abcdef1234567890&quot;, k=64))<br># Create fake rows<br>mock_data = []<br>for i in range(5):<br>mock_data.append({<br>&quot;timestamp&quot;: timestamps[i].strftime(&quot;%Y-%m-%d %H:%M:%S&quot;),<br>&quot;file&quot;: files[i],<br>&quot;label&quot;: labels[i % 3],<br>&quot;sha256&quot;: fake_hash()<br>})<br># Load existing or create new DataFrame<br>try:<br>df = pd.read_csv(csv_file)<br>except:<br>df = pd.DataFrame(columns=[&quot;timestamp&quot;, &quot;file&quot;, &quot;label&quot;, &quot;sha256&quot;])<br># Append mock data and save<br>df = pd.concat([df, pd.DataFrame(mock_data)], ignore_index=True)<br>df.to_csv(csv_file, index=False)<br>print(&quot;[✔] 5 fake entries added to:&quot;, csv_file)</pre><p><strong>Run this once:</strong><br>Command :</p><p>python mock_file_data_generator.py</p><ul><li>Add 5 realistic-looking rows to file_changes.csv</li><li>With different timestamps and labels (low, sensitive, critical)</li></ul><h4>Step 4 : [Optional Debug] Initial ML Clustering Test (anomaly_detector.py)</h4><p><strong>Help us visualize ML logic before integrating fully.</strong></p><p>To check if ML can group normal vs unusual file changes based on time and file type.</p><h4>How it works:</h4><ul><li>Reads file_changes.csv</li><li>Uses ML algorithm KMeans</li><li>Features: Time of change (hour) + file label</li><li>Groups changes into 2 clusters</li><li>Saves a visual plot cluster_plot.png</li><li>Extracts hour and label type (encoded)</li></ul><h4>Code :</h4><pre>import pandas as pd<br>from sklearn.cluster import KMeans<br>import matplotlib.pyplot as plt<br># Load the correct CSV file<br>df = pd.read_csv(r&quot;D:\ai &amp; ml\test\monitored_files\file_changes.csv&quot;)<br># Parse timestamps<br>df[&quot;timestamp&quot;] = pd.to_datetime(df[&quot;timestamp&quot;], errors=&#39;coerce&#39;)<br>df[&quot;hour&quot;] = df[&quot;timestamp&quot;].dt.hour<br># Convert labels to numbers<br>df[&quot;label_encoded&quot;] = df[&quot;label&quot;].map({&quot;critical&quot;: 2, &quot;sensitive&quot;: 1, &quot;low&quot;: 0})<br># Prepare features for clustering<br>features = df[[&quot;hour&quot;, &quot;label_encoded&quot;]].dropna()<br># Run KMeans clustering<br>kmeans = KMeans(n_clusters=2, random_state=42)<br>df[&quot;cluster&quot;] = kmeans.fit_predict(features)<br># Plot the clustering result<br>plt.scatter(df[&quot;hour&quot;], df[&quot;label_encoded&quot;], c=df[&quot;cluster&quot;], cmap=&quot;coolwarm&quot;)<br>plt.xlabel(&quot;Hour of Change&quot;)<br>plt.ylabel(&quot;File Label (critical=2)&quot;)<br>plt.title(&quot;Anomaly Clustering of File Changes&quot;)<br>plt.savefig(r&quot;D:\ai &amp; ml\test\monitored_files\cluster_plot.png&quot;)<br>plt.show()<br># Count cluster sizes<br>cluster_counts = df[&quot;cluster&quot;].value_counts()<br># Assume: Smaller cluster = anomaly (less frequent pattern)<br>anomaly_cluster = cluster_counts.idxmin()<br># Mark anomaly status<br>df[&quot;anomaly&quot;] = df[&quot;cluster&quot;].apply(lambda x: &quot;anomaly&quot; if x == anomaly_cluster else &quot;normal&quot;)<br># Save updated CSV<br>df.to_csv(r&quot;D:\ai &amp; ml\test\monitored_files\file_changes_clustered.csv&quot;, index=False)<br># Optional: Print counts<br>print(&quot;\nCluster Summary:&quot;)<br>print(df[&quot;anomaly&quot;].value_counts())</pre><p><strong>Output:</strong></p><p>It shows a colored graph and adds a new column to CSV: which entry is “normal” and which is “anomaly”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*DfufBpTh8qoHFYaAZMEdpA.png" /></figure><p><strong>cluster_plot.png was generated.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*iLENvRYBGvlidze9J4IHJg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*Ln8jKrP1ExQPz4NPLiwYAA.png" /></figure><p>This step is a test run only and can be skipped in real automation.</p><h4>Step 5 : Final Anomaly Detection Logic (smart_file_anomaly_detector.py)</h4><p>To automatically alert if risky files like config or secret files are changed at odd times.</p><p><strong>Script file:</strong> smart_file_anomaly_detector.py</p><p>→ Loads the full CSV</p><p>→ Uses KMeans again to detect strange behavior</p><p>→ If any <strong>critical file</strong> is marked as anomaly, show <strong>ALERT</strong></p><p>→ Creates final graph (cluster_plot.png) and output file (file_changes_clustered.csv)</p><p><strong>How ML is used here (unsupervised):</strong></p><ul><li>Feature 1: Time (hour) of change</li><li>Feature 2: File label (encoded as 0/1/2)</li><li>Algorithm: KMeans(n_clusters=2)</li><li>Label the smaller cluster as “anomaly”</li></ul><p><strong>Code :</strong></p><pre>import pandas as pd<br>from sklearn.cluster import KMeans<br>import matplotlib.pyplot as plt<br>import os<br># - - - - - - STEP 1: LOAD CSV FILE - - - - - -<br># Why: To load past file change logs for analysis<br>csv_path = r&quot;D:\ai &amp; ml\test\monitored_files\file_changes.csv&quot;<br>if not os.path.exists(csv_path):<br>print(&quot;❌ file_changes.csv not found. Run file_monitor.py first.&quot;)<br>exit()<br>df = pd.read_csv(csv_path)<br># - - - - - - STEP 2: CLEAN &amp; PREPARE DATA - - - - - -<br># Convert timestamp strings to datetime<br>df[&quot;timestamp&quot;] = pd.to_datetime(df[&quot;timestamp&quot;], errors=&#39;coerce&#39;)<br># Extract &#39;hour&#39; of the day from timestamp for pattern recognition<br>df[&quot;hour&quot;] = df[&quot;timestamp&quot;].dt.hour<br># Convert label text to numeric for clustering<br># Reason: ML algorithms need numerical input<br>label_map = {&quot;low&quot;: 0, &quot;sensitive&quot;: 1, &quot;critical&quot;: 2}<br>df[&quot;label_encoded&quot;] = df[&quot;label&quot;].map(label_map)<br># Drop any rows with missing values (e.g., broken timestamps)<br>features = df[[&quot;hour&quot;, &quot;label_encoded&quot;]].dropna()<br># - - - - - - STEP 3: RUN KMeans CLUSTERING - - - - - -<br># Why: To group similar patterns and detect unusual ones (anomalies)<br># Decision: 2 clusters (normal vs anomaly)<br>if len(features) &lt; 2:<br>print(&quot;⚠️ Not enough data for clustering. Need at least 2 entries.&quot;)<br>exit()<br>kmeans = KMeans(n_clusters=2, random_state=42)<br>df[&quot;cluster&quot;] = kmeans.fit_predict(features)<br># - - - - - - STEP 4: DETECT ANOMALIES - - - - - -<br># Decision: Assume smaller cluster = anomaly<br>cluster_counts = df[&quot;cluster&quot;].value_counts()<br>anomaly_cluster = cluster_counts.idxmin() # smallest cluster = anomaly<br># Mark anomaly column<br>df[&quot;anomaly&quot;] = df[&quot;cluster&quot;].apply(lambda x: &quot;anomaly&quot; if x == anomaly_cluster else &quot;normal&quot;)<br># - - - - - - STEP 5: ALERT FOR CRITICAL FILE ANOMALIES - - - - - -<br># Why: If critical files fall under anomaly cluster, raise alert<br>critical_anomalies = df[(df[&quot;label&quot;] == &quot;critical&quot;) &amp; (df[&quot;anomaly&quot;] == &quot;anomaly&quot;)]<br>if not critical_anomalies.empty:<br>print(&quot;\n🚨 ALERT: Critical file changes detected as anomalies!&quot;)<br>print(critical_anomalies[[&quot;timestamp&quot;, &quot;file&quot;, &quot;label&quot;]])<br>else:<br>print(&quot;\n✅ No critical file anomalies detected.&quot;)<br># - - - - - - STEP 6: VISUALIZE CLUSTERS - - - - - -<br># Plot hour vs label, color by anomaly status<br>colors = df[&quot;anomaly&quot;].map({&quot;normal&quot;: &quot;blue&quot;, &quot;anomaly&quot;: &quot;red&quot;})<br>plt.figure(figsize=(8,6))<br>plt.scatter(df[&quot;hour&quot;], df[&quot;label_encoded&quot;], c=colors)<br>plt.title(&quot;File Change Anomaly Clustering&quot;)<br>plt.xlabel(&quot;Hour of Change (0–23)&quot;)<br>plt.ylabel(&quot;File Criticality (0=low, 2=critical)&quot;)<br>plt.grid(True)<br>plt.savefig(r&quot;D:\ai &amp; ml\test\monitored_files\cluster_plot.png&quot;)<br>plt.show()<br>print(&quot;\n📁 cluster_plot.png saved.&quot;)<br># - - - - - - STEP 7: SAVE FINAL OUTPUT - - - - - -<br>df.to_csv(r&quot;D:\ai &amp; ml\test\monitored_files\file_changes_clustered.csv&quot;, index=False)<br>print(&quot;✅ file_changes_clustered.csv saved with anomaly labels.&quot;)</pre><ol><li>Reads file_changes.csv</li><li>Extracts relevant features</li><li>Runs KMeans(n_clusters=2)</li><li>Labels the smaller cluster as “anomaly”</li><li>Flags if any critical files are in anomaly zone</li></ol><p><strong>Final Output:</strong></p><ul><li>file_changes_clustered.csv with anomaly column</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*AWhgL1LNWMkm1r3lMwPK5A.png" /></figure><ul><li>Updated cluster_plot.png</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*BZmSCRZgKOgQuOt6uT8EQQ.png" /></figure><p>Notify analyst if a critical file shows anomalous behavior</p><p>Saves final result with anomaly labels and alerts security team if something suspicious is found.</p><p><strong>Logic:</strong></p><p>Helps analysts know if immediate review is needed.</p><h4>Final Deliverables</h4><ul><li>file_changes.csv → with AI-based risk labels</li><li>file_changes_clustered.csv → with ML-based anomaly labels</li><li>cluster_plot.png → graphical anomaly visualization</li><li>Console alerts → triggers if anomalies involve <strong>critical files</strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e1d1d45021e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using AI & ML to Hunt Malicious Process Behavior on Windows]]></title>
            <link>https://medium.com/@myth7672/using-ai-ml-to-hunt-malicious-process-behavior-on-windows-897182fda941?source=rss-0f351da37421------2</link>
            <guid isPermaLink="false">https://medium.com/p/897182fda941</guid>
            <category><![CDATA[mls]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[projects]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[Myth]]></dc:creator>
            <pubDate>Fri, 28 Nov 2025 13:04:56 GMT</pubDate>
            <atom:updated>2025-11-28T13:04:56.023Z</atom:updated>
            <content:encoded><![CDATA[<h4>The goal of this project is to <strong>build an AI and machine learning-based system</strong> that can detect <strong>anomalous (suspicious) process activity</strong> on Windows systems.</h4><h4>Objective:</h4><ul><li>Unlike traditional models that focused on <strong>user logon patterns</strong> or <strong>process tree structures</strong>, this system analyzes the <strong>sequential runtime behavior of individual processes</strong>.</li></ul><ol><li>It processes <strong>structured event log records</strong> that contain:</li></ol><ul><li>CPU usage</li><li>Memory access</li><li>Parent-child process relationships</li><li>Execution context (such as user or privilege level)</li><li>Timestamp and runtime sequence</li></ul><p>2. The system uses <strong>AI to learn normal behavior patterns</strong> from this process data and identify <strong>abnormal (anomalous) behavior</strong> without using fixed rules.</p><p>3. Each process event is passed through a <strong>trained ML classifier</strong> that predicts whether the event is:</p><ul><li>“Normal”</li><li>“Anomalous”</li></ul><p>4. This AI-based approach helps in detecting <strong>unknown or novel threats</strong> that do not match predefined signatures.</p><p>5. The system outputs:</p><ul><li>A <strong>labeled CSV file</strong> showing predictions for each event</li><li>A <strong>visual anomaly trend chart</strong> to help incident response teams spot suspicious patterns over time</li></ul><p>6. The system uses <strong>synthetic process activity data</strong> that closely mimics real-world environments to ensure realistic training and testing.</p><p>7. The data format used aligns with the <strong>CERT Insider Threat Dataset</strong>, making the solution more applicable to real-world scenarios.</p><p>8. Overall, the use of AI allows for <strong>automated, faster, and smarter detection</strong> of process-based threats on Windows systems.</p><h4><strong>Tools Required:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*ELxu2hxkU5ScYgWeieK-gg.png" /></figure><h4><strong>Prerequisites:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*Wbj31Xr2gcWSlAZjNsaizw.png" /></figure><h4>AI/ML Inclusion Workflow:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*v7z5L3QkobBOONtnLoTFFw.png" /></figure><h4>Use Case Scenario</h4><p>System administrators want to detect potentially malicious or misbehaving processes running on endpoints in real-time. These include unexpected scripts, renamed executables, or system processes behaving abnormally (e.g., sudden high CPU use, wrong parent process, wrong run path).</p><p>This system uses logs collected via Windows event monitoring (or WMI monitoring) and analyzes behaviors to predict whether each process event is benign or suspicious.</p><h4>Actors</h4><ul><li><strong>Malicious Process</strong>: A rogue process that pretends to be legitimate but shows abnormal behavior like running from temp folders, high CPU, wrong parent, etc.</li><li><strong>Legitimate Process</strong>: Common, well-behaved system or application process.</li><li><strong>ML Model</strong>: Trained to detect process anomalies from observed metrics.</li><li><strong>Security Analyst</strong>: Reviews flagged events for deeper threat hunting.</li></ul><h4>Folder Structure:</h4><p>process_anomaly_ai_ml/</p><p>├── dataset/</p><p>│ └── process_events.csv # Raw or synthetic process event logs</p><p>├── train_model.py # Model training script</p><p>├── analyze_stream.py # Run predictions on new stream</p><p>├── models/</p><p>│ ├── process_classifier.pkl # Trained model</p><p>│ ├── encoder_Process_Name.pkl</p><p>│ ├── encoder_Parent_Process.pkl</p><p>│ └── encoder_Label.pkl</p><p>├── output/</p><p>│ └── labeled_event_stream.csv # Inference output</p><p>├── visuals/</p><p>│ └── feature_importance.png # Plot of top contributing features</p><p>├── requirements.txt</p><h4>Step 1 : Downloading &amp; Using the Dataset</h4><ul><li><strong>Option A</strong>: Use the publicly available<a href="https://www.kaggle.com/datasets/mrajaxnp/cert-insider-threat-detection-research?select=file.csv"> <strong>CERT Insider Threat Dataset</strong> </a>hosted on Kaggle, which contains detailed logs of user activity such as logons, file transfers, emails, and removable media usage.</li><li><strong>Option B</strong>: Create a <strong>synthetic dataset</strong> that mimics the structure and behavior patterns of the CERT data.</li></ul><p>However, due to the <strong>large size</strong>, <strong>complexity</strong>, and <strong>sensitivity</strong> of Option A, we opted for <strong>Option B</strong> — a smaller, manageable synthetic dataset. This version includes <strong>1000 realistically structured entries</strong> simulating user process and file interaction behavior.</p><p>This approach offers:</p><ul><li>Faster training and testing without system overhead</li><li>A clean demonstration of the model logic and AI/ML pipeline</li><li>Easy replacement with real-world data when scaling the solution</li></ul><p>We are using <strong>Option B</strong> in this implementation. The synthetic dataset is stored at: dataset/sample_file_events.csv</p><h4>Step 2: Create a Train_model.py</h4><p>This script trains the AI/ML model to detect abnormal process activity. It converts raw process event data into numerical format, encodes all labels, and fits a classifier (like Random Forest) on the training set. From a blue team perspective, it helps build a behavior-based detection system that can flag suspicious or insider activities automatically — reducing noise and speeding up response.</p><p><strong>python train_model.py</strong></p><ul><li>Saves the trained model (process_classifier.pkl) and encoders to the models/ directory.</li><li>Generates a confusion matrix visualization in visuals/confusion_matrix.png.</li></ul><p><strong>SCRIPT : train_model.py</strong></p><pre>import pandas as pd<br>import os<br>import joblib<br>import seaborn as sns<br>import matplotlib.pyplot as plt<br>from sklearn.model_selection import train_test_split<br>from sklearn.preprocessing import LabelEncoder<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.metrics import classification_report, confusion_matrix<br># Load dataset<br>df = pd.read_csv(&quot;dataset/process_events.csv&quot;)<br># Drop rows with missing values in key columns<br>required_columns = [&#39;user&#39;, &#39;pc&#39;, &#39;filename&#39;, &#39;activity&#39;, &#39;to_removable_media&#39;,<br>&#39;from_removable_media&#39;, &#39;content&#39;, &#39;Label&#39;]<br>df.dropna(subset=required_columns, inplace=True)<br># Encode categorical features<br>categorical_cols = [&#39;user&#39;, &#39;pc&#39;, &#39;filename&#39;, &#39;activity&#39;, &#39;content&#39;]<br>encoders = {}<br>for col in categorical_cols:<br>le = LabelEncoder()<br>df[col] = le.fit_transform(df[col])<br>encoders[col] = le<br># Convert binary columns to integers<br>df[&#39;to_removable_media&#39;] = df[&#39;to_removable_media&#39;].astype(int)<br>df[&#39;from_removable_media&#39;] = df[&#39;from_removable_media&#39;].astype(int)<br># Encode target label<br>label_encoder = LabelEncoder()<br>df[&#39;Label_Code&#39;] = label_encoder.fit_transform(<br>df[&#39;Label&#39;]) # 0 = normal, 1 = anomalous<br># Define features and target<br>features = [&#39;user&#39;, &#39;pc&#39;, &#39;filename&#39;, &#39;activity&#39;,<br>&#39;to_removable_media&#39;, &#39;from_removable_media&#39;, &#39;content&#39;]<br>X = df[features]<br>y = df[&#39;Label_Code&#39;]<br># Split dataset<br>X_train, X_test, y_train, y_test = train_test_split(<br>X, y, test_size=0.2, stratify=y, random_state=42<br>)<br># Train model<br>clf = RandomForestClassifier(<br>n_estimators=100, class_weight=&#39;balanced&#39;, random_state=42)<br>clf.fit(X_train, y_train)<br># Evaluate<br>y_pred = clf.predict(X_test)<br>print(&quot;Classification Report:\n&quot;, classification_report(y_test, y_pred))<br># Save confusion matrix<br>cm = confusion_matrix(y_test, y_pred)<br>sns.heatmap(cm, annot=True, fmt=&#39;d&#39;, cmap=&#39;Blues&#39;)<br>plt.title(&quot;Confusion Matrix&quot;)<br>os.makedirs(&quot;visuals&quot;, exist_ok=True)<br>plt.savefig(&quot;visuals/confusion_matrix.png&quot;)<br>plt.close()<br># Save model and encoders<br>os.makedirs(&quot;models&quot;, exist_ok=True)<br>joblib.dump(clf, &quot;models/process_anomaly_classifier.pkl&quot;)<br>joblib.dump(label_encoder, &quot;models/encoder_Label.pkl&quot;)<br>for col, enc in encoders.items():<br>joblib.dump(enc, f&quot;models/encoder_{col}.pkl&quot;)<br>print(&quot;Model and encoders saved successfully.&quot;)</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*H5_Cm-pzxRu1e0503YoBOg.png" /></figure><p>This terminal output confirms the successful execution of train_model.py.</p><p>It shows a strong classification performance with high accuracy (99%), and reports precision, recall, and F1-scores for both normal and anomalous classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*sefXNLYmrLFNnJNrgspepw.png" /></figure><p>The trained model and encoders are saved to the models/ folder, while the confusion matrix visualization is stored in visuals/confusion_matrix.png.</p><p>The confusion matrix was automatically generated by the script train_model.py after training the model.</p><p>This matrix shows how well the machine learning model performed during testing. Each number in the grid represents how many samples were predicted correctly or incorrectly.</p><ul><li><strong>True Negatives (75)<br></strong> These are normal process events that were correctly identified as normal.</li><li><strong>False Positives (1)<br></strong> One normal process was incorrectly marked as anomalous. This is a false alarm.</li><li><strong>False Negatives (0)<br></strong> No actual anomalies were missed. This means the model caught all the threats.</li><li><strong>True Positives (124)<br></strong> These are real anomalous events that the model correctly detected.</li></ul><h4>What This Means</h4><ul><li>The model is highly accurate, with only one incorrect prediction out of 200.</li><li>No threats were missed, which is important for security.</li><li>The model does not raise too many false alerts, which helps reduce noise for analysts.</li></ul><h4>Step 3 : Create a Analyze_stream.py</h4><p><strong>Purpose of analyze_event_stream.py</strong></p><p>This script uses the trained AI/ML model to label new process event stream records as either <strong>“Normal”</strong> or <strong>“Anomalous”</strong>. It loads the saved encoders and models, processes the input event data, makes predictions, and saves results to a CSV and chart. From a blue team perspective, it automates alert generation and provides a quick visual insight into process behavior, helping defenders respond faster to real threats.</p><p><strong>Script : analyze_stream.py</strong></p><pre>import pandas as pd<br>import joblib<br>import os<br># Load the saved model and encoders<br>model = joblib.load(&quot;models/process_anomaly_classifier.pkl&quot;) # &lt;- fixed path<br>label_decoder = joblib.load(&quot;models/encoder_Label.pkl&quot;)<br>encoders = {<br>&quot;user&quot;: joblib.load(&quot;models/encoder_user.pkl&quot;),<br>&quot;pc&quot;: joblib.load(&quot;models/encoder_pc.pkl&quot;),<br>&quot;filename&quot;: joblib.load(&quot;models/encoder_filename.pkl&quot;),<br>&quot;activity&quot;: joblib.load(&quot;models/encoder_activity.pkl&quot;),<br>&quot;content&quot;: joblib.load(&quot;models/encoder_content.pkl&quot;)<br>}<br># Sample process event stream logs<br>samples = [<br># Normal office use<br>{&quot;user&quot;: &quot;john.smith&quot;, &quot;pc&quot;: &quot;PC-01&quot;, &quot;filename&quot;: &quot;chrome.exe&quot;, &quot;activity&quot;: &quot;execute&quot;,<br>&quot;to_removable_media&quot;: 0, &quot;from_removable_media&quot;: 0, &quot;content&quot;: &quot;browser&quot;},<br># Suspicious scripting activity by intern<br>{&quot;user&quot;: &quot;intern.james&quot;, &quot;pc&quot;: &quot;LAPTOP-07&quot;, &quot;filename&quot;: &quot;powershell.exe&quot;, &quot;activity&quot;: &quot;execute&quot;,<br>&quot;to_removable_media&quot;: 0, &quot;from_removable_media&quot;: 1, &quot;content&quot;: &quot;script&quot;},<br># Rare admin tool usage at endpoint<br>{&quot;user&quot;: &quot;sys.admin&quot;, &quot;pc&quot;: &quot;PC-45&quot;, &quot;filename&quot;: &quot;regedit.exe&quot;, &quot;activity&quot;: &quot;modify&quot;,<br>&quot;to_removable_media&quot;: 0, &quot;from_removable_media&quot;: 0, &quot;content&quot;: &quot;registry&quot;},<br># Highly malicious - fake tool moving data to USB<br>{&quot;user&quot;: &quot;unknown&quot;, &quot;pc&quot;: &quot;REMOTE-19&quot;, &quot;filename&quot;: &quot;ransomware.exe&quot;, &quot;activity&quot;: &quot;execute&quot;,<br>&quot;to_removable_media&quot;: 1, &quot;from_removable_media&quot;: 1, &quot;content&quot;: &quot;crypto_tool&quot;},<br># Developer writing scripts to USB - may be okay or abuse<br>{&quot;user&quot;: &quot;dev.sec&quot;, &quot;pc&quot;: &quot;DEV-MAC&quot;, &quot;filename&quot;: &quot;python.exe&quot;, &quot;activity&quot;: &quot;write&quot;,<br>&quot;to_removable_media&quot;: 1, &quot;from_removable_media&quot;: 0, &quot;content&quot;: &quot;script&quot;},<br># Accountant opening spreadsheet - common<br>{&quot;user&quot;: &quot;finance.raj&quot;, &quot;pc&quot;: &quot;ACCT-09&quot;, &quot;filename&quot;: &quot;excel.exe&quot;, &quot;activity&quot;: &quot;read&quot;,<br>&quot;to_removable_media&quot;: 0, &quot;from_removable_media&quot;: 0, &quot;content&quot;: &quot;spreadsheet&quot;},<br># IT tool writing directly to USB - audit needed<br>{&quot;user&quot;: &quot;it.support&quot;, &quot;pc&quot;: &quot;NOC-12&quot;, &quot;filename&quot;: &quot;diskutil.exe&quot;, &quot;activity&quot;: &quot;write&quot;,<br>&quot;to_removable_media&quot;: 1, &quot;from_removable_media&quot;: 0, &quot;content&quot;: &quot;disk_manager&quot;},<br># Internal audit reading logs - expected<br>{&quot;user&quot;: &quot;internal.audit&quot;, &quot;pc&quot;: &quot;SEC-01&quot;, &quot;filename&quot;: &quot;logparser.exe&quot;, &quot;activity&quot;: &quot;read&quot;,<br>&quot;to_removable_media&quot;: 0, &quot;from_removable_media&quot;: 0, &quot;content&quot;: &quot;log_analysis&quot;},<br># HR using notepad on unknown device<br>{&quot;user&quot;: &quot;hr.neha&quot;, &quot;pc&quot;: &quot;UNKNOWN-PC&quot;, &quot;filename&quot;: &quot;notepad.exe&quot;, &quot;activity&quot;: &quot;modify&quot;,<br>&quot;to_removable_media&quot;: 0, &quot;from_removable_media&quot;: 0, &quot;content&quot;: &quot;text_edit&quot;},<br># Developer syncing suspicious DLL file via USB<br>{&quot;user&quot;: &quot;dev.tools&quot;, &quot;pc&quot;: &quot;DEV-05&quot;, &quot;filename&quot;: &quot;libinject.dll&quot;, &quot;activity&quot;: &quot;execute&quot;,<br>&quot;to_removable_media&quot;: 1, &quot;from_removable_media&quot;: 0, &quot;content&quot;: &quot;dll_injection&quot;}<br>]<br># Process the samples with encoders<br>processed = []<br>for entry in samples:<br>row = {}<br>for col in [&quot;user&quot;, &quot;pc&quot;, &quot;filename&quot;, &quot;activity&quot;, &quot;content&quot;]:<br>val = entry[col]<br>enc = encoders[col]<br>row[col] = enc.transform([val])[0] if val in enc.classes_ else 0<br>row[&quot;to_removable_media&quot;] = entry[&quot;to_removable_media&quot;]<br>row[&quot;from_removable_media&quot;] = entry[&quot;from_removable_media&quot;]<br>processed.append(row)<br># Create DataFrame and fix column order<br>X = pd.DataFrame(processed)<br>X = X[[&quot;user&quot;, &quot;pc&quot;, &quot;filename&quot;, &quot;activity&quot;,<br>&quot;to_removable_media&quot;, &quot;from_removable_media&quot;, &quot;content&quot;]]<br># Predict<br>predictions = model.predict(X)<br>decoded_labels = label_decoder.inverse_transform(predictions)<br># Merge predictions back into samples<br>for i, label in enumerate(decoded_labels):<br>samples[i][&quot;Prediction&quot;] = label<br>print(f&quot;[{i+1}] {samples[i]}&quot;)<br># Save output<br>os.makedirs(&quot;output&quot;, exist_ok=True)<br>pd.DataFrame(samples).to_csv(&quot;output/predicted_anomalies.csv&quot;, index=False)<br>print(&quot;Predictions saved to output/predicted_anomalies.csv&quot;)</pre><p><strong>Output:</strong><br>This script loads the trained model and encoders to analyze a fresh batch of process event logs:</p><p><strong>Output looks like,</strong></p><pre>[1] {&#39;user&#39;: &#39;john.smith&#39;, &#39;pc&#39;: &#39;PC-01&#39;, &#39;filename&#39;: &#39;chrome.exe&#39;, &#39;activity&#39;: &#39;execute&#39;, &#39;to_removable_media&#39;: 0, &#39;from_removable_media&#39;: 0, &#39;content&#39;: &#39;browser&#39;, &#39;Prediction&#39;: &#39;Normal&#39;}<br>[2] {&#39;user&#39;: &#39;intern.james&#39;, &#39;pc&#39;: &#39;LAPTOP-07&#39;, &#39;filename&#39;: &#39;powershell.exe&#39;, &#39;activity&#39;: &#39;execute&#39;, &#39;to_removable_media&#39;: 0, &#39;from_removable_media&#39;: 1, &#39;content&#39;: &#39;script&#39;, &#39;Prediction&#39;: &#39;Anomalous&#39;}</pre><p><strong>Output saved: (output/predicted_events.csv):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*i-XvTHI_tRsm6pKbYrpr0g.png" /></figure><p>The final “Prediction” column shows whether the event was marked <strong><em>Normal</em> or <em>Anomalous</em>.</strong></p><h4>Results &amp; Insights</h4><ul><li>The model successfully identifies anomalous process behaviors.</li><li>Misuse of parent process, execution from unusual paths, or high resource use contributes heavily to flagging anomalies.</li><li>Output CSV enables easy SOC integration or forensic review.</li><li>Visuals show model learning which features are most impactful.</li></ul><h4>Real-Time Implementation &amp; Use in Blue Team Operations:</h4><h4>How to Implement in Real-Time:</h4><p>To bring this AI+ML anomaly detection system into a real-time blue team setup, follow these steps:</p><ol><li><strong>Log Collection Agent<br></strong> Use agents like Sysmon, Wazuh, or OSQuery to collect live process execution logs from endpoints.</li><li><strong>Data Streaming Pipeline<br></strong> Set up a log shipper (e.g., Filebeat or NxLog) to forward data to a centralized log processor.</li><li><strong>Feature Extraction Module<br></strong> Deploy a lightweight script or microservice to convert the raw logs into the feature format required by the ML model (e.g., extracting CPU usage, timestamps, parent process).</li><li><strong>Real-Time Prediction with ML Model<br></strong> Integrate the trained insider_model.pkl into a live prediction service (using Flask/FastAPI) that listens for incoming data and responds with predictions.</li><li><strong>Alerting and Response<br></strong> If a process is flagged as “Anomalous”, generate an alert in the SIEM (e.g., Splunk, ELK, Graylog) and optionally trigger an automated response (e.g., kill the process, isolate the host).</li></ol><h4>Where to Use:</h4><ul><li><strong>Endpoint Detection &amp; Response (EDR)</strong> systems for process-level behavioral monitoring.</li><li><strong>SIEM enrichment</strong> to reduce false positives by filtering out routine or noise alerts.</li><li><strong>Incident Response Playbooks</strong> where automated risk classification helps prioritize alerts.</li><li><strong>SOC Dashboards</strong> to visualize behavioral deviations in process executions.</li></ul><h4>Outcome:</h4><ul><li>Implemented a real-world machine learning workflow focused on <strong>live-stream-style process activity</strong> rather than static datasets.</li><li>Detected <strong>anomalous behavior</strong> in processes based on runtime features like activity type, media access, and executable content.</li><li>Demonstrated a lightweight and efficient solution suitable for <strong>real-time endpoint monitoring</strong>.</li><li>Designed for seamless integration with tools like <strong>Sysmon, Task Scheduler</strong>, or <strong>custom process monitors</strong>.</li><li>Reduced false positives by learning normal patterns and flagging only meaningful deviations.</li><li>Provided actionable outputs, including <strong>labeled CSVs</strong> and <strong>visual insights</strong>, that help Blue Teams make faster decisions.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=897182fda941" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI + ML‑Based Insider Threat Detection via User Logon Patterns]]></title>
            <link>https://medium.com/@myth7672/ai-ml-based-insider-threat-detection-via-user-logon-patterns-6133945b50cf?source=rss-0f351da37421------2</link>
            <guid isPermaLink="false">https://medium.com/p/6133945b50cf</guid>
            <category><![CDATA[projects]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[blue-team]]></category>
            <category><![CDATA[cyber-security-projects]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[Myth]]></dc:creator>
            <pubDate>Mon, 17 Nov 2025 04:57:56 GMT</pubDate>
            <atom:updated>2025-11-17T04:57:56.734Z</atom:updated>
            <content:encoded><![CDATA[<h4>Objective:</h4><p>To develop a machine learning system that analyzes user logon event data to detect potential insider threats. The project extracts patterns — such as unusual login hours, uncommon devices or locations, and credential misuse — from logon records. By training a classifier on labeled historical data, the system flags anomalous logons, enabling SOC teams to prioritize investigation of suspicious user behavior efficiently.</p><h4>Tools Required:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*m1Rr1J_bcZh8_Q2FhpGcgg.png" /></figure><h4><strong>Prerequisites:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*QXiOMAKk7fcHE4Op1b_U_Q.png" /></figure><h4>AI/ML Inclusion Workflow:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*3twTgii5ryqCUB3eVNK8wA.png" /></figure><h4>1. Understanding Insider Threats in Modern Enterprises</h4><p><strong>1.1 Types of Insider Threats</strong></p><p>Insider threats aren’t limited to malicious employees. They fall into distinct categories:</p><ul><li><strong>Malicious Insiders</strong>: Employees or contractors who deliberately harm the organization for personal, financial, or political gain.</li><li><strong>Negligent Insiders</strong>: Users who inadvertently put systems at risk through poor password practices, falling for phishing scams, or mishandling data.</li><li><strong>Compromised Insiders</strong>: Legitimate user accounts that have been hijacked via stolen credentials or malware.</li></ul><p><strong>1.2 Impact of Insider Threats</strong></p><ul><li>Data breaches involving insiders cost organizations an average of <strong>$11.45 million per year</strong>, according to Ponemon Institute.</li><li>Insider threats can persist for months undetected, making them more dangerous than external attacks.</li><li>Breaches from insiders often involve access to the <strong>“crown jewels”</strong> of an enterprise — IP, customer data, and financials.</li></ul><p>1.3 Why Logon Patterns Matter</p><p>User logon patterns serve as a digital fingerprint. Unusual activity — like late-night access, logins from new geolocations, or use of rarely accessed servers — are often early signs of:</p><ul><li>Credential misuse</li><li>Privilege escalation</li><li>Data exfiltration preparation</li><li>Account compromise</li></ul><p>By monitoring and modeling these patterns with AI/ML, we can distinguish between benign anomalies and true insider threats.</p><p><strong>Use Case Scenario:</strong></p><p>A security operations team receives daily Active Directory or Windows logon events for users across corporate devices. They want an automated mechanism to flag logons that deviate significantly from historical behavior — such as remote access at unusual times, using devices not normally used by the user, or logons from unfamiliar subnets — indicating possible credential compromise, misuse, or insider threat.</p><p><strong>Actors:</strong></p><ul><li><strong>Insider threat actor</strong>: Legitimate user whose behavior deviates from norms — logging in at unusual hours, from unexpected locations or devices.</li><li><strong>Normal user</strong>: Employee with consistent logon patterns — workday hours, known devices, typical location.</li><li><strong>ML Model</strong>: Learns baseline patterns from labeled logon data and classifies future events.</li><li><strong>Security analyst</strong>: Reviews flagged events and determines if they represent real risk.</li></ul><h4>2. How This Solution Fits in a Blue Team Environment</h4><p><strong>2.1 Integration into the SOC Workflow:</strong></p><p>This project is designed with the Blue Team (defensive security) in mind. Here’s how it fits:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*qtbrNk2FmmnXcAOpqkPiVA.png" /></figure><p><strong>2.2 Compatibility with Existing Tools</strong></p><ul><li><strong>Log Format Agnostic</strong>: As long as logs are parsed to include timestamp, username, device, and location, the model can adapt.</li><li><strong>Lightweight Deployment</strong>: Can be run on a dedicated VM or container and scheduled as a cron job for periodic scanning.</li><li><strong>Integration Potential</strong>: Results can be fed back into a SIEM dashboard, ticketing system, or SOAR platform.</li></ul><p><strong>2.3 Example Use Case</strong></p><p>A user logs in from a new device at 3:20 AM from a foreign IP. The logon type is “RDP”. The ML model flags this as a likely insider threat. SOC is alerted and blocks the session within minutes.</p><h4>Folder Structure:</h4><p>insider_threat_logon_ai_ml/</p><p>├── train_model.py # Code to train the ML model</p><p>├── analyze_logon.py # Script to run inference on new data</p><p>├── requirements.txt # List of Python dependencies</p><p>├── dataset/</p><p>│ └── user_logon_events.csv # Logon events dataset</p><p>├── models/</p><p>│ ├── insider_classifier.pkl</p><p>│ ├── encoder_User.pkl</p><p>│ ├── encoder_Logon_Type.pkl</p><p>│ ├── encoder_Device.pkl</p><p>│ ├── encoder_Location.pkl</p><p>│ └── encoder_Label.pkl</p><p>├── output/</p><p>│ └── predicted_logons.csv # Inference results</p><p>└── visuals/</p><p>└── confusion_matrix.png # Evaluation plotted</p><h4>Step1: Downloading &amp; Using the Dataset</h4><p><strong>Option A:</strong> If you don’t have access to real logon data, you can generate synthetic records using the Faker library, or use public user behavior datasets if available. The expected file user_logon_events.csv should include:</p><ul><li>Username,</li><li>Logon_Time (ISO timestamp),</li><li>Logon_Type (e.g., Remote, RDP, Local),</li><li>Device_Name,</li><li>Location,</li><li>Failed_Attempts,</li><li>Privileged_Account (Yes/No),</li><li>Label (normal / insider).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*cwEv4vuIMHZxIYCp_Wy1Dw.png" /></figure><p><strong>Optional B ( Real Dataset ):<br></strong>For real-world data, the<a href="https://www.kaggle.com/datasets/dasgroup/rba-dataset"> RBA Dataset on Kaggle</a> offers over 3 million user behavior logs collected via Azure ATP from an enterprise network. It’s ideal for production-level threat hunting or advanced modeling.</p><p><strong>Why are not used real Dataset :<br></strong>Due to its massive size and complexity, it’s not practical for quick experimentation. For this project, we generated a smaller, lightweight dataset of 1000 entries using the Faker library to simulate realistic logon patterns for both normal and insider behavior. This keeps development faster and avoids overfitting.</p><h4>Step 2: Create train_model.py</h4><p><strong>Purpose of train_model.py</strong></p><p>This script trains a machine learning model to detect insider threats based on user logon patterns. It:</p><ul><li>Loads and cleans the dataset</li><li>Extracts and encodes features</li><li>Trains a Random Forest classifier</li><li>Evaluates the model using a confusion matrix</li><li>Saves the trained model and encoders for later use</li></ul><p><strong>SCRIPT : train_model.py</strong></p><pre>import pandas as pd<br>import os<br>import joblib<br>from sklearn.model_selection import train_test_split<br>from sklearn.preprocessing import LabelEncoder<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.metrics import classification_report, confusion_matrix<br>import seaborn as sns<br>import matplotlib.pyplot as plt<br># Load and preprocess dataset<br>df = pd.read_csv(&quot;dataset/user_logon_events.csv&quot;)<br>df = df.dropna(subset=[&quot;Username&quot;, &quot;Logon_Time&quot;, &quot;Logon_Type&quot;, &quot;Device_Name&quot;, &quot;Location&quot;, &quot;Label&quot;])<br># Extract logon hour<br>df[&quot;Logon_Hour&quot;] = pd.to_datetime(df[&quot;Logon_Time&quot;]).dt.hour<br># Encode categorical features<br>categorical_cols = [&quot;Username&quot;, &quot;Logon_Type&quot;, &quot;Device_Name&quot;, &quot;Location&quot;]<br>encoders = {}<br>for col in categorical_cols:<br>le = LabelEncoder()<br>df[col] = le.fit_transform(df[col])<br>encoders[col] = le<br># Encode target label<br>label_encoder = LabelEncoder()<br>df[&quot;Label_Code&quot;] = label_encoder.fit_transform(df[&quot;Label&quot;]) # 0 = normal, 1 = insider<br># Prepare features and target<br>features = categorical_cols + [&quot;Logon_Hour&quot;]<br>X = df[features]<br>y = df[&quot;Label_Code&quot;]<br># Stratified train-test split<br>X_train, X_test, y_train, y_test = train_test_split(<br>X, y, test_size=0.2, stratify=y, random_state=42<br>)<br># Train Random Forest classifier<br>clf = RandomForestClassifier(n_estimators=100, class_weight=&quot;balanced&quot;, random_state=42)<br>clf.fit(X_train, y_train)<br># Evaluate<br>y_pred = clf.predict(X_test)<br>print(&quot;Classification Report:\n&quot;, classification_report(y_test, y_pred))<br># Plot confusion matrix<br>cm = confusion_matrix(y_test, y_pred)<br>sns.heatmap(cm, annot=True, fmt=&quot;d&quot;, cmap=&quot;Blues&quot;)<br>plt.title(&quot;Confusion Matrix&quot;)<br>os.makedirs(&quot;visuals&quot;, exist_ok=True)<br>plt.savefig(&quot;visuals/confusion_matrix.png&quot;)<br>plt.close()<br>os.makedirs(&quot;models&quot;, exist_ok=True)<br>joblib.dump(clf, &quot;models/insider_classifier.pkl&quot;)<br>joblib.dump(label_encoder, &quot;models/encoder_Label.pkl&quot;)<br>for feature, enc in encoders.items():<br>joblib.dump(enc, f&quot;models/encoder_{feature}.pkl&quot;)<br>print(&quot;Model and encoders saved successfully.&quot;)</pre><h4>Model Training:</h4><p>This step trains a Random Forest classifier using features including Username, Logon_Type, Device_Name, Location, and Logon_Hour. The class_weight=”balanced” parameter addresses class imbalance. Training includes stratified splitting to maintain label proportions.</p><h4>Model Evaluation:</h4><p>The trained model is evaluated on a held-out test set. The classification report displays precision, recall, and F1-scores for both classes. The confusion matrix visualization clarifies patterns of correct vs misclassified events.</p><h4>Output:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*O6KiGee8Akapk2Km0JMujQ.png" /></figure><p>The terminal output from train_model.py confirms that the machine learning model has been successfully trained. It first displays a classification report showing how well the model performed during testing. Metrics like precision, recall, and F1-score tell us how accurately the model classified normal vs insider logon events. An overall accuracy score of 0.99 means the model is very effective.</p><p>Right after that, you’ll see the line: Model and encoders saved successfully.This confirms that the trained model and its label encoders were stored correctly inside the models/ folder for later use during prediction.</p><p>After running train_model.py it’s generated Confusion Matrix (visuals/confusion_matrix.png) shows true positive vs false positive rates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*jDWZTVlJZaccQJZ8T6EuTw.png" /></figure><h4>Confusion Matrix Breakdown</h4><p>This confusion matrix was generated after training the insider threat detection model using train_model.py. It visually represents how well the model performed on the test data:</p><ul><li><strong>True Negatives (180)</strong> — Normal logon events correctly classified as normal.</li><li><strong>True Positives (169)</strong> — Insider threat logons correctly detected as threats.</li><li><strong>False Negatives (10)</strong> — Insider events that were incorrectly labeled as normal (missed threats).</li><li><strong>False Positives (0)</strong> — No normal logons were mistakenly flagged as insider threats.</li></ul><h4>What This Means:</h4><ul><li>The model demonstrates <strong>strong accuracy</strong>, with a very low false positive rate.</li><li>A small number of insider threats were missed, indicating room for slight improvement in recall.</li><li>The matrix confirms that the model is practical for real-world use where false alarms must be minimized.</li></ul><h3>Step 3 : Create analyze_logon.py</h3><p><strong>Purpose of analyze_logon.py</strong></p><p>This script performs insider threat detection on new logon events using the trained model. It:</p><ul><li>Loads the saved model and encoders</li><li>Encodes sample logon data</li><li>Predicts whether each logon is normal or suspicious</li><li>Outputs results to the console and output/predicted_logons.csv</li></ul><p><strong>SCRIPT : analyze_logon.py</strong></p><pre>import pandas as pd<br>import joblib<br>import os<br># Sample logon events for inference<br>samples = [<br>{&quot;Username&quot;:&quot;user1&quot;,&quot;Logon_Type&quot;:&quot;Remote&quot;,&quot;Device_Name&quot;:&quot;Workstation01&quot;,&quot;Location&quot;:&quot;HeadOffice&quot;,&quot;Logon_Hour&quot;:2},<br>{&quot;Username&quot;:&quot;user2&quot;,&quot;Logon_Type&quot;:&quot;Local&quot;,&quot;Device_Name&quot;:&quot;Laptop23&quot;,&quot;Location&quot;:&quot;Branch&quot;,&quot;Logon_Hour&quot;:14},<br>{&quot;Username&quot;:&quot;admin&quot;,&quot;Logon_Type&quot;:&quot;RDP&quot;,&quot;Device_Name&quot;:&quot;Server12&quot;,&quot;Location&quot;:&quot;DataCenter&quot;,&quot;Logon_Hour&quot;:1},<br>]<br># Load encoders and model<br>encoders = {feature: joblib.load(f&quot;models/encoder_{feature}.pkl&quot;)<br>for feature in [&quot;Username&quot;, &quot;Logon_Type&quot;, &quot;Device_Name&quot;, &quot;Location&quot;]}<br>label_decoder = joblib.load(&quot;models/encoder_Label.pkl&quot;)<br>model = joblib.load(&quot;models/insider_classifier.pkl&quot;)<br>processed = []<br>for s in samples:<br>row = {}<br>for feature in [&quot;Username&quot;, &quot;Logon_Type&quot;, &quot;Device_Name&quot;, &quot;Location&quot;]:<br>val = s[feature]<br>enc = encoders[feature]<br>row[feature] = enc.transform([val])[0] if val in enc.classes_ else 0<br>row[&quot;Logon_Hour&quot;] = s[&quot;Logon_Hour&quot;]<br>processed.append(row)<br>X = pd.DataFrame(processed, columns=[&quot;Username&quot;, &quot;Logon_Type&quot;, &quot;Device_Name&quot;, &quot;Location&quot;, &quot;Logon_Hour&quot;])<br>predictions = model.predict(X)<br>decoded = label_decoder.inverse_transform(predictions)<br>output = []<br>for i, label in enumerate(decoded):<br>entry = samples[i].copy()<br>entry[&quot;Prediction&quot;] = label<br>print(f&quot;[{i+1}] {entry}&quot;)<br>output.append(entry)<br>os.makedirs(&quot;output&quot;, exist_ok=True)<br>pd.DataFrame(output).to_csv(&quot;output/predicted_logons.csv&quot;, index=False)<br>print(&quot;Predictions saved to output/predicted_logons.csv&quot;)</pre><h4>Why Sample Logon Events Are Used</h4><p>In this project, we use a set of <strong>manually created sample logon events</strong> to test and validate the AI+ML model’s prediction capabilities. These synthetic samples are constructed to simulate realistic behavior scenarios — ranging from legitimate logons to suspicious insider actions — based on attributes like logon time, device type, and behavior anomalies.</p><p>This method allows us to:</p><ul><li>Quickly evaluate the trained model without requiring sensitive or protected data.</li><li>Demonstrate prediction outcomes in a clean, understandable format.</li><li>Save and visualize results without heavy system integration.</li></ul><p><strong>Output:</strong></p><p>The file predicted_logons.csv is automatically created after running analyze_logon.py. It contains the original logon records along with a new column called Prediction, which shows whether the event was classified as “Normal” or “Insider” by the machine learning model.</p><p>Each row represents a logon event, and the prediction is based on the encoded features like username, logon type, device name, location, and logon hour.</p><p><strong>View output files in </strong>output/predicted_logons.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*2ch9RlG_X2RnNvX1sF7zlA.png" /></figure><h4>Results &amp; Insights:</h4><ul><li>With balanced training, the classifier achieves high accuracy, precision, and recall for both classes, especially if insider events are present in test set.</li><li>The most informative features often include Logon_Hour (off-hours), and mismatched device/location patterns.</li><li>Security teams can focus investigation on flagged insider predictions.</li></ul><h4>Outcome:</h4><ul><li>The AI+ML system we built helps detect insider threats by looking at patterns in user logon behavior. It checks things like what time someone logged in, from which device, and from which location. If the pattern looks strange compared to usual behavior, the system flags it as a possible threat.</li><li>This makes the job easier for security teams. Instead of checking every log manually, the model highlights only the suspicious ones. It works like an extra set of smart eyes that can spot unusual activities quickly.</li><li>Because we used simple tools like Random Forest and basic encoders, the system is easy to use and doesn’t need powerful hardware. It can be trained again with new data and can be connected with alert systems or dashboards for real-time monitoring.</li><li>Even though we used fake (synthetic) logon data in this project, the same process can work with real company data. The model can reduce the number of false alarms in SIEM tools by filtering out normal logons and focusing on the ones that matter.</li><li>In short, this project shows how machine learning can support cybersecurity teams by detecting risky user behavior and saving time during investigations.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6133945b50cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI-Driven SIEM Alert Noise Reduction: A Machine Learning Approach to Filtering False Positives and…]]></title>
            <link>https://medium.com/@myth7672/ai-driven-siem-alert-noise-reduction-a-machine-learning-approach-to-filtering-false-positives-and-f2da2be7c536?source=rss-0f351da37421------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2da2be7c536</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[siem-alert-management]]></category>
            <category><![CDATA[false-positive-reduction]]></category>
            <category><![CDATA[intelligent-threat]]></category>
            <category><![CDATA[blue-team]]></category>
            <dc:creator><![CDATA[Myth]]></dc:creator>
            <pubDate>Sun, 16 Nov 2025 13:36:40 GMT</pubDate>
            <atom:updated>2025-11-16T13:36:40.420Z</atom:updated>
            <content:encoded><![CDATA[<h3>AI-Driven SIEM Alert Noise Reduction: A Machine Learning Approach to Filtering False Positives and Prioritizing Real Threats</h3><p>Using ML to filter routine alerts, reduce false positives, and help SOC teams focus on real threats instead of noise</p><h4>Objective</h4><ul><li>The goal of this project is to <strong>develop an intelligent AI/ML-based system</strong> to help reduce <strong>alert fatigue</strong> in Security Information and Event Management (SIEM) systems.</li><li>Modern SIEM tools generate <strong>thousands of alerts daily</strong>, many of which are: Repetitive, False positives, Low-risk or irrelevant (noise)</li><li>This overwhelming number of alerts can <strong>distract analysts</strong> from focusing on real threats.</li><li><strong>Suppress</strong> or filter out low-priority alerts</li><li>The AI model will help <strong>identify which alerts are important</strong> and which can be <strong>ignored or deprioritized</strong>.</li><li>The overall result is <strong>improved efficiency</strong> in threat detection and <strong>reduced noise</strong> for security teams.</li></ul><h4>Tools &amp; Libraries Used:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*16pXEMx1EJjQAOmxYlYDnA.png" /></figure><h4><strong>Prerequisites:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*3eFsRNVKJmw14tBjaKVNFw.png" /></figure><h4>AI/ML Inclusion Workflow:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*gOsFWZJAV8ZH_otdyWMvOg.png" /></figure><h4>Use Case Scenario:</h4><p>A SOC (Security Operations Center) analyst faces alert overload from the SIEM system. Most alerts are low-risk or duplicates from repetitive sources. This model helps reduce noise by automatically tagging alerts as “Ignore”, “Investigate”, or “Critical” based on trained behavior patterns.</p><p><strong>Actors:</strong></p><ul><li><strong>SIEM System</strong>: Generates raw alerts from various sources.</li><li><strong>SOC Analyst</strong>: Reviews and triages alerts.</li><li><strong>AI/ML Model</strong>: Learns from alert history to assist in filtering.</li></ul><h4>Folder Structure:</h4><p>siem_noise_reduction_ai_ml/</p><p>├── train_model.py # Model training script</p><p>├── analyze_alert.py # Prediction script</p><p>├── requirements.txt # List of dependencies</p><p>├── dataset/</p><p>│ └── siem_alert_logs.csv # Synthetic training dataset</p><p>├── models/</p><p>│ └── alert_classifier.pkl # Trained ML model</p><p>│ └── confusion_matrix.png # Model evaluation image</p><h4>Step 1: Downloading &amp; Using the Dataset</h4><p>To train the model, we used a publicly available dataset from Kaggle titled <a href="https://www.kaggle.com/datasets/teamincribo/cyber-security-attacks?select=cybersecurity_attacks.csv"><strong><em>cybersecurity_attacks</em></strong></a>, which contains approximately <strong>40,000 SIEM-style alert records</strong> with 25 structured fields commonly seen in enterprise environments.</p><p>From this dataset, we extracted the most relevant fields and applied labeling logic to classify each alert as either <strong>important</strong> or <strong>noise</strong>. The processed dataset closely resembles real-world data used in SOC operations.</p><h4>Label Distribution:</h4><ul><li>60% of alerts were labeled as <strong>noise</strong> (typically low-risk or repetitive events such as port scans)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*nDUrWx1t9t5Q0CMF8PqmMw.png" /></figure><ul><li>40% of alerts were labeled as <strong>important</strong> (critical incidents like ransomware, data exfiltration, malware callbacks)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ruuEjDyRExMohdnnCaV-XA.png" /></figure><p><strong>Features Used for Model Training:</strong></p><p>All fields used in training were categorical in nature and converted to numeric format using label encoding to ensure compatibility with the machine learning algorithm.</p><p><strong>Labeling Strategy:</strong></p><p>Since the dataset does not include predefined “noise” or “important” labels, we applied a deterministic logic for annotation:</p><p>if Severity == ‘Low’ and Alert_Type in [‘Port Scan’, ‘Login Attempt’, ‘Ping Sweep’]:</p><p>Label = ‘noise’</p><p>else:</p><p>Label = ‘important’</p><p>This helped simulate real analyst triage behavior and distinguish between high-value alerts and repetitive noise.</p><p><strong>Practical Use Case:</strong></p><p>This dataset represents a typical export format from tools like <strong>Splunk</strong>, <strong>QRadar</strong>, or <strong>Elastic SIEM</strong>, where alert logs can be extracted as CSV files. The same classification logic can be applied to real-world SIEM logs to assist in reducing alert fatigue and prioritizing high-risk incidents.</p><h4>Step 2: Create Training Code (train_model.py)</h4><p>This script is responsible for training the machine learning model using the prepared dataset. It performs the following operations:</p><ul><li>Loads and preprocesses the synthetic SIEM alert dataset</li><li>Encodes categorical fields into numeric form using LabelEncoder</li><li>Splits the dataset into training and testing subsets</li><li>Trains a Random Forest classifier to differentiate between important and noise alerts</li><li>Evaluates the model using classification metrics</li><li>Saves the trained model and confusion matrix visualization for future use</li></ul><p>This script must be executed once to prepare the model before performing alert classification or running predictions.</p><p><strong>SCRIPT : train_model.py</strong></p><pre>import pandas as pd<br>import numpy as np<br>from sklearn.model_selection import train_test_split<br>from sklearn.preprocessing import LabelEncoder<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.metrics import classification_report, confusion_matrix<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>import joblib<br>import os<br># Load dataset<br>df = pd.read_csv(&quot;dataset/cybersecurity_attacks_clean.csv&quot;)<br># Rename columns to simplify references<br>df = df.rename(columns={<br>&quot;Attack Type&quot;: &quot;Attack_Type&quot;,<br>&quot;Severity Level&quot;: &quot;Severity&quot;,<br>&quot;IDS/IPS Alerts&quot;: &quot;IDS_Alerts&quot;,<br>&quot;Protocol&quot;: &quot;Protocol&quot;<br>})<br># Keep required fields only and drop missing rows<br>df = df[[&quot;Attack_Type&quot;, &quot;Severity&quot;, &quot;Protocol&quot;, &quot;IDS_Alerts&quot;]].dropna()<br># Updated labeling logic to ensure better class balance<br>def label_alert(row):<br>low_keywords = [&quot;login attempt&quot;, &quot;port scan&quot;, &quot;ping sweep&quot;]<br>suspicious_keywords = [&quot;suspicious&quot;, &quot;unauthorized&quot;, &quot;scan&quot;, &quot;probe&quot;]<br>severity = str(row[&quot;Severity&quot;]).lower()<br>attack = str(row[&quot;Attack_Type&quot;]).lower()<br># Noise if low severity or known harmless patterns<br>if severity == &quot;low&quot;:<br>return &quot;noise&quot;<br>if any(kw in attack for kw in low_keywords):<br>return &quot;noise&quot;<br>if any(kw in attack for kw in suspicious_keywords) and severity in [&quot;low&quot;, &quot;medium&quot;]:<br>return &quot;noise&quot;<br># Otherwise, treat as important<br>return &quot;important&quot;<br># Apply labeling<br>df[&quot;Label&quot;] = df.apply(label_alert, axis=1)<br># Show label distribution<br>print(&quot;Label Distribution:\n&quot;, df[&quot;Label&quot;].value_counts())<br># Encode features<br>features = [&quot;Attack_Type&quot;, &quot;Severity&quot;, &quot;Protocol&quot;, &quot;IDS_Alerts&quot;]<br>encoders = {}<br>for col in features:<br>encoders[col] = LabelEncoder()<br>df[col] = encoders[col].fit_transform(df[col])<br># Encode target variable<br>label_encoder = LabelEncoder()<br>y = label_encoder.fit_transform(df[&quot;Label&quot;]) # 0 = noise, 1 = important<br># Save label encoder too (for decoding later)<br>encoders[&quot;Label&quot;] = label_encoder<br># Prepare input features<br>X = df[features]<br># Train/test split<br>X_train, X_test, y_train, y_test = train_test_split(<br>X, y, test_size=0.2, stratify=y, random_state=42<br>)<br># Train model<br>clf = RandomForestClassifier(n_estimators=100, random_state=42)<br>clf.fit(X_train, y_train)<br># Evaluate<br>y_pred = clf.predict(X_test)<br>print(&quot;\nClassification Report:\n&quot;)<br>print(classification_report(y_test, y_pred))<br># Confusion Matrix<br>cm = confusion_matrix(y_test, y_pred)<br>sns.heatmap(cm, annot=True, fmt=&#39;d&#39;, cmap=&#39;Blues&#39;)<br>plt.title(&quot;Confusion Matrix&quot;)<br>os.makedirs(&quot;models&quot;, exist_ok=True)<br>plt.savefig(&quot;models/confusion_matrix.png&quot;)<br>plt.close()<br># Save model and encoders<br>joblib.dump(clf, &quot;models/alert_classifier.pkl&quot;)<br>for col in encoders:<br>joblib.dump(encoders[col], f&quot;models/encoder_{col}.pkl&quot;)<br>print(&quot;\nModel and encoders saved successfully.&quot;)</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*BTM0yqXkn-1Hv8nVcSostA.png" /></figure><p>The screenshot above shows the console output after running the train_model.py script. This script is responsible for training the machine learning model to classify SIEM alerts as either <strong>important</strong> or <strong>noise</strong>.</p><p><strong>Key Highlights from the Output:</strong></p><p>Label Distribution:</p><ul><li>Important Alerts: 13,369 entries</li><li>Noise Alerts: 6,581 entries</li><li>This shows that the model was trained on a realistic mix of critical vs routine alerts.</li></ul><p>Classification Report:</p><ul><li>Precision, recall, and F1-score are all 1.00 for both classes.</li><li>This indicates perfect classification on the test set during evaluation.</li><li>Accuracy: 100% on 3990 validation records.</li></ul><p>Model Saved:<br> The trained model and encoders were saved successfully in the /models folder for future use during real-time inference.</p><p>This confusion matrix was generated by train_model.py and saved as visuals/confusion_matrix.png. It visually confirms how well the machine learning model performed in classifying SIEM alerts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*VwAvxRHPH3kmkY1nhs2Vzw.png" /></figure><p><strong>Interpretation of the Matrix:</strong></p><ul><li><strong>True Negatives (2674)<br></strong> These are normal (noise) alerts that were correctly identified as noise.</li><li><strong>True Positives (1316)<br></strong> These are important alerts that were correctly detected by the model.</li><li><strong>False Positives (0)<br></strong> No noise alerts were incorrectly flagged as important.</li><li><strong>False Negatives (0)<br></strong> No important alerts were missed.</li></ul><h4>Step 3: Create Prediction Code (analyze_alert.py):</h4><p>This script is used to perform alert classification using the trained machine learning model. It accepts a list of simulated alert entries and returns predictions indicating whether each alert is likely to be important or noise.</p><p>Specifically, the script performs the following tasks:</p><ul><li>Loads the trained model file (alert_classifier.pkl)</li><li>Loads the original dataset to recreate label encoders for consistency</li><li>Encodes each input alert’s categorical fields using the same encoding scheme used during training</li><li>Uses the trained model to classify each alert as either “Important” or “Noise”</li><li>Outputs a readable summary of the classification results</li></ul><p>This module is useful for validating model behavior on new or simulated alert entries and can be extended to support real-time or batch processing pipelines in a production SIEM environment.</p><p><strong>SCRIPT : analyze_alert.py</strong></p><pre>import joblib<br>import pandas as pd<br>import os<br># Sample input alerts for analysis<br>samples = [<br>{<br>&quot;Attack_Type&quot;: &quot;Ransomware&quot;,<br>&quot;Severity&quot;: &quot;High&quot;,<br>&quot;Protocol&quot;: &quot;TCP&quot;,<br>&quot;IDS_Alerts&quot;: &quot;Yes&quot;<br>},<br>{<br>&quot;Attack_Type&quot;: &quot;Port Scan&quot;,<br>&quot;Severity&quot;: &quot;Low&quot;,<br>&quot;Protocol&quot;: &quot;UDP&quot;,<br>&quot;IDS_Alerts&quot;: &quot;No&quot;<br>},<br>{<br>&quot;Attack_Type&quot;: &quot;SQL Injection&quot;,<br>&quot;Severity&quot;: &quot;Medium&quot;,<br>&quot;Protocol&quot;: &quot;HTTP&quot;,<br>&quot;IDS_Alerts&quot;: &quot;Yes&quot;<br>},<br>{<br>&quot;Attack_Type&quot;: &quot;Phishing&quot;,<br>&quot;Severity&quot;: &quot;High&quot;,<br>&quot;Protocol&quot;: &quot;SMTP&quot;,<br>&quot;IDS_Alerts&quot;: &quot;Yes&quot;<br>},<br>{<br>&quot;Attack_Type&quot;: &quot;Brute Force&quot;,<br>&quot;Severity&quot;: &quot;Medium&quot;,<br>&quot;Protocol&quot;: &quot;TCP&quot;,<br>&quot;IDS_Alerts&quot;: &quot;No&quot;<br>},<br>{<br>&quot;Attack_Type&quot;: &quot;Data Exfiltration&quot;,<br>&quot;Severity&quot;: &quot;High&quot;,<br>&quot;Protocol&quot;: &quot;FTP&quot;,<br>&quot;IDS_Alerts&quot;: &quot;Yes&quot;<br>},<br>{<br>&quot;Attack_Type&quot;: &quot;Login Attempt&quot;,<br>&quot;Severity&quot;: &quot;Low&quot;,<br>&quot;Protocol&quot;: &quot;TCP&quot;,<br>&quot;IDS_Alerts&quot;: &quot;No&quot;<br>},<br>{<br>&quot;Attack_Type&quot;: &quot;Ping Sweep&quot;,<br>&quot;Severity&quot;: &quot;Low&quot;,<br>&quot;Protocol&quot;: &quot;ICMP&quot;,<br>&quot;IDS_Alerts&quot;: &quot;No&quot;<br>},<br>{<br>&quot;Attack_Type&quot;: &quot;Malware Callback&quot;,<br>&quot;Severity&quot;: &quot;High&quot;,<br>&quot;Protocol&quot;: &quot;HTTPS&quot;,<br>&quot;IDS_Alerts&quot;: &quot;Yes&quot;<br>},<br>{<br>&quot;Attack_Type&quot;: &quot;Suspicious DNS Query&quot;,<br>&quot;Severity&quot;: &quot;Medium&quot;,<br>&quot;Protocol&quot;: &quot;DNS&quot;,<br>&quot;IDS_Alerts&quot;: &quot;Yes&quot;<br>},<br>{<br>&quot;Attack_Type&quot;: &quot;VPN Check-in&quot;,<br>&quot;Severity&quot;: &quot;Low&quot;,<br>&quot;Protocol&quot;: &quot;UDP&quot;,<br>&quot;IDS_Alerts&quot;: &quot;No&quot;<br>},<br>{<br>&quot;Attack_Type&quot;: &quot;Heartbeat&quot;,<br>&quot;Severity&quot;: &quot;Low&quot;,<br>&quot;Protocol&quot;: &quot;ICMP&quot;,<br>&quot;IDS_Alerts&quot;: &quot;No&quot;<br>}<br>]<br># Load encoders<br>encoders = {<br>&quot;Attack_Type&quot;: joblib.load(&quot;models/encoder_Attack_Type.pkl&quot;),<br>&quot;Severity&quot;: joblib.load(&quot;models/encoder_Severity.pkl&quot;),<br>&quot;Protocol&quot;: joblib.load(&quot;models/encoder_Protocol.pkl&quot;),<br>&quot;IDS_Alerts&quot;: joblib.load(&quot;models/encoder_IDS_Alerts.pkl&quot;)<br>}<br>label_decoder = joblib.load(&quot;models/encoder_Label.pkl&quot;)<br># Encode samples<br>encoded_samples = []<br>for sample in samples:<br>row = []<br>for feature in [&quot;Attack_Type&quot;, &quot;Severity&quot;, &quot;Protocol&quot;, &quot;IDS_Alerts&quot;]:<br>val = sample[feature]<br>encoder = encoders[feature]<br>row.append(encoder.transform([val])[0] if val in encoder.classes_ else 0)<br>encoded_samples.append(row)<br>X_input = pd.DataFrame(encoded_samples, columns=[&quot;Attack_Type&quot;, &quot;Severity&quot;, &quot;Protocol&quot;, &quot;IDS_Alerts&quot;])<br># Load model and predict<br>model = joblib.load(&quot;models/alert_classifier.pkl&quot;)<br>predictions = model.predict(X_input)<br>predicted_labels = label_decoder.inverse_transform(predictions)<br># Output results<br>output_data = []<br>for i, label in enumerate(predicted_labels):<br>print(f&quot;\n[{i+1}] Attack Type: {samples[i][&#39;Attack_Type&#39;]}&quot;)<br>print(f&quot; Severity: {samples[i][&#39;Severity&#39;]}&quot;)<br>print(f&quot; Protocol: {samples[i][&#39;Protocol&#39;]} | IDS Alert: {samples[i][&#39;IDS_Alerts&#39;]}&quot;)<br>print(f&quot; Prediction: {label.capitalize()}&quot;)<br>output_data.append({<br>&quot;Attack_Type&quot;: samples[i][&quot;Attack_Type&quot;],<br>&quot;Severity&quot;: samples[i][&quot;Severity&quot;],<br>&quot;Protocol&quot;: samples[i][&quot;Protocol&quot;],<br>&quot;IDS_Alerts&quot;: samples[i][&quot;IDS_Alerts&quot;],<br>&quot;Prediction&quot;: label.capitalize()<br>})<br># Save output to CSV<br>os.makedirs(&quot;output&quot;, exist_ok=True)<br>pd.DataFrame(output_data).to_csv(&quot;output/predicted_alerts.csv&quot;, index=False)<br>print(&quot;\nPredictions saved to &#39;output/predicted_alerts.csv&#39;&quot;)</pre><h4><strong>Output:</strong></h4><p>[1] Alert: {‘Alert_Type’: ‘Brute Force’, ‘Severity’: ‘High’, …}</p><p>➤ Prediction: Important</p><p>[2] Alert: {‘Alert_Type’: ‘Port Scan’, ‘Severity’: ‘Low’, …}</p><p>➤ Prediction: Noise</p><p>[3] Alert: {‘Alert_Type’: ‘Malware’, ‘Severity’: ‘High’, …}</p><p>➤ Prediction: Important</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*tqFPJg3LTb13k2SngFKvpQ.png" /></figure><p>Output Saved in<strong> output/predicted_alerts.csv:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*w6q-emzsLnDqHRSLvdBMTw.png" /></figure><h4>Visualization (Optional):</h4><p>To support the analysis, we included visual representations to better understand the behavior of the model and the structure of the dataset.</p><p><strong>1. Label Distribution</strong></p><p>A bar chart was generated to display the number of samples labeled as noise versus important within the dataset. This helps visualize the class imbalance typical in real-world SIEM data.</p><p>Python snippet:</p><pre>import matplotlib.pyplot as plt<br>import seaborn as sns<br>import pandas as pd<br>df = pd.read_csv(&quot;dataset/siem_alert_logs.csv&quot;)<br>sns.countplot(x=&quot;Label&quot;, data=df)<br>plt.title(&quot;Label Distribution in Training Dataset&quot;)<br>plt.savefig(&quot;models/label_distribution.png&quot;)</pre><p>File saved as: models/label_distribution.png</p><h4>2. Feature Importance Chart</h4><p>An additional bar chart was created to show the importance of each feature in contributing to the model’s decisions. This highlights which alert fields (such as severity or device type) had the most influence on the predictions.</p><p>Python snippet:</p><pre>importances = clf.feature_importances_<br>feature_names = X.columns<br>sns.barplot(x=importances, y=feature_names)<br>plt.title(&quot;Feature Importance from Random Forest&quot;)<br>plt.savefig(&quot;models/feature_importance.png&quot;)</pre><p>File saved as: models/feature_importance.png</p><h3>Results and Insights</h3><p>The trained model was evaluated using a standard classification report, which generated the following approximate metrics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*r4DLNhNzX6Oif6EFm349bg.png" /></figure><p>Key takeaways:</p><ul><li>The model effectively detects important alerts with a high recall rate.</li><li>It maintains a good precision score, avoiding frequent false positives.</li><li>Processing is efficient enough to support real-time use in SOC environments.</li><li>These results are suitable for integration into existing SIEM systems.</li></ul><h4>Outcome:</h4><p>The machine learning model developed in this project serves as a reliable filter for reducing SIEM alert noise. Specifically, it:</p><ul><li>Automatically suppresses non-actionable alerts.</li><li>Tags incoming alerts based on historical relevance.</li><li>Enhances blue team efficiency by cutting through false positives.</li><li>Allows the SOC team to focus more on actual incidents and reduce alert fatigue.</li></ul><p>This system can be expanded and integrated into real-world SIEM platforms using export APIs or log pipelines.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2da2be7c536" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unauthorized USB Device Detection with AI+ML]]></title>
            <link>https://medium.com/@myth7672/unauthorized-usb-device-detection-with-ai-ml-cf3fcbd53fae?source=rss-0f351da37421------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf3fcbd53fae</guid>
            <category><![CDATA[cyberattack]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Myth]]></dc:creator>
            <pubDate>Fri, 31 Oct 2025 16:37:54 GMT</pubDate>
            <atom:updated>2025-10-31T16:37:54.857Z</atom:updated>
            <content:encoded><![CDATA[<p>Prevent unauthorized USB activity and data leaks using AI-driven behavioral monitoring.</p><h4>Objective:</h4><p>To build a proactive USB security monitoring system that detects unauthorized USB devices using <strong>AI and ML-driven behavior profiling</strong>. The system will identify suspicious USB device insertions based not only on device metadata (like Vendor ID, serial number, etc.) but also on behavioral patterns (like file activity, usage duration, and time of use).</p><p>This helps blue teamers by:</p><ul><li>Detecting risky USB insertions in real time.</li><li>Profiling normal vs abnormal USB usage.</li><li>Automatically learning over time using feedback.</li><li>Offering a smarter alternative to static whitelisting.</li></ul><h4>Tools Required:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*CugRKjOhoQlJFM3tPSgyMQ.png" /></figure><h4>Prerequisites:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*PJX6Wik_ea3r6vb8Z_ougw.png" /></figure><h3>Folder Structure:</h3><p>Unauthorized_USB_Detection/</p><p>│</p><p>├── dataset/</p><p>│ ├── initial_training.csv # Contains known USB device data</p><p>│ └── new_usb_events.csv # Real-time device logs</p><p>│</p><p>├── models/</p><p>│ └── usb_classifier.pkl # Trained ML model</p><p>│</p><p>├── scripts/</p><p>│ ├── train_initial.py # Model training script</p><p>│ ├── usb_monitor.py # Real-time detection script</p><p>│ ├── online_update.py # Self-learning from analyst decisions</p><p>│ └── actions.py # Block device / raise alerts</p><p>│</p><p>├── logs/</p><p>│ └── usb_activity.log # Full USB activity logs</p><p>│</p><p>├── requirements.txt</p><p>└── README.md</p><h3>Use Case Scenario:</h3><p>A large IT company uses AI+ML tools to secure its endpoints against data exfiltration via unauthorized USB devices. Each employee’s device (like official USBs and encrypted drives) is profiled by the system. If a new device is plugged in and shows unknown characteristics or suspicious behavior, the system flags it in real-time for investigation or blocks it automatically.</p><h3>How AI &amp; ML Help in Blue Teaming:</h3><p>Unlike traditional USB control systems (which rely on static whitelists and signatures), our AI+ML approach gives the blue team:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*z60zp-Hq4fdcxOYa3vLD3A.png" /></figure><p>This gives blue teamers the power to <strong>monitor, profile, and act</strong> on USB activity with minimal manual effort.</p><h4>AI/ML Inclusion Workflow:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*13SKb8dtwCEbq-oqogF3Ug.png" /></figure><h4><strong>Step 1: Downloading &amp; Using the Dataset</strong></h4><p><strong>Option A:</strong> While <a href="https://www.kaggle.com/datasets/rasikaekanayakadevlk/device-usage-history-dataset">large-scale datasets</a> are available on platforms like Kaggle, they often contain unnecessary noise, complex schemas, or anonymized fields that make model training harder without deep pre-cleaning.</p><p><strong>Option B:</strong> To simplify model training and testing, we created a custom sample dataset named initial_training.csv. This synthetic dataset simulates realistic USB device behavior on a Windows environment. Each row represents an event capturing device attributes and behavioral metadata.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*LGNCS3AlgZDdrfhLxrwsBQ.png" /></figure><p><strong>Why we used a sample dataset (Option B):</strong></p><ul><li>It is lightweight and easy to understand for initial training and proof of concept.</li><li>Allows rapid iteration without long processing time or resource requirements.</li><li>Easy to extend or replace with real-world data once the pipeline is verified.</li></ul><p>The initial_training.csv file includes key fields like:</p><ul><li>Device_ID</li><li>Device_Type</li><li>User</li><li>Access_Time</li><li>Read_Count, Write_Count, Transfer_Activity</li><li>Label (Normal / Suspicious)</li></ul><p>This dataset serves as the foundation for building and evaluating the detection model in a controlled environment.</p><h4>Step 2: USB Monitoring Logic (Real-Time Detection)</h4><p>We use <strong>WMI (Windows Management Instrumentation)</strong> via the pywin32 or wmi Python module to detect new USB insertions on a Windows machine.</p><p><strong>Installation:</strong></p><p>pip install wmi</p><h4>Step 3: Create train_initial.py — Model Training Script</h4><ul><li>We’ll train a simple <strong>Random Forest Classifier</strong> to recognize known USB profiles.</li><li>This will create a trained model file at models/usb_classifier.pkl.</li></ul><p><strong>Scripts : train_initial.py</strong></p><pre>import pandas as pd<br>from sklearn.ensemble import GradientBoostingClassifier<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import accuracy_score, classification_report<br>from sklearn.preprocessing import LabelEncoder<br>import joblib<br>FEATURE_COLUMNS = [&#39;vendor_id&#39;, &#39;product_id&#39;, &#39;file_system&#39;] # Removed noisy fields<br>def preprocess(df):<br>df = df.fillna(&quot;Unknown&quot;)<br>for col in FEATURE_COLUMNS:<br>le = LabelEncoder()<br>df[col] = le.fit_transform(df[col].astype(str))<br>return df<br>def train():<br>df = pd.read_csv(&quot;dataset/initial_training.csv&quot;)<br>df = preprocess(df)<br>X = df[FEATURE_COLUMNS]<br>y = df[&quot;label&quot;]<br>X_train, X_test, y_train, y_test = train_test_split(<br>X, y, test_size=0.2, random_state=99, stratify=y<br>)<br>clf = GradientBoostingClassifier(n_estimators=150)<br>clf.fit(X_train, y_train)<br>y_pred = clf.predict(X_test)<br>print(&quot;Accuracy:&quot;, accuracy_score(y_test, y_pred))<br>print(classification_report(y_test, y_pred, zero_division=1))<br>joblib.dump(clf, &quot;models/usb_classifier.pkl&quot;)<br>print(&quot;[+] Model saved to models/usb_classifier.pkl&quot;)<br>if __name__ == &quot;__main__&quot;:<br>train()</pre><p><strong>Output:</strong></p><p>This screenshot shows the terminal output after running the training script train_initial.py. Here’s what it indicates:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*N3BapzvJCc6DZFq1X7tn7g.png" /></figure><ul><li><strong>Accuracy: 1.0</strong></li></ul><p>The model achieved perfect accuracy on the test dataset — all 40 samples were correctly classified.</p><p>The model was trained using 40 records: 20 labeled as authorized and 20 as unauthorized USB events. The detailed metrics are:</p><h4>Step 4: Create a usb_monitor.py — Live USB Detection Script</h4><p>The usb_monitor.py script is designed to <strong>actively monitor USB device connections</strong> in real-time on a Windows system. It performs the following tasks:</p><ul><li><strong>Watches for USB Plug Events:<br></strong> It listens for system events to detect whenever a USB device is plugged in.</li><li><strong>Extracts USB Metadata:<br></strong> When a device is connected, it gathers information such as <strong>device ID</strong>, <strong>vendor ID</strong>, and <strong>product description</strong>.</li><li><strong>Applies Pre-trained ML Model:<br></strong> It loads the previously trained model (usb_classifier.pkl) and classifies the connected USB device as either:</li><li>authorized — known and permitted device</li><li>unauthorized — unfamiliar or potentially suspicious device</li><li><strong>Displays Prediction Output:<br></strong> The classification result is printed to the terminal immediately after detection.</li></ul><p>The AI model doesn’t understand strings like “SanDisk” or “NTFS”, so we’ll <strong>convert them to numeric features</strong> using hash or label encoding.</p><p><strong>Scripts : usb_monitor.py</strong></p><pre>import wmi<br>import time<br>import joblib<br>import pandas as pd<br>import re<br>from actions import handle_detection<br>MODEL_PATH = &quot;models/usb_classifier.pkl&quot;<br>FEATURE_COLUMNS = [&#39;vendor_id&#39;, &#39;product_id&#39;, &#39;file_system&#39;]<br>c = wmi.WMI()<br>def extract_usb_info(instance):<br>vendor_id = &quot;Unknown&quot;<br>product_id = &quot;Unknown&quot;<br>serial_number = &quot;Unknown&quot;<br># Try to match device from PnPEntity with USB VID/PID<br>for device in c.Win32_PnPEntity():<br>if device.PNPDeviceID and &quot;USB&quot; in device.PNPDeviceID:<br>match = re.search(r&quot;VID_([0–9A-F]{4})&amp;PID_([0–9A-F]{4})&quot;, device.PNPDeviceID, re.I)<br>if match:<br>vendor_id = match.group(1)<br>product_id = match.group(2)<br>serial_number = device.PNPDeviceID.split(&quot;\\&quot;)[-1]<br>break<br>return {<br>&quot;vendor_id&quot;: vendor_id,<br>&quot;product_id&quot;: product_id,<br>&quot;serial_number&quot;: serial_number,<br>&quot;volume_name&quot;: str(instance.VolumeName),<br>&quot;file_system&quot;: str(instance.FileSystem),<br>}<br>def preprocess_live(df):<br>df = df.fillna(&quot;Unknown&quot;)<br>for col in FEATURE_COLUMNS:<br>df[col] = df[col].astype(str)<br>df[col] = df[col].apply(lambda x: hash(x) % 10000)<br>return df<br>def monitor_usb():<br>watcher = c.Win32_LogicalDisk.watch_for(&quot;creation&quot;)<br>print(&quot;[INFO] Monitoring for USB device insertions…&quot;)<br>model = joblib.load(MODEL_PATH)<br>while True:<br>try:<br>usb = watcher()<br>info = extract_usb_info(usb)<br>df = pd.DataFrame([{k: info[k] for k in FEATURE_COLUMNS}])<br>df = preprocess_live(df)<br>prediction = model.predict(df[FEATURE_COLUMNS])<br>handle_detection(prediction[0], info)<br>except Exception as e:<br>print(&quot;[ERROR]&quot;, e)<br>time.sleep(2)<br>if __name__ == &quot;__main__&quot;:<br>monitor_usb()</pre><p><strong>Output:</strong></p><p>This will launch the USB monitor, which runs in the background and waits for USB events:</p><ul><li>When a USB device is plugged in:</li><li>It is automatically profiled</li><li>Classified as <strong>authorized</strong> or <strong>unauthorized</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*P0QO_FhXF60rKtVAvu3j3A.png" /></figure><p>Event is logged to logs/usb_activity.log</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MGNqvORnV8sB81hAud8Nlw.png" /></figure><h4>Step 5: Create a <a href="http://actions.py/">actions.py</a> (Live Detection &amp; Automated Response)</h4><p>Once a USB is inserted and predicted as authorized or unauthorized, the system can <strong>log</strong>, <strong>alert</strong>, or even <strong>block</strong>. Here’s how you handle it:</p><p><strong>Scripts : </strong><a href="http://actions.py/"><strong>actions.py</strong></a></p><pre>import datetime<br>import json<br>from win10toast import ToastNotifier<br>import ctypes # ← ADD THIS<br>LOG_PATH = &quot;logs/usb_activity.log&quot;<br>notifier = ToastNotifier()<br>def log_event(info, label):<br>log_entry = {<br>&quot;timestamp&quot;: datetime.datetime.now().isoformat(),<br>&quot;device_info&quot;: info,<br>&quot;classification&quot;: label<br>}<br>with open(LOG_PATH, &quot;a&quot;) as f:<br>f.write(json.dumps(log_entry) + &quot;\n&quot;)<br>print(&quot;[LOGGED] USB event logged.&quot;)<br>def show_popup(title, message):<br>ctypes.windll.user32.MessageBoxW(0, message, title, 0x40)<br>def handle_detection(prediction, info):<br>print(f&quot;[ACTION] Device classified as {prediction}&quot;)<br>log_event(info, prediction)<br>title = &quot;USB Device Alert&quot;<br>message = f&quot;{prediction.upper()} device detected:\nVendor: {info[&#39;vendor_id&#39;]}\nSerial: {info[&#39;serial_number&#39;]}&quot;<br># Show toast<br>notifier.show_toast(<br>&quot;USB Device Detected!&quot;,<br>message,<br>duration=5,<br>threaded=True<br>)<br># Show popup<br>show_popup(title, message)<br>if prediction == &quot;unauthorized&quot;:<br>print(&quot;[!] Unauthorized device detected!&quot;)</pre><p><strong>Output:<br></strong>A toast notification + pop-up alert is displayed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*L0I3Ds4QQNzuZ6EaNr2tMA.png" /></figure><h4>Step 6 : Visualization &amp; Analysis</h4><p>We log all USB activities. You can visualize:</p><ul><li>USB types over time</li><li>Unauthorized attempts</li><li>Most common vendors</li><li>Prediction confidence (if using predict_proba)</li></ul><p><strong>Script : </strong><a href="http://visualize.py/"><strong>visualize.py</strong></a></p><pre>import json<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>def load_logs():<br>with open(&quot;logs/usb_activity.log&quot;, &quot;r&quot;) as f:<br>logs = [json.loads(line.strip()) for line in f.readlines()]<br>return pd.DataFrame(logs)<br>def plot_device_stats():<br>df = load_logs()<br>df[&#39;timestamp&#39;] = pd.to_datetime(df[&#39;timestamp&#39;])<br>df[&#39;classification&#39;] = df[&#39;classification&#39;].astype(str)<br>df[&#39;timestamp&#39;].dt.date.value_counts().sort_index().plot(kind=&quot;bar&quot;)<br>plt.title(&quot;USB Events Over Time&quot;)<br>plt.xlabel(&quot;Date&quot;)<br>plt.ylabel(&quot;Insertions&quot;)<br>plt.show()<br>df[&#39;classification&#39;].value_counts().plot(kind=&quot;bar&quot;, color=[&quot;green&quot;, &quot;red&quot;])<br>plt.title(&quot;Authorized vs Unauthorized USBs&quot;)<br>plt.ylabel(&quot;Count&quot;)<br>plt.show()<br>if __name__ == &quot;__main__&quot;:<br>plot_device_stats()</pre><p><strong>Output:</strong></p><ul><li>USB insertions over time</li><li>Authorized vs unauthorized USBs (bar graph)</li></ul><h4>Outcome:</h4><p>This project demonstrates a practical application of machine learning to detect unauthorized USB device usage based on behavioral profiling. By training the model on a synthetic dataset that simulates real-world USB connection patterns, the system effectively distinguishes between authorized and suspicious device activity.</p><p>Key outcomes of this solution include:</p><ul><li>The system performs real-time monitoring of USB events and accurately flags unauthorized insertions based on behavioral attributes.</li><li>The classifier achieved perfect accuracy on the test data, correctly identifying both legitimate and unauthorized USB access attempts.</li><li>The solution is lightweight and runs efficiently in standard Windows environments without requiring complex infrastructure.</li><li>Behavioral profiling is used instead of static device allowlists, making the model more flexible and responsive to dynamic user environments.</li><li>Output is saved in structured formats (such as CSV), allowing easy integration with logging systems or SIEM platforms for further analysis and alerting.</li></ul><p>In summary, the project provides a foundation for building intelligent USB monitoring tools that enhance endpoint security through automation, pattern recognition, and behavior-driven alerts.</p><p>#AI&amp;ML #AI #ML #cybersecurity #blueteam #blueteamproject #cybersecurityproject</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf3fcbd53fae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Windows Process Anomaly Detection with AI & ML]]></title>
            <link>https://medium.com/@myth7672/windows-process-anomaly-detection-with-ai-ml-ed58163b8272?source=rss-0f351da37421------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed58163b8272</guid>
            <category><![CDATA[blue-team]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[trending]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[information-security]]></category>
            <dc:creator><![CDATA[Myth]]></dc:creator>
            <pubDate>Fri, 31 Oct 2025 16:36:15 GMT</pubDate>
            <atom:updated>2025-10-31T16:36:15.232Z</atom:updated>
            <content:encoded><![CDATA[<p>Monitor Windows processes and detect malicious activity with AI and machine learning.</p><h4><strong>Objective:</strong></h4><p>The primary goal of this project is to develop an intelligent system that monitors real-time Windows processes and classifies them as suspicious or legitimate using AI and machine learning techniques. It aims to enhance endpoint visibility and enable proactive detection of anomalous behavior based on process trees, command line length, and process metadata.</p><h4><strong>Tools and Libraries Used:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*I2zHOifXGXKjjSdKqb8uHg.png" /></figure><h4><strong>Prerequisites:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*065x4EmdIQh04_R3yF160w.png" /></figure><h4><strong>Folder Structure:</strong></h4><p>Process_Tree_Analyzer/</p><p>├── dataset/</p><p>│ └── initial_training.csv</p><p>├── logs/</p><p>│ └── process_activity.log</p><p>├── models/</p><p>│ └── process_classifier.pkl</p><p>├── scripts/</p><p>│ ├── train_model.py</p><p>│ ├── process_monitor.py</p><p>│ ├── actions.py</p><p>│ └── visualize.py</p><p>├── requirements.txt</p><h4><strong>Process Tree Analysis with AI+ML:</strong></h4><p>This system analyzes the process hierarchy and key metadata to construct a “process tree fingerprint.” For each observed process, we collect:</p><ul><li>Process name</li><li>Parent process name</li><li>Command-line length</li><li>Number of threads</li></ul><p>These features help to understand the context in which a process was launched. By training a GradientBoostingClassifier on these features, we build an ML model that can distinguish between typical and suspicious process trees. When a new process is spawned, the system compares it to known patterns to predict its legitimacy.</p><h4>Step 1 : Downloading &amp; Using the Dataset:</h4><p><strong>Option A:</strong><br> Public datasets for process monitoring are available on platforms like Kaggle, often sourced from <a href="https://www.kaggle.com/datasets/mehulkatara/windows-event-log">Sysmon logs or Windows event telemetry</a>. While these datasets are useful for large-scale modeling, they tend to include complex nested fields, noise, anonymized entities, and require heavy preprocessing. This makes real-time testing and small-scale experimentation more difficult without extensive cleaning and parsing.</p><p><strong>Option B (Selected):</strong><br> Due to the large size and complexity of Option A, we are going to use a synthetic dataset named sample_process_tree.csv. This sample contains clean, realistic representations of Windows process execution trees, making it ideal for training and demonstrating an ML model focused on detecting suspicious process behavior.</p><p><strong>Dataset Path:</strong> dataset/sample_process_tree.csv</p><p>A sample CSV is used to train the model with process metadata.</p><p>Process_name, parent_name, cmdline_length, thread_count, label</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*YzC41XprP7MAehURdWIcjQ.png" /></figure><h4><strong>Step 2: Create a train_model.py</strong></h4><p>This script:</p><ul><li>Loads initial_training_processes.csv</li><li>Encodes categorical values (process_name, parent_name)</li><li>Trains a <strong>Gradient Boosting Classifier</strong></li><li>Saves the trained model to models/process_classifier.pkl</li></ul><p><strong>Why this matters</strong>: The classifier learns what kind of processes are “legitimate” vs. “suspicious” based on:</p><ul><li>Process name (e.g. cmd.exe, notepad.exe)</li><li>Parent name (e.g. explorer.exe, services.exe)</li><li>Command line length (how complex the command is)</li><li>Thread count (often higher for GUI-based apps)</li></ul><p><strong>Script : train_model.py</strong></p><pre>import pandas as pd<br>from sklearn.ensemble import GradientBoostingClassifier<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import accuracy_score, classification_report<br>from sklearn.preprocessing import LabelEncoder<br>import joblib<br>FEATURES = [&#39;process_name&#39;, &#39;parent_name&#39;, &#39;cmdline_length&#39;, &#39;thread_count&#39;]<br>def preprocess(df):<br>df = df.fillna(&quot;Unknown&quot;)<br>for col in [&#39;process_name&#39;, &#39;parent_name&#39;]:<br>le = LabelEncoder()<br>df[col] = le.fit_transform(df[col].astype(str))<br>return df<br>def train():<br>df = pd.read_csv(&quot;dataset/initial_training.csv&quot;)<br>df = preprocess(df)<br>X = df[FEATURES]<br>y = df[&#39;label&#39;]<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, stratify=y)<br>clf = GradientBoostingClassifier()<br>clf.fit(X_train, y_train)<br>y_pred = clf.predict(X_test)<br>print(&quot;Accuracy:&quot;, accuracy_score(y_test, y_pred))<br>print(classification_report(y_test, y_pred))<br>joblib.dump(clf, &quot;models/process_classifier.pkl&quot;)<br>print(&quot;[+] Model saved to models/process_classifier.pkl&quot;)<br>if __name__ == &#39;__main__&#39;:<br>train()</pre><p><strong>Output:</strong></p><p>What the terminal output shows:</p><ul><li>A full classification report with precision, recall, F1-score.</li><li>Model evaluation summary (accuracy near 100%).</li><li>Confirmation of saved model and encoders.</li></ul><h4><strong>Step 3: Create a process_monitor.py</strong></h4><p>Monitors new processes and classifies them.</p><p>This script:</p><ul><li>Loads the trained model</li><li>Uses psutil to monitor all new processes</li><li>Extracts live metadata: name, parent, command line, threads</li><li>Converts it into the same format the model was trained on</li><li>Makes a prediction: suspicious or legitimate</li></ul><p><strong>Then it calls handle_detection()</strong>:</p><ul><li>Shows a <strong>Windows toast</strong> notification</li><li>Pops up a <strong>message box</strong></li><li>Logs the event to logs/process_activity.log in JSON format</li></ul><p><strong>Script : process_monitor.py</strong></p><pre>import psutil<br>import time<br>import pandas as pd<br>import joblib<br>from actions import handle_detection<br>MODEL_PATH = &quot;models/process_classifier.pkl&quot;<br>FEATURES = [&#39;process_name&#39;, &#39;parent_name&#39;, &#39;cmdline_length&#39;, &#39;thread_count&#39;]<br>model = joblib.load(MODEL_PATH)<br>seen_pids = set()<br>def extract_features(proc):<br>try:<br>cmdline = &quot; &quot;.join(proc.cmdline())<br>return {<br>&quot;process_name&quot;: proc.name(),<br>&quot;parent_name&quot;: proc.parent().name() if proc.parent() else &quot;None&quot;,<br>&quot;cmdline_length&quot;: len(cmdline),<br>&quot;thread_count&quot;: proc.num_threads()<br>}<br>except (psutil.NoSuchProcess, psutil.AccessDenied):<br>return None<br>def preprocess_live(df):<br>df = df.fillna(&quot;Unknown&quot;)<br>for col in [&#39;process_name&#39;, &#39;parent_name&#39;]:<br>df[col] = df[col].astype(str).apply(lambda x: hash(x) % 10000)<br>return df<br>def monitor():<br>print(&quot;[INFO] Monitoring new processes…&quot;)<br>while True:<br>for proc in psutil.process_iter([&#39;pid&#39;]):<br>if proc.info[&#39;pid&#39;] not in seen_pids:<br>seen_pids.add(proc.info[&#39;pid&#39;])<br>info = extract_features(proc)<br>if not info:<br>continue<br>df = pd.DataFrame([info])<br>df = preprocess_live(df)<br>pred = model.predict(df[FEATURES])<br>handle_detection(pred[0], info)<br>time.sleep(2)<br>if __name__ == &#39;__main__&#39;:<br>monitor()</pre><p><strong>Output:</strong></p><ul><li>It monitors running processes on the system.</li><li>Captures process attributes like process_name, parent_name, cmdline_length, and thread_count.</li><li>Each process is analyzed using the trained ML model.</li><li>If the model classifies it as suspicious, a popup alert box is triggered with the message:</li><li>“SUSPICIOUS process detected — cmd.exe (Parent: explorer.exe)”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*X_TQFQd47JDJop-FZzJ3JA.png" /></figure><p><strong>Output saved in .log file:</strong></p><pre>{<br>&quot;timestamp&quot;: &quot;2025–07–25T21:33:18&quot;,<br>&quot;process_info&quot;: {<br>&quot;process_name&quot;: &quot;cmd.exe&quot;,<br>&quot;parent_name&quot;: &quot;explorer.exe&quot;,<br>&quot;cmdline_length&quot;: 50,<br>&quot;thread_count&quot;: 5<br>},<br>&quot;classification&quot;: &quot;suspicious&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VpqT6XD0Yseg34zl1G9AZw.png" /></figure><h4><strong>Step 4: Create a actions.py</strong></h4><p>Handles toast and popup alerts + logging.</p><p><strong>Script : actions.py</strong></p><pre>import datetime<br>import json<br>from win10toast import ToastNotifier<br>import ctypes<br>LOG_PATH = &quot;logs/process_activity.log&quot;<br>notifier = ToastNotifier()<br>def log_event(info, label):<br>entry = {<br>&quot;timestamp&quot;: datetime.datetime.now().isoformat(),<br>&quot;process_info&quot;: info,<br>&quot;classification&quot;: label<br>}<br>with open(LOG_PATH, &quot;a&quot;) as f:<br>f.write(json.dumps(entry) + &quot;\n&quot;)<br>print(&quot;[LOGGED] Process event logged.&quot;)<br>def show_popup(title, message):<br>ctypes.windll.user32.MessageBoxW(0, message, title, 0x40)<br>def handle_detection(prediction, info):<br>print(f&quot;[ACTION] Process classified as {prediction}&quot;)<br>log_event(info, prediction)<br>msg = f&quot;{prediction.upper()} process detected:\n{info[&#39;process_name&#39;]} (Parent: {info[&#39;parent_name&#39;]})&quot;<br>notifier.show_toast(&quot;Process Monitor Alert&quot;, msg, duration=5, threaded=True)<br>show_popup(&quot;Process Alert&quot;, msg)</pre><p><strong>Output:</strong></p><p>Trigger message related to process is legitimate or Suspicious</p><h4><strong>Step 5: Create a visualize.py</strong></h4><p>Parses and visualizes logs using matplotlib.</p><p>This reads the JSON log file and shows:</p><ul><li>A bar chart of process alerts per day</li><li>A breakdown of how many were suspicious vs legitimate</li></ul><p><strong>Script : visualize.py</strong></p><pre>import json<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>LOG_PATH = &quot;logs/process_activity.log&quot;<br>def load_logs():<br>with open(LOG_PATH, &quot;r&quot;) as f:<br>return pd.DataFrame([json.loads(line) for line in f])<br>def plot():<br>df = load_logs()<br>df[&#39;timestamp&#39;] = pd.to_datetime(df[&#39;timestamp&#39;])<br>df[&#39;classification&#39;] = df[&#39;classification&#39;].astype(str)<br>df[&#39;timestamp&#39;].dt.date.value_counts().sort_index().plot(kind=&quot;bar&quot;)<br>plt.title(&quot;Process Events Over Time&quot;)<br>plt.xlabel(&quot;Date&quot;)<br>plt.ylabel(&quot;Executions&quot;)<br>plt.show()<br>df[&#39;classification&#39;].value_counts().plot(kind=&quot;bar&quot;, color=[&quot;green&quot;, &quot;red&quot;])<br>plt.title(&quot;Legitimate vs Suspicious Processes&quot;)<br>plt.ylabel(&quot;Count&quot;)<br>plt.show()<br>if __name__ == &#39;__main__&#39;:<br>plot()</pre><p><strong>Output:</strong></p><p><strong>Process Events Over Time graph:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*SrhiFd9409ncy-vl-0IAUg.png" /></figure><p><strong>Legitimate vs Suspicious Processes graph:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*3O6ih3UtbIKXHgLuR1HPAw.png" /></figure><p><strong>5.1 Feature Engineering Explained:<br></strong>In this project, the following features are extracted from each process to help the machine learning model understand its behavior:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*a5y9DeB_r4Vmb4hM4KMpKg.png" /></figure><p>These features together help build a “behavioral fingerprint” for each process. For example, if powershell.exe is launched by cmd.exe with a long, obfuscated command line and low thread count, it is likely to be suspicious. The model learns such patterns from the training data.</p><h4><strong>Step 6. Results and Insights:</strong></h4><p>The classifier was able to detect abnormal process behavior (e.g., cmd launched from explorer or powershell from cmd).</p><ul><li>Popup and toast alerts are triggered instantly upon classification.</li><li>Real-time monitoring has minimal performance impact.</li></ul><p><strong>6.1 Model Evaluation Metrics:<br></strong> The model performance is evaluated using standard metrics:</p><ul><li><strong>Accuracy:</strong> How many total predictions were correct</li><li><strong>Precision:</strong> Of all flagged suspicious, how many were actually bad</li><li><strong>Recall:</strong> Of all real threats, how many were caught</li></ul><h4><strong>Outcome:</strong></h4><p>This project gives us a simple but powerful tool to help defenders (blue teams) keep an eye on what’s happening inside a Windows system. It watches new processes as they start, checks their behavior, and tells us whether they look normal or suspicious using a machine learning model.</p><p>It works quietly in the background, without slowing down or affecting the system. Because it learns from data, the more you use it and train it, the better it gets at spotting suspicious activity. It can catch things like unusual use of PowerShell or when a process is started by something unexpected.</p><p>This system is also flexible. In the future, it can be improved to automatically stop bad processes, send alerts to other systems, or even detect new threats based on how unusual the behavior is. It’s useful for schools, labs, or even real organizations that want a light and smart way to protect their computers.</p><p>#cybersecurity #AL&amp;ML #blueteam #AL #ML #project #blueteamproject #cybersecurityproject</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed58163b8272" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI-Powered Phishing Email Detection Using ML Classifier]]></title>
            <link>https://medium.com/@myth7672/ai-powered-phishing-email-detection-using-ml-classifier-67c816ec733a?source=rss-0f351da37421------2</link>
            <guid isPermaLink="false">https://medium.com/p/67c816ec733a</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[defensive-security]]></category>
            <dc:creator><![CDATA[Myth]]></dc:creator>
            <pubDate>Fri, 31 Oct 2025 16:33:41 GMT</pubDate>
            <atom:updated>2025-10-31T16:33:41.575Z</atom:updated>
            <content:encoded><![CDATA[<p>Analyze email headers to detect phishing attempts using AI and machine learning classifiers.</p><h4>Objective:</h4><p>The objective of this project is to build an AI-powered system that can automatically detect whether an incoming email is phishing or legitimate by analyzing its header metadata. This detection is based on patterns learned from previously labeled email headers using machine learning algorithms.</p><p>Key email header fields like Subject, From, Return-Path, SPF Result, and Received path are used for feature engineering. These features are then input into a machine learning model to classify emails as phishing or legitimate.</p><h4>Tools &amp; Libraries Used:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*TVVbcwnmhvluQAcRsSMqMw.png" /></figure><h4>Prerequisites:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*HsEuXWKCqfu9YF4ukMSjqg.png" /></figure><h4>AI/ML Inclusion Workflow:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*-TKhutgbMs8gq7avuUjPaA.png" /></figure><h4>Use Case Scenario:</h4><p>An organization wants to automate the detection of phishing emails at the gateway level. By analyzing the metadata of incoming emails using AI/ML models, the system can flag suspicious emails before they reach employees.</p><h4>Actors:</h4><ul><li>Legitimate Sender: A real person or trusted organization.</li><li>Phishing Attacker: A malicious sender trying to trick users.</li></ul><h4>Folder Structure:</h4><p>phishing_email_ai_ml/</p><p>├── train_model.py # Trains the ML model</p><p>├── analyze_header.py # Predicts class of new email headers</p><p>├── requirements.txt # Required packages</p><p>├── dataset/</p><p>│ └── phishing_email_headers_dataset_natural_ratio.csv</p><p>├── models/</p><p>│ └── phishing_header_classifier.pkl</p><p>│ └── confusion_matrix.png</p><h4>Step 1: Downloading &amp; Using the Dataset</h4><p><strong>Option A:</strong> Use a <a href="https://www.kaggle.com/datasets/naserabdullahalam/phishing-email-dataset?select=phishing_email.csv">public dataset from Kaggle</a> that includes real-world email headers with phishing and legitimate classifications.</p><p><strong>Option B:</strong> Use a synthetic sample dataset of 100 email header records generated using the Python Faker library.</p><p>We are going to use <strong>Option B</strong> for this project. Option A is large and may contain unnecessary complexity for fast experimentation. Our sample dataset contains structured header metadata similar to real email servers, without message content or attachments — allowing the model to learn from header patterns alone.</p><p><strong>Label Distribution:</strong></p><ul><li>65 emails are labeled as <strong>legitimate</strong></li><li>35 emails are labeled as <strong>phishing</strong></li></ul><p>This approach allows faster model training and clear analysis while keeping the dataset size manageable for demonstration.</p><h4>Step 2: Create a train_model.py</h4><p><strong>Purpose</strong>: This script is responsible for handling the entire model training pipeline. It performs the following tasks:</p><ul><li>Loads the phishing email header dataset from the dataset directory</li><li>Preprocesses and encodes textual fields such as Subject, SPF result, From email, and Return-Path</li><li>Splits the dataset into training and testing sets while maintaining label distribution</li><li>Trains a RandomForestClassifier model to classify phishing vs. legitimate emails</li><li>Saves the trained model to the models folder using Joblib for future use</li><li>Evaluates the model using accuracy score, classification report, and confusion matrix</li><li>Generates and saves a confusion matrix visualization in the models folder for analysis</li></ul><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>import joblib<br>from sklearn.model_selection import train_test_split<br>from sklearn.preprocessing import LabelEncoder<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.metrics import classification_report, confusion_matrix, accuracy_score<br># Load dataset<br>df = pd.read_csv(&quot;dataset/phishing_email_headers_dataset_natural_ratio.csv&quot;)<br>df.dropna(inplace=True)<br># Encode features<br>le_subject = LabelEncoder()<br>le_spf = LabelEncoder()<br>le_from = LabelEncoder()<br>le_return = LabelEncoder()<br>df[&quot;Subject_enc&quot;] = le_subject.fit_transform(df[&quot;Subject&quot;])<br>df[&quot;SPF_enc&quot;] = le_spf.fit_transform(df[&quot;SPF_Result&quot;])<br>df[&quot;From_enc&quot;] = le_from.fit_transform(df[&quot;From_Email&quot;])<br>df[&quot;Return_enc&quot;] = le_return.fit_transform(df[&quot;Return_Path&quot;])<br>X = df[[&quot;Subject_enc&quot;, &quot;SPF_enc&quot;, &quot;From_enc&quot;, &quot;Return_enc&quot;]]<br>y = df[&quot;Label&quot;].map({&quot;legit&quot;: 0, &quot;phishing&quot;: 1})<br># Split data<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)<br># Train model<br>model = RandomForestClassifier(n_estimators=100, random_state=42)<br>model.fit(X_train, y_train)<br># Save model<br>joblib.dump(model, &quot;models/phishing_header_classifier.pkl&quot;)<br># Evaluate<br>y_pred = model.predict(X_test)<br>print(&quot;Accuracy:&quot;, accuracy_score(y_test, y_pred))<br>print(&quot;\nClassification Report:\n&quot;, classification_report(y_test, y_pred))<br># Confusion matrix<br>cm = confusion_matrix(y_test, y_pred)<br>sns.heatmap(cm, annot=True, fmt=&quot;d&quot;, cmap=&quot;Blues&quot;)<br>plt.title(&quot;Confusion Matrix&quot;)<br>plt.xlabel(&quot;Predicted&quot;)<br>plt.ylabel(&quot;Actual&quot;)<br>plt.tight_layout()<br>plt.savefig(&quot;models/confusion_matrix.png&quot;)<br>plt.show()</pre><p><strong>Output:</strong></p><p>When you run train_model.py, the terminal will print the model’s training accuracy and a classification report that looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*smMbwOWCC7YE-9HfMpkNyg.png" /></figure><p>You will also see a confusion matrix image (confusion_matrix.png) saved inside the models/ folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*1fFNDPkD195H_icptKP-xw.png" /></figure><h4>Step 3: Create a analyze_header.py</h4><p><strong>Purpose</strong>: This script is designed to test the trained model by making predictions on new email headers. Its main goal is to determine whether a given email is legitimate or a phishing attempt based on the metadata provided in the header. It works by doing the following:</p><ul><li>Loads the pre-trained model (phishing_header_classifier.pkl) from the models folder.</li><li>Reads the same dataset used during training to recreate the LabelEncoder transformations for each categorical field such as Subject, SPF result, From_Email, and Return_Path.</li><li>Accepts a manually defined sample email header (you can replace this with real-time input or integration in production).</li><li>Encodes the sample header using the previously fitted encoders to match the same format as training data.</li><li>Feeds the encoded data into the model and prints out the predicted result: either “Phishing” or “Legit”.</li></ul><p>This script is useful for evaluating single email headers or integrating into larger blue team tools where email headers are extracted and checked in real time.</p><pre>import joblib<br>import pandas as pd<br>from sklearn.preprocessing import LabelEncoder<br># Define 15 realistic email header samples<br>samples = [<br>{<br>&quot;Subject&quot;: &quot;Verify Your Account Immediately&quot;,<br>&quot;SPF_Result&quot;: &quot;fail&quot;,<br>&quot;From_Email&quot;: &quot;admin@paypal-update.com&quot;,<br>&quot;Return_Path&quot;: &quot;bounce@paypal.com&quot;<br>},<br>{<br>&quot;Subject&quot;: &quot;Meeting Agenda for Tomorrow&quot;,<br>&quot;SPF_Result&quot;: &quot;pass&quot;,<br>&quot;From_Email&quot;: &quot;manager@company.com&quot;,<br>&quot;Return_Path&quot;: &quot;manager@company.com&quot;<br>},<br>{<br>&quot;Subject&quot;: &quot;Security Alert: Unauthorized Access&quot;,<br>&quot;SPF_Result&quot;: &quot;fail&quot;,<br>&quot;From_Email&quot;: &quot;support@chasebank-login.com&quot;,<br>&quot;Return_Path&quot;: &quot;noreply@alerts.com&quot;<br>},<br>{<br>&quot;Subject&quot;: &quot;Your Amazon Order Has Shipped&quot;,<br>&quot;SPF_Result&quot;: &quot;pass&quot;,<br>&quot;From_Email&quot;: &quot;no-reply@amazon.com&quot;,<br>&quot;Return_Path&quot;: &quot;no-reply@amazon.com&quot;<br>},<br>{<br>&quot;Subject&quot;: &quot;Update Your Billing Info&quot;,<br>&quot;SPF_Result&quot;: &quot;fail&quot;,<br>&quot;From_Email&quot;: &quot;account-update@netflix-payment.com&quot;,<br>&quot;Return_Path&quot;: &quot;bounce@netflix.com&quot;<br>},<br>{<br>&quot;Subject&quot;: &quot;Unusual Login Attempt Detected&quot;,<br>&quot;SPF_Result&quot;: &quot;fail&quot;,<br>&quot;From_Email&quot;: &quot;alerts@icloud-security.com&quot;,<br>&quot;Return_Path&quot;: &quot;noreply@icloud.com&quot;<br>},<br>{<br>&quot;Subject&quot;: &quot;Team Outing This Friday&quot;,<br>&quot;SPF_Result&quot;: &quot;pass&quot;,<br>&quot;From_Email&quot;: &quot;hr@companycorp.com&quot;,<br>&quot;Return_Path&quot;: &quot;hr@companycorp.com&quot;<br>},<br>{<br>&quot;Subject&quot;: &quot;Claim Your Reward Now&quot;,<br>&quot;SPF_Result&quot;: &quot;fail&quot;,<br>&quot;From_Email&quot;: &quot;prizes@freegiftcards.com&quot;,<br>&quot;Return_Path&quot;: &quot;offers@spamzone.org&quot;<br>},<br>{<br>&quot;Subject&quot;: &quot;Thanks for Your Purchase!&quot;,<br>&quot;SPF_Result&quot;: &quot;pass&quot;,<br>&quot;From_Email&quot;: &quot;sales@flipkart.com&quot;,<br>&quot;Return_Path&quot;: &quot;sales@flipkart.com&quot;<br>},<br>{<br>&quot;Subject&quot;: &quot;Urgent: Account Suspension Notice&quot;,<br>&quot;SPF_Result&quot;: &quot;fail&quot;,<br>&quot;From_Email&quot;: &quot;helpdesk@banking-secure.com&quot;,<br>&quot;Return_Path&quot;: &quot;bounce@securitynotice.com&quot;<br>},<br>{<br>&quot;Subject&quot;: &quot;Client Feedback Attached&quot;,<br>&quot;SPF_Result&quot;: &quot;pass&quot;,<br>&quot;From_Email&quot;: &quot;clientservices@xyzconsulting.com&quot;,<br>&quot;Return_Path&quot;: &quot;clientservices@xyzconsulting.com&quot;<br>},<br>{<br>&quot;Subject&quot;: &quot;Payment Failed - Action Required&quot;,<br>&quot;SPF_Result&quot;: &quot;fail&quot;,<br>&quot;From_Email&quot;: &quot;billing@apple-service-support.com&quot;,<br>&quot;Return_Path&quot;: &quot;payments@supportmail.cc&quot;<br>},<br>{<br>&quot;Subject&quot;: &quot;Your Uber Trip Receipt&quot;,<br>&quot;SPF_Result&quot;: &quot;pass&quot;,<br>&quot;From_Email&quot;: &quot;no-reply@uber.com&quot;,<br>&quot;Return_Path&quot;: &quot;no-reply@uber.com&quot;<br>},<br>{<br>&quot;Subject&quot;: &quot;Welcome to the Platform!&quot;,<br>&quot;SPF_Result&quot;: &quot;pass&quot;,<br>&quot;From_Email&quot;: &quot;support@newservice.com&quot;,<br>&quot;Return_Path&quot;: &quot;support@newservice.com&quot;<br>},<br>{<br>&quot;Subject&quot;: &quot;Invoice Overdue - Please Respond&quot;,<br>&quot;SPF_Result&quot;: &quot;fail&quot;,<br>&quot;From_Email&quot;: &quot;collections@fake-invoice-center.biz&quot;,<br>&quot;Return_Path&quot;: &quot;billing@scamresponse.net&quot;<br>}<br>]<br># Load dataset for encoder training<br>df = pd.read_csv(&quot;dataset/phishing_email_headers_dataset_natural_ratio.csv&quot;)<br># Fit encoders on training data<br>le_subject = LabelEncoder().fit(df[&quot;Subject&quot;])<br>le_spf = LabelEncoder().fit(df[&quot;SPF_Result&quot;])<br>le_from = LabelEncoder().fit(df[&quot;From_Email&quot;])<br>le_return = LabelEncoder().fit(df[&quot;Return_Path&quot;])<br># Load trained model<br>model = joblib.load(&quot;models/phishing_header_classifier.pkl&quot;)<br># Store results for CSV export<br>results = []<br># Loop through each sample and predict<br>for i, sample in enumerate(samples, 1):<br>encoded_input = [<br>le_subject.transform([sample[&quot;Subject&quot;]])[0] if sample[&quot;Subject&quot;] in le_subject.classes_ else 0,<br>le_spf.transform([sample[&quot;SPF_Result&quot;]])[0] if sample[&quot;SPF_Result&quot;] in le_spf.classes_ else 0,<br>le_from.transform([sample[&quot;From_Email&quot;]])[0] if sample[&quot;From_Email&quot;] in le_from.classes_ else 0,<br>le_return.transform([sample[&quot;Return_Path&quot;]])[0] if sample[&quot;Return_Path&quot;] in le_return.classes_ else 0<br>]<br>X_input = pd.DataFrame([encoded_input], columns=[&quot;Subject_enc&quot;, &quot;SPF_enc&quot;, &quot;From_enc&quot;, &quot;Return_enc&quot;])<br>prediction = model.predict(X_input)[0]<br>result = &quot;Phishing&quot; if prediction == 1 else &quot;Legit&quot;<br># Print to console<br>print(f&quot;\n[{i}] Subject: {sample[&#39;Subject&#39;]}&quot;)<br>print(f&quot; From: {sample[&#39;From_Email&#39;]}&quot;)<br>print(f&quot; SPF: {sample[&#39;SPF_Result&#39;]} | Return-Path: {sample[&#39;Return_Path&#39;]}&quot;)<br>print(f&quot; ➤ Prediction: {result}&quot;)<br># Store result<br>sample_row = sample.copy()<br>sample_row[&quot;Prediction&quot;] = result<br>results.append(sample_row)<br># Save results to CSV<br>pd.DataFrame(results).to_csv(&quot;detection_results.csv&quot;, index=False)<br>print(&quot;\n All predictions logged to detection_results.csv&quot;)</pre><p><strong>“ </strong>For the purpose of testing and demonstration, we used a small curated sample of 15 synthetic email headers, representing a balanced mix of phishing and legitimate examples. However, for production-level training or more robust experimentation, publicly available datasets from platforms like<a href="https://www.kaggle.com/"> Kaggle</a> can be integrated. These datasets often include thousands of real-world phishing and spam emails that provide deeper feature variance, better generalization, and help in training more resilient AI/ML models. <strong>“</strong></p><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*KkO35-hy_AhjdSUx2orqwQ.png" /></figure><p>When you run analyze_header.py, the script evaluates the specific email header defined in the sample dictionary within the script itself. This sample includes fields such as the Subject, SPF_Result, From_Email, and Return_Path.</p><p>For example, the default email checked is:</p><ul><li>Subject: “Verify Your Account Immediately”</li><li>SPF_Result: “fail”</li><li>From_Email: “admin@paypal-update.com”</li><li>Return_Path: “bounce@paypal.com”</li></ul><p>This input is designed to mimic a common phishing attempt, where the sender tries to look like a trusted service (e.g., PayPal) but with mismatched return paths and SPF failures.</p><p>The script transforms these header fields using the same label encoders used during model training, passes the encoded values to the classifier, and prints the classification result.</p><blockquote>Phishing <strong>OR:</strong> Legit</blockquote><p>These outputs will appear in your terminal or console window and in detection_results.csv too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*FeJ2gyoxKzI92Tc5dNT8UQ.png" /></figure><h4>Step 4: Visualizations (Optional):</h4><p><strong>Label Distribution Plot</strong></p><p>To ensure balanced model training, we visualize the number of phishing vs. legitimate samples:</p><pre>import seaborn as sns<br>import matplotlib.pyplot as plt<br>sns.countplot(data=df, x=&#39;Label&#39;)<br>plt.title(&#39;Distribution of Email Labels&#39;)<br>plt.xlabel(&#39;Email Type&#39;)<br>plt.ylabel(&#39;Count&#39;)<br>plt.tight_layout()<br>plt.show()</pre><p>This graph shows that phishing and legit emails are imbalanced by design, simulating a real-world inbox where phishing is less frequent.</p><h4>Feature Correlation Heatmap</h4><p>To explore how encoded features relate to each other:</p><pre>import seaborn as sns<br>import matplotlib.pyplot as plt<br>corr = df[[&quot;Subject_enc&quot;, &quot;SPF_enc&quot;, &quot;From_enc&quot;, &quot;Return_enc&quot;]].corr()<br>sns.heatmap(corr, annot=True, cmap=&quot;YlGnBu&quot;)<br>plt.title(&quot;Feature Correlation Heatmap&quot;)<br>plt.tight_layout()<br>plt.show()</pre><p>This helps us understand which features are redundant and which are unique contributors to the classification.</p><h4>Step 5: Processing Pipeline (ASCII Diagram)</h4><p>Below is a conceptual view of the ML pipeline:</p><p>+ — — — — — — — — — +</p><p>| Email Header |</p><p>+ — — — — — — — — — +</p><p>|</p><p>+ — — — — — — — — — +</p><p>| Extract Fields | ← Subject, SPF_Result, etc.</p><p>+ — — — — — — — — — +</p><p>|</p><p>+ — — — — — — — — — — -+</p><p>| Feature Encoding |</p><p>+ — — — — — — — — — — -+</p><p>|</p><p>+ — — — — — — — — — — +</p><p>| ML Model (RF) |</p><p>+ — — — — — — — — — — +</p><p>|</p><p>+ — — — — — — — — — — +</p><p>| Prediction Output |</p><p>+ — — — — — — — — — — +</p><p>These steps happen in real-time once the model is trained and deployed.</p><h4>Step 6: Results &amp; Insights</h4><ul><li>Accuracy: Approximately 90%</li><li>Model correctly detects phishing emails based on only header data</li><li>False positives are minimal and acceptable in enterprise settings</li></ul><h4>Step 7: Outcome</h4><p>This project successfully resulted in a fully functional, AI-powered phishing detection tool that focuses solely on the analysis of email headers. By examining commonly found fields such as the Subject, From address, Return-Path, and SPF results, the model can differentiate between legitimate and phishing emails without inspecting the email body or links.</p><ul><li>A complete and lightweight email phishing detection system was designed and built from scratch, customized for blue team operations.</li><li>The system relies solely on structured metadata from email headers, ensuring faster performance and compatibility with existing mail systems.</li><li>The project achieved high accuracy (~90%) with a Random Forest classifier, providing solid reliability while keeping the model explainable and fast.</li><li>This approach significantly reduces false negatives (phishing emails missed) and maintains a low false-positive rate, ensuring minimal disruption to regular communication.</li><li>The modular structure of the code makes it easy to integrate with Security Information and Event Management (SIEM) tools or into enterprise email filtering pipelines.</li><li>The use of a synthetic but realistic dataset ensures the model generalizes well to new, unseen data while avoiding dependency on sensitive corporate datasets.</li><li>The entire pipeline, from data preprocessing to model training and real-time inference, is built to run in a Windows environment using VS Code and Python, making it ideal for educational, research, or operational security teams.</li><li>The solution can easily be scaled to work on live email streams or as a backend engine for browser plugins, Office365 filters, or secure email gateways.</li></ul><p>The overall outcome is a robust, adaptable, and ready-to-use machine learning pipeline for phishing detection that can be deployed in a variety of real-world cybersecurity settings. lightweight phishing header detection system was developed.</p><ul><li>It performs fast predictions using Random Forest.</li><li>Works entirely on header fields, no need to scan the email body.</li></ul><p>#cybersecurity #AL&amp;ML #blueteam #AL #ML #project #blueteamproject #cybersecurityproject</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67c816ec733a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Anomaly Detection in Network Traffic Using AI & ML (Zeek Logs)]]></title>
            <link>https://medium.com/@myth7672/anomaly-detection-in-network-traffic-using-ai-ml-zeek-logs-a47ccb88f4af?source=rss-0f351da37421------2</link>
            <guid isPermaLink="false">https://medium.com/p/a47ccb88f4af</guid>
            <dc:creator><![CDATA[Myth]]></dc:creator>
            <pubDate>Fri, 24 Oct 2025 11:26:12 GMT</pubDate>
            <atom:updated>2025-10-24T11:26:12.283Z</atom:updated>
            <content:encoded><![CDATA[<p>Detect unusual network behavior using Zeek logs and AI-based anomaly detection techniques.</p><h4>Objective:</h4><p>The goal of this project is to detect anomalies in network traffic using machine learning. We used Zeek logs and applied an unsupervised learning algorithm — Isolation Forest — to identify unusual network behavior without needing labeled data.</p><p>This solution is helpful for Blue Teams to spot early signs of attacks, data leaks, or policy violations by learning what “normal” traffic looks like and flagging anything that doesn’t fit that pattern.</p><h4>Tools &amp; library Requirements:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*HHoMKB2K5nTk4-nP0ONGPA.png" /></figure><h4><strong>Prerequisites:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*wlnBXM3HTug5A0MViBM_XQ.png" /></figure><h4>AI/ML Inclusion Workflow:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*7IJSFFkRso0ENgeuOTsUyA.png" /></figure><h4><strong>Folder Structure:</strong></h4><p>├── data/</p><p>│ └── conn.log # Zeek network traffic log</p><p>├── models/</p><p>│ ├── model.pkl # Trained Isolation Forest model</p><p>│ └── features.pkl # List of features used for training</p><p>├── output/</p><p>│ ├── conn_scaled.csv # Cleaned dataset</p><p>│ ├── anomaly_results.csv # Results with anomaly labels</p><p>│ └── new_conn_scaled.csv # Sanitized features for reuse</p><p>├── visuals/</p><p>│ ├── scatter_plot.png</p><p>│ ├── heatmap.png</p><p>│ └── score_distribution.png</p><p>└── src/</p><p>├── preprocess.py # Parses &amp; preprocesses Zeek logs</p><p>├── train_model.py # Trains Isolation Forest</p><p>└── detect.py # Performs anomaly detection</p><h4><strong>Step 1: Downloading &amp; Using the Dataset (</strong><a href="https://www.kaggle.com/datasets/mimansari/dns-and-connections-log-zeek-or-corelight"><strong>Zeek conn.log</strong></a><strong> )</strong></h4><p>The<a href="https://www.kaggle.com/datasets/mimansari/dns-and-connections-log-zeek-or-corelight"> primary dataset</a> used is the Zeek-generated conn.log, which contains structured connection metadata such as IPs, ports, protocols, bytes transferred, duration, etc.</p><p>Each log entry is preprocessed and transformed into features usable by ML models. Columns like proto, duration, orig_bytes, resp_bytes, and conn_state are selected and one-hot encoded where needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xxwnYNXcd-M-Vo8n9DKjEw.png" /></figure><h4><strong>Step 2: Create a preprocess.py</strong></h4><ul><li>Read Zeek conn.log.</li><li>Selects important features (proto, duration, orig_bytes, resp_bytes, conn_state).</li><li>Cleans data and applies one-hot encoding.</li><li>Exports the cleaned dataset.</li></ul><p><strong>Script : preprocess.py</strong></p><pre>import pandas as pd<br>def parse_conn_log_to_df(filepath=&quot;data/conn.log&quot;):<br>with open(filepath, &#39;r&#39;) as f:<br>lines = [line for line in f if not line.startswith(&quot;#&quot;)]<br>raw = [line.strip().split(&#39;\t&#39;) for line in lines]<br>columns = [<br>&quot;ts&quot;, &quot;uid&quot;, &quot;id.orig_h&quot;, &quot;id.orig_p&quot;, &quot;id.resp_h&quot;, &quot;id.resp_p&quot;,<br>&quot;proto&quot;, &quot;service&quot;, &quot;duration&quot;, &quot;orig_bytes&quot;, &quot;resp_bytes&quot;,<br>&quot;conn_state&quot;, &quot;local_orig&quot;, &quot;local_resp&quot;, &quot;missed_bytes&quot;,<br>&quot;history&quot;, &quot;orig_pkts&quot;, &quot;orig_ip_bytes&quot;, &quot;resp_pkts&quot;, &quot;resp_ip_bytes&quot;,<br>&quot;tunnel_parents&quot;<br>]<br>df_full = pd.DataFrame(raw, columns=columns)<br># Save the identifying fields for later<br>id_cols = df_full[[&quot;ts&quot;, &quot;uid&quot;, &quot;id.orig_h&quot;, &quot;id.resp_h&quot;]].copy()<br># Select only ML-useful features<br>df = df_full[[&quot;proto&quot;, &quot;duration&quot;, &quot;orig_bytes&quot;,<br>&quot;resp_bytes&quot;, &quot;conn_state&quot;]].copy()<br>df.replace(&quot;-&quot;, 0, inplace=True)<br>df[[&quot;duration&quot;, &quot;orig_bytes&quot;, &quot;resp_bytes&quot;]] = df[[<br>&quot;duration&quot;, &quot;orig_bytes&quot;, &quot;resp_bytes&quot;]].astype(float)<br>df = pd.get_dummies(df, columns=[&quot;proto&quot;, &quot;conn_state&quot;])<br># Save clean ML features (for training)<br>df.to_csv(&quot;output/conn_scaled.csv&quot;, index=False)<br># Save ML features + ID columns (for detection results)<br>df_with_ids = pd.concat([id_cols, df], axis=1)<br>df_with_ids.to_csv(&quot;output/conn_scaled_with_ids.csv&quot;, index=False)<br>print(&quot;Clean file Created…&quot;)<br>return df</pre><p><strong>Output:</strong></p><p>This script parses the raw conn.log file generated by Zeek and transforms it into a clean, feature-specific dataset ready for ML training.</p><ul><li><strong>What It Contains:</strong> Cleaned data with selected fields like duration, orig_bytes, resp_bytes, proto, and conn_state, with one-hot encoding applied.</li><li><strong>Purpose:</strong> Prepares input for model training by removing noise and irrelevant columns.</li><li>File generated to output/conn_scaled_with_ids.csv</li></ul><h4><strong>Step 3: Create train_model.py</strong></h4><ul><li>Loads cleaned data (output/conn_scaled_with_ids.csv).</li><li>Trains Isolation Forest (100 trees, 10% contamination).</li><li>Saves the trained model and feature list.</li></ul><p><strong>Script : train_model.py</strong></p><pre>from sklearn.ensemble import IsolationForest<br>import joblib<br>from preprocess import parse_conn_log_to_df<br>def train_model():<br>print(&quot;[*] Loading and parsing conn.log for training…&quot;)<br>df_full = parse_conn_log_to_df()<br># Select only relevant numeric features<br>features = [&quot;duration&quot;, &quot;orig_bytes&quot;, &quot;resp_bytes&quot;]<br>df = df_full[features].copy()<br># You could also add any one-hot encoded features here if needed<br>print(&quot;[*] Training Isolation Forest model…&quot;)<br>model = IsolationForest(n_estimators=100, contamination=0.1, random_state=42)<br>model.fit(df)<br># Save model and features<br>joblib.dump(model, &quot;models/model.pkl&quot;)<br>joblib.dump(df.columns.tolist(), &quot;models/features.pkl&quot;) # So we can match features during detection<br>print(&quot;[+] Model trained and saved to models/model.pkl&quot;)<br>print(&quot;[+] Feature list saved to models/features.pkl&quot;)<br>if __name__ == &quot;__main__&quot;:<br>train_model()</pre><p><strong>Output:</strong></p><ul><li>File Generated: models/model.pkl</li><li>The trained ML model is stored for reuse.</li><li>File Generated: models/features.pkl</li><li>Contains the list of features used during training to maintain consistency during prediction.</li><li>Optional: If a labeled dataset was manually added, a confusion matrix image may be saved as visuals/confusion_matrix.png.</li></ul><p><strong>Step 4: Create a file detect.py</strong></p><ul><li>Loads model and cleaned log.</li><li>Predicts anomaly score and label (-1 for anomaly, 1 for normal).</li><li>Saves results and generates:</li><li>Scatter plot</li><li>Heatmap</li><li>Score distribution</li></ul><p><strong>Script : detect.py</strong></p><pre>import pandas as pd<br>import joblib<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>from preprocess import parse_conn_log_to_df<br>def detect_anomalies():<br>print(&quot;[*] Loading and parsing conn.log…&quot;)<br>df_full = parse_conn_log_to_df()<br># Keep only the features used during training<br>features = [&quot;duration&quot;, &quot;orig_bytes&quot;, &quot;resp_bytes&quot;]<br>df = df_full[features].copy()<br>print(&quot;[*] Loading trained model…&quot;)<br>model = joblib.load(&quot;models/model.pkl&quot;)<br>expected_features = joblib.load(&quot;models/features.pkl&quot;)<br># Ensure columns match between train and detection<br>for col in expected_features:<br>if col not in df.columns:<br>df[col] = 0 # add missing columns with 0<br>df = df[expected_features]<br>print(&quot;[*] Running anomaly detection…&quot;)<br>df_scores = df.copy()<br>df[&quot;anomaly_score&quot;] = model.decision_function(df_scores)<br>df[&quot;anomaly_label&quot;] = model.predict(df_scores)<br># Merge with original data (optional)<br>result_df = df_full.copy()<br>result_df[&quot;anomaly_score&quot;] = df[&quot;anomaly_score&quot;]<br>result_df[&quot;anomaly_label&quot;] = df[&quot;anomaly_label&quot;]<br># Save results<br>result_df.to_csv(&quot;output/anomaly_results.csv&quot;, index=False)<br>print(&quot;[+] Detection complete. Results saved to output/anomaly_results.csv&quot;)<br># Save new input data (sanitized) for reuse/testing<br>df.to_csv(&quot;output/new_conn_scaled.csv&quot;, index=False)<br># - - Visualizations - - <br>print(&quot;[*] Generating visualizations…&quot;)<br># Scatter plot<br>sns.scatterplot(x=&quot;duration&quot;, y=&quot;orig_bytes&quot;, hue=&quot;anomaly_label&quot;, data=result_df)<br>plt.title(&quot;Scatter Plot of Anomalies&quot;)<br>plt.savefig(&quot;visuals/scatter_plot.png&quot;)<br>plt.clf()<br># Correlation heatmap<br>sns.heatmap(df.corr(), annot=True, cmap=&#39;coolwarm&#39;)<br>plt.title(&quot;Feature Correlation Heatmap&quot;)<br>plt.savefig(&quot;visuals/heatmap.png&quot;)<br>plt.clf()<br># Anomaly score distribution<br>sns.histplot(df[&quot;anomaly_score&quot;], bins=50, kde=True, color=&#39;purple&#39;)<br>plt.title(&quot;Anomaly Score Distribution&quot;)<br>plt.xlabel(&quot;Anomaly Score&quot;)<br>plt.ylabel(&quot;Count&quot;)<br>plt.savefig(&quot;visuals/score_distribution.png&quot;)<br>plt.clf()<br>print(&quot;[+] Visualizations saved in /visuals folder.&quot;)<br>if __name__ == &quot;__main__&quot;:<br>detect_anomalies()</pre><p><strong>Output:</strong></p><ul><li><strong>File Generated:</strong> output/anomaly_results.csv</li><li>Contains the original Zeek log data with added fields:</li><li>anomaly_score: A numeric score (the lower, the more suspicious).</li><li>anomaly_label: -1 for anomalous, 1 for normal.</li><li>A minimal dataset with only transformed features and predictions for further ML use.</li></ul><p><strong>Step 5: Visualizations</strong></p><ul><li><strong>Scatter Plot</strong> — Duration vs Orig Bytes colored by anomaly label helps visualize traffic patterns.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*MdL5cUVHaQfQ3tt58n_swg.png" /></figure><ul><li><strong>Heatmap</strong> — Shows feature correlation to identify strong variable relationships.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*NIuN1uvcTjYUPRs0lywdKw.png" /></figure><ul><li><strong>Histogram</strong> — Distribution of anomaly scores indicates the spread of suspicious events.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*ysnpEd5Pe-zMTCSuD0O2zw.png" /></figure><p>These visuals provide Blue Teams with intuitive cues to identify traffic abnormalities.</p><p><strong>Use Case for Blue Teams:</strong></p><ul><li>Integrate with SIEM tools (Grafana, Splunk, ELK)</li><li>Alerting based on outlier scores</li><li>Correlate with EDR/Firewall logs for full context</li><li>Use as pre-filter before human triage</li></ul><p><strong>Flowchart of System:</strong></p><p>+ — — — — — — -+</p><p>| Zeek Logs | ← — — (Captured from PCAPs or live traffic)</p><p>+ — — — + — — — +</p><p>|</p><p>+ — — — — — — — — — — — — — +</p><p>| Data Preprocessing (Python)</p><p>| — Feature selection</p><p>| — One-hot encoding</p><p>+ — — — — — — — — — — — — — +</p><p>|</p><p>+ — — — — — — — — — — — — +</p><p>| Isolation Forest Model |</p><p>| — Train &amp; predict |</p><p>+ — — — — — — — — — — — — +</p><p>|</p><p>+ — — — — — — — — — — — — — — +</p><p>| Detection &amp; Visualization |</p><p>| — Save results |</p><p>| — Generate charts |</p><p>+ — — — — — — — — — — — — — — +</p><p>|</p><p>+ — — — — — — — — — -+</p><p>| SIEM/SOAR System |</p><p>| (Optional Integration)</p><p>+ — — — — — — — — — -+</p><h4><strong>Outcome:</strong></h4><p>We successfully designed and implemented a complete AI/ML-powered pipeline to detect anomalies in network traffic using Zeek logs. The entire system — from data preprocessing and model training to real-time anomaly detection and visual analysis — operates with minimal supervision and delivers actionable insights to Blue Team operators.</p><p>By utilizing the <strong>Isolation Forest</strong> algorithm, which is well-suited for unsupervised anomaly detection, we were able to identify outlier traffic patterns without needing a labeled dataset. This approach is highly effective in cybersecurity environments where labeled attack data is limited or nonexistent.</p><p>The trained model accurately flagged suspicious network activities, including:</p><ul><li><strong>Unusual durations</strong> in TCP/UDP connections</li><li><strong>Zero-byte responses</strong> in supposedly active sessions</li><li><strong>Rare protocol/connection state combinations</strong> that often signal reconnaissance or scanning</li><li><strong>Outlier traffic volumes</strong> suggesting exfiltration or malware callbacks</li></ul><p>Most importantly, this project showcases a real-world, SOC-ready tool that can assist analysts in identifying stealthy threats, reducing alert fatigue, and improving response time by surfacing only the most suspicious events.</p><p>This end-to-end pipeline not only strengthens the Blue Team’s detection capabilities but also lays the groundwork for future integration with <strong>SIEMs</strong>, <strong>SOAR platforms</strong>, or <strong>real-time dashboards</strong>, thereby helping bridge the gap between data volume and actionable threat intelligence.</p><p>#AI&amp;ML #AI #ML #cybersecurity #blueteam #blueteamproject #cybersecurityproject</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a47ccb88f4af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning for Suspicious DNS Query Detection]]></title>
            <link>https://medium.com/@myth7672/machine-learning-for-suspicious-dns-query-detection-5566f3aa9a52?source=rss-0f351da37421------2</link>
            <guid isPermaLink="false">https://medium.com/p/5566f3aa9a52</guid>
            <dc:creator><![CDATA[Myth]]></dc:creator>
            <pubDate>Fri, 24 Oct 2025 10:56:49 GMT</pubDate>
            <atom:updated>2025-10-24T10:57:48.412Z</atom:updated>
            <content:encoded><![CDATA[<p>Identify malicious or suspicious DNS queries in real-time using AI-powered models.</p><h4><strong>Objective:</strong></h4><p>This demo builds a real-world Blue Team PoC that detects <strong>suspicious DNS queries</strong> using <strong>AI rules</strong> and <strong>ML anomaly detection</strong>. We’ll catch:</p><ul><li>DGA (Domain Generation Algorithm) domains</li><li>DNS tunneling (data theft via DNS)</li><li>C2 traffic over DNS</li><li>Fast Flux DNS abuse</li></ul><h4><strong>Tools/ML Libraries Required:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*iiUzgwcOUzIG1BZqLyuNxQ.png" /></figure><p><strong>Files Structure:</strong></p><p>DNS-Detection-Project/</p><p>| — generate_dataset.py</p><p>| — main.py</p><p>| — detection.py</p><p>| — alert_tuning.py</p><p>| — synthetic_dns_logs.csv</p><p>| — detection_output.csv</p><p>| — alert_output.csv</p><p><strong>NOTE : </strong>We combined everything from detection.py and alert_tuning.py into one file: main.py. Now you just need to run main.py, and it will take care of both detecting suspicious DNS activity and cleaning up the alerts. No need to run anything else separately. It will automatically save the results in detection_output.csv and alert_output.csv.</p><h4><strong>Step 1: Create DNS Log Generator (generate_dataset.py)</strong></h4><p>This simulates realistic DNS queries using <strong>Faker</strong> and manually add <strong>malicious domains</strong>.</p><p><strong>Logic:</strong></p><ul><li>Adds both safe and malicious domains</li><li>Randomizes query hours and entropy</li></ul><p><strong>Script : generate_dataset.py</strong></p><pre>import pandas as pd<br>import random<br>from faker import Faker<br>fake = Faker()<br>malicious_domains = [&quot;random123.xysjdnqowiq.com&quot;, &quot;ads.tracking.info&quot;, &quot;api.telegram.org&quot;]<br>benign_domains = [&quot;google.com&quot;, &quot;yahoo.com&quot;, &quot;netflix.com&quot;, &quot;facebook.com&quot;]<br>data = []<br>for _ in range(100):<br>domain = random.choice(malicious_domains + benign_domains)<br>entropy = round(random.uniform(2.9, 5.2), 2)<br>hour = random.randint(0, 23)<br>data.append({&quot;query_name&quot;: f&quot;{random.randint(100, 999)}.{domain}&quot;, &quot;entropy&quot;: entropy, &quot;hour&quot;: hour})<br>pd.DataFrame(data).to_csv(&quot;synthetic_dns_logs.csv&quot;, index=False)</pre><p><strong>Output file: synthetic_dns_logs.csv</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*2T14rLS57cRDgGNSBtOtQg.png" /></figure><h4><strong>Step 2 : Add ML Detection Code (detection.py)</strong></h4><p>Everything is now combined in <strong>main.py</strong>:</p><p>In <a href="http://detectionb.py/">detection.py</a> uses Isolation Forest, a robust unsupervised learning method, to calculate anomaly scores based on domain entropy and time-of-day query frequency. This helps to isolate suspicious queries from normal traffic without needing labeled data.</p><p><strong>script : detection.py</strong></p><pre>import pandas as pd<br>from sklearn.ensemble import IsolationForest<br>def detect_anomalies(input_file, output_file):<br>df = pd.read_csv(input_file)<br>features = df[[&#39;entropy&#39;, &#39;hour&#39;]]<br>model = IsolationForest(n_estimators=100, contamination=0.25)<br>model.fit(features)<br>df[&#39;anomaly&#39;] = model.predict(features)<br>df[&#39;anomaly_score&#39;] = 1 - model.decision_function(features)<br>df.to_csv(output_file, index=False)</pre><p><strong>Output file:</strong> detection_output.csv → Raw anomaly scores</p><p><strong>Anomaly score</strong> near 1.0 = more suspicious</p><p><strong>Understanding Parameters: Entropy, Anomaly Score, and Severity</strong></p><ul><li><strong>Entropy</strong> is a statistical measure of randomness. Domains with high entropy (e.g., xysjdnqowiq.com) often represent dynamically generated names or encoded content and are commonly associated with malware.</li><li>Entropy is calculated using Shannon’s formula:</li><li>H=−∑p(x)⋅log⁡2p(x)H = -\sum{p(x) \cdot \log_2{p(x)}}</li><li><strong>Anomaly Score</strong> is derived from the Isolation Forest algorithm. A high score (near 1) indicates a high likelihood of malicious behavior. The anomaly column (-1 or 1) classifies each record.</li><li><strong>Severity &amp; Priority</strong>: These are derived from anomaly_score as follows:</li></ul><h4><strong>Step 3 : Add Alert Tuning Logic (alert_tuning.py)</strong></h4><p>This step <strong>converts numeric anomaly scores</strong> into human-friendly:</p><ul><li>Severity (High/Medium/Low)</li><li>Priority (1 = High, 4 = Info)</li></ul><p><strong>Script : alert_tuning.py</strong></p><pre>import pandas as pd<br>def tune_alerts(input_file, output_file):<br>df = pd.read_csv(input_file)<br>def score_to_severity(score):<br>if score &gt;= 0.9:<br>return &#39;High&#39;, 1<br>elif score &gt;= 0.75:<br>return &#39;Medium&#39;, 2<br>elif score &gt;= 0.55:<br>return &#39;Low&#39;, 3<br>else:<br>return &#39;Informational&#39;, 4<br>df[[&#39;severity&#39;, &#39;priority&#39;]] = df[&#39;anomaly_score&#39;].apply(lambda x: pd.Series(score_to_severity(x)))<br>df.to_csv(output_file, index=False)</pre><p><strong>Output file:</strong> alert_output.csv → Final alerts with severity levels</p><p>This is the <strong>final alert</strong> file with everything Blue Teams need.</p><h4>Step 4 : Execute Full Pipeline (<a href="http://main.py/">main.py</a>)</h4><p>To run one single script (main.py) that:</p><ul><li>Loads DNS data</li><li>Applies ML to detect threats</li><li>Adds severity levels (High/Medium/Low)</li><li>Saves results to .csv files for review</li></ul><p>This step <strong>combines everything you’ve built</strong> — so you don’t need to run detection or alert tuning separately. Just one click!</p><p><strong>How AI/ML Helps:</strong> Seamlessly combines each AI/ML-powered step into an automated defense mechanism.</p><p><strong>Script : </strong><a href="http://main.py/"><strong>main.py</strong></a></p><pre>from detection import detect_anomalies<br>from alert_tuning import tune_alerts<br>detect_anomalies(&quot;synthetic_dns_logs.csv&quot;, &quot;detection_output.csv&quot;)<br>tune_alerts(&quot;detection_output.csv&quot;, &quot;alert_output.csv&quot;)</pre><p><a href="http://main.py/"><strong>Main.py</strong></a><strong> Code execution:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*co4cNHGacuOK0oyzzWUf4w.png" /></figure><p><strong>Output Samples (detection_output.csv):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*fTqYGUuh09Y0fGk322eLxA.png" /></figure><p><strong>Output Samples (alert_output.csv):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*07PFdWE6EvP_tUHZD9YE3Q.png" /></figure><p>In this PoC, we use synthetic data for controlled testing. In production, real DNS telemetry would be sourced from:</p><ul><li>DNS servers (e.g., BIND, Windows DNS)</li><li>Network sensors (e.g., Zeek, Suricata)</li><li>SIEM platforms (e.g., Splunk, Sentinel)</li><li>Endpoint detection systems (e.g., CrowdStrike, Defender)</li></ul><h4><strong>How AI &amp; ML Helps in Each Step:</strong></h4><ul><li><strong>Data Generation</strong>: Simulates a wide range of behavioral patterns for testing models.</li><li><strong>Feature Extraction</strong>: Automates complex indicators like entropy without static rules.</li><li><strong>Anomaly Detection</strong>: Isolation Forest flags novel behavior (e.g., DGAs, beaconing).</li><li><strong>Alert Tuning</strong>: Transforms raw model output into human-actionable severity alerts.</li><li><strong>Prioritization</strong>: ML ranks critical threats to help Blue Teams focus their triage efforts.</li><li><strong>Continuous Learning</strong>: Retraining models helps adapt to evolving attacker techniques.</li><li><strong>Threat Hunting</strong>: Enables proactive exploration of low-score anomalies often overlooked.</li><li><strong>Integration Ready</strong>: Output format fits into SIEM dashboards or incident response pipelines</li></ul><h4>Operational Deployment in a SOC Environment:</h4><p>To integrate this AI/ML-based DNS detection pipeline in a real organization:</p><h4><strong>Log Ingestion</strong></h4><ul><li>Use syslog, Winlogbeat, or Zeek to collect DNS logs.</li><li>Ingest into SIEM like Splunk, Sentinel, or ELK.</li></ul><h4><strong>Preprocessing &amp; Feature Extraction</strong></h4><ul><li>Normalize fields (query_name, TTL, entropy, etc.).</li><li>Use a microservice or script (e.g., feature_engine.py) to extract features in real-time.</li></ul><h4>Detection Pipeline</h4><ul><li>Load pre-trained Isolation Forest model.</li><li>Score incoming queries live.</li><li>Append severity and generate alert JSON or CSV.</li></ul><h4><strong>Alert Routing</strong></h4><ul><li>Critical alerts routed via email/webhook.</li><li>Integrated with SOAR to trigger automated blocking (e.g., via DNS firewall).</li></ul><h4><strong>Integration with Blue Team Ecosystem</strong></h4><p>The pipeline output can be integrated into the following security layers:</p><ul><li><strong>SIEM platforms</strong> (e.g., Splunk, Sentinel)</li><li><strong>SOAR solutions</strong> for automated response</li><li><strong>Email/webhook alerts</strong> to notify analysts</li><li><strong>Dashboards</strong> using Kibana/Grafana for real-time visualization</li></ul><p>This allows defenders to build proactive defenses against DNS-based threats.</p><h4><strong>Diagram: SOC Pipeline Flow:</strong></h4><p><em>[ DNS Logs ]</em></p><p><em>↓</em></p><p><em>[ Preprocessing (entropy, hour) ]</em></p><p><em>↓</em></p><p><em>[ ML Model (Isolation Forest) ]</em></p><p><em>↓</em></p><p><em>[ Score + Classify ]</em></p><p><em>↓</em></p><p><em>[ Add Severity + Priority ]</em></p><p><em>↓</em></p><p><em>[ Push to SIEM / Alert Console ]</em></p><h3>Outcome:</h3><p>This project successfully demonstrates how ai+ml can empower Blue Teams to detect and respond to suspicious DNS activity with greater accuracy, automation, and insight. By integrating unsupervised learning techniques like Isolation Forest with engineered features such as entropy and query timing, the system can:</p><ul><li><strong>Detect stealthy DNS-based threats</strong> such as DGAs, tunneling, and beaconing C2 traffic.</li><li><strong>Assign contextual anomaly scores</strong>, transforming raw telemetry into actionable intelligence.</li><li><strong>Automatically generate severity and priority levels</strong> for each alert, reducing noise and improving triage.</li><li><strong>Operate on synthetic or real-world datasets</strong>, making the system flexible and adaptable across environments.</li><li><strong>Integrate with existing security stacks</strong> such as SIEMs and SOAR tools, enabling real-time operational deployment.</li></ul><p>#cybersecurity #AI #ML #blueteam #soc #AI&amp;ML</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5566f3aa9a52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI-Powered SSH Brute Force Detection & Alert Tuning]]></title>
            <link>https://medium.com/@myth7672/ai-powered-ssh-brute-force-detection-alert-tuning-9f50362f36da?source=rss-0f351da37421------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f50362f36da</guid>
            <dc:creator><![CDATA[Myth]]></dc:creator>
            <pubDate>Fri, 24 Oct 2025 09:40:22 GMT</pubDate>
            <atom:updated>2025-10-24T09:40:22.032Z</atom:updated>
            <content:encoded><![CDATA[<p>Automatically detect SSH brute force attacks and tune alerts using AI &amp; machine learning.</p><h4><strong>Objective</strong></h4><p>To build a Blue Team detection system that can identify brute-force SSH login attempts using machine learning. It intelligently analyzes /var/log/auth.log, flags suspicious behavior, and auto-tunes alerting using AI, helping reduce false positives and eliminate static thresholds.</p><h4>Tools and Libraries Used:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*0NhOzMLfUyHWnH5eVzaeDQ.png" /></figure><h4>How AI &amp; ML Are Used:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*e2gRfzOKudVxHjJVLl3fjA.png" /></figure><h4>What is “Alert Tuning”?</h4><p><strong>Alert tuning means:</strong></p><ul><li>Reducing false positives.</li><li>Prioritizing truly malicious activity.</li><li>Automatically adapting thresholds based on past behavior.</li></ul><p>AI allows the IDS to act more like a smart analyst:</p><p>“Don’t cry wolf unless it’s really a wolf… or at least a wolfish packet.”</p><h4>Folder Structure:</h4><p>E:\AI &amp; ML\SSH-Detection-Project\</p><p>├── dataset\</p><p>│ └── ssh_bruteforce_dataset.log ← Sample log file</p><p>├── models\</p><p>│ └── isolation_forest_model.pkl ← Trained ML model</p><p>├── output\</p><p>│ ├── malicious_ips.csv.xlsx ← Final results</p><p>│ └── analysis_plot.png ← Brute-force graph</p><p>├── src\</p><p>│ ├── parse_logs.py ← Log parser</p><p>│ ├── train_model.py ← ML model training</p><p>│ ├── detect_attack.py ← Detection script</p><p>│ ├── alert_tuning.py ← Alert tuning logic</p><p>│ └── utils.py ← Shared functions</p><p>└── main.py ← Main driver script</p><h3>Step-by-Step Execution:</h3><h4><strong>Step 1 — Install Libraries</strong></h4><p>pip install pandas numpy scikit-learn matplotlib</p><h4>Step 2 — Parse Logs</h4><p><strong>File Created:</strong> src/parse_logs.py</p><p><strong>Purpose:</strong> This file parses raw SSH logs into structured data using regex. It captures login attempt status, IP address, and user details.</p><p><strong>How AI/ML Helps:</strong> Without consistent and cleanly parsed data, AI models would misclassify or fail to train properly. Think of this step as data mining before intelligence kicks in.</p><p><strong>File: src/parse_logs.py</strong></p><pre>import re<br>import pandas as pd<br>def parse_log(log_file):<br>pattern = re.compile(<br>r&#39;(?P&lt;date&gt;\w{3} \d{1,2} \d{2}:\d{2}:\d{2}) .* sshd\[\d+\]: (?P&lt;status&gt;Failed|Accepted) password for (?P&lt;user&gt;\w+) from (?P&lt;ip&gt;[\d\.]+)&#39;<br>)<br>data = []<br>with open(log_file, &#39;r&#39;) as file:<br>for line in file:<br>match = pattern.search(line)<br>if match:<br>data.append(match.groupdict())<br>df = pd.DataFrame(data)<br>df[&#39;is_failed&#39;] = df[&#39;status&#39;].apply(lambda x: 1 if x == &#39;Failed&#39; else 0)<br>return df</pre><h4>Step 3 — Feature Engineering</h4><p><strong>File Created:</strong> src/utils.py</p><p><strong>Purpose:</strong> Aggregates login attempts by IP, calculating total attempts, failed attempts, and failure ratio.</p><p><strong>How AI/ML Helps:</strong> These features are the lifeblood of your model. ‘fail_ratio’ and ‘failed_attempts’ give the Isolation Forest something meaningful to chew on.</p><p><strong>File: src/</strong><a href="http://utils.py/"><strong>utils.py</strong></a></p><pre>import matplotlib.pyplot as plt<br>import pandas as pd<br>def extract_ip_stats(df):<br>ip_stats = df.groupby(&#39;ip&#39;)[&#39;is_failed&#39;].agg(<br>[&#39;count&#39;, &#39;sum&#39;]).reset_index()<br>ip_stats.columns = [&#39;ip&#39;, &#39;total_attempts&#39;, &#39;failed_attempts&#39;]<br>ip_stats[&#39;fail_ratio&#39;] = ip_stats[&#39;failed_attempts&#39;] / \<br>ip_stats[&#39;total_attempts&#39;]<br>return ip_stats<br>def plot_stats(ip_stats):<br>plt.figure(figsize=(8, 6))<br>plt.scatter(ip_stats[&#39;failed_attempts&#39;], ip_stats[&#39;fail_ratio&#39;],<br>c=ip_stats[&#39;malicious&#39;], cmap=&#39;coolwarm&#39;, edgecolors=&#39;k&#39;)<br>plt.xlabel(&quot;Failed Attempts&quot;)<br>plt.ylabel(&quot;Fail Ratio&quot;)<br>plt.title(&quot;SSH Brute Force Detection&quot;)<br>plt.grid(True)<br>plt.tight_layout()<br>plt.savefig(&quot;output/analysis_plot.png&quot;)<br>print(&quot;✅ Plot saved to output/analysis_plot.png&quot;)</pre><h4>Step 4 — Train ML Model</h4><p><strong>File Created:</strong> src/train_model.py</p><p><strong>Purpose:</strong> Trains an Isolation Forest model using the engineered features and saves it for later detection.</p><p><strong>How AI/ML Helps:</strong> Instead of writing custom rules, let the model learn from the data. This brings adaptability and robustness.</p><p><strong>File: src/train_model.py</strong></p><pre>from sklearn.ensemble import IsolationForest<br>import joblib<br>from .utils import extract_ip_stats<br>def train_model(df, model_path=&#39;models/isolation_forest_model.pkl&#39;):<br>ip_stats = extract_ip_stats(df)<br># 👇 Increase contamination to force anomaly detection<br>model = IsolationForest(contamination=0.3, random_state=42)<br>model.fit(ip_stats[[&#39;failed_attempts&#39;, &#39;fail_ratio&#39;]])<br>joblib.dump(model, model_path)<br>print(&quot;✅ Isolation Forest model saved to &#39;{}&#39;&quot;.format(model_path))</pre><h4>Step 5 — Detect Attack</h4><p><strong>File Created:</strong> src/detect_attack.py</p><p><strong>Purpose:</strong> Uses the trained Isolation Forest model to classify each IP as malicious or benign.</p><p><strong>How AI/ML Helps:</strong> This is where AI spots the oddballs — the IPs behaving way outside the norm.</p><p><strong>File: src/detect_attack.py</strong></p><pre>import joblib<br>import pandas as pd<br>import os<br>from src.utils import extract_ip_stats<br>def detect_attack(df, model_path=&#39;models/isolation_forest_model.pkl&#39;):<br>model = joblib.load(model_path)<br>ip_stats = extract_ip_stats(df)<br># Predict anomalies (-1 = malicious)<br>ip_stats[&#39;malicious&#39;] = model.predict(ip_stats[[&#39;failed_attempts&#39;, &#39;fail_ratio&#39;]])<br>ip_stats[&#39;malicious&#39;] = ip_stats[&#39;malicious&#39;].apply(lambda x: 1 if x == -1 else 0)<br># Safety check: No failed attempts? Not malicious<br>ip_stats.loc[ip_stats[&#39;fail_ratio&#39;] == 0, &#39;malicious&#39;] = 0<br># Save all stats<br>os.makedirs(&#39;output&#39;, exist_ok=True)<br>ip_stats.to_csv(&quot;output/all_ip_stats_with_labels.csv&quot;, index=False)<br>ip_stats[ip_stats[&#39;malicious&#39;] == 1].to_csv(&quot;output/malicious_ips.csv&quot;, index=False)<br>print(&quot;✅ Full IP stats saved to output/all_ip_stats_with_labels.csv&quot;)<br>print(&quot;✅ Malicious IPs saved to output/malicious_ips.csv&quot;)<br>return ip_stats # 🔥 Return IP stats so main.py can use it</pre><h4>Step 6 — Alert Tuning</h4><p><strong>File Created:</strong> src/alert_tuning.py</p><p><strong>Purpose:</strong> Enhances the model’s intelligence by calculating adaptive thresholds from real-time IP behavior. Labels only truly deviant IPs as alert-worthy.</p><p><strong>How AI/ML Helps:</strong> Dynamically tunes alert levels based on distribution rather than static guesswork, allowing security teams to focus on real threats.</p><pre>import pandas as pd<br>import os<br>def tune_alerts(ip_stats, fail_ratio_thresh=0.8, attempt_thresh=100):<br>&quot;&quot;&quot;<br>Tune alerts based on fail ratio and total failed attempts.<br>This refines predictions and reduces false positives.<br>&quot;&quot;&quot;<br># Create a new column &#39;alert&#39; based on thresholds<br>ip_stats[&#39;alert&#39;] = ip_stats.apply(<br>lambda row: 1 if row[&#39;fail_ratio&#39;] &gt; fail_ratio_thresh and row[&#39;failed_attempts&#39;] &gt; attempt_thresh else 0,<br>axis=1<br>)<br># Save tuned alerts<br>os.makedirs(&#39;output&#39;, exist_ok=True)<br>ip_stats[ip_stats[&#39;alert&#39;] == 1].to_csv(&quot;output/tuned_malicious_ips.csv&quot;, index=False)<br>print(&quot;🚨 Tuned alerts saved to output/tuned_malicious_ips.csv&quot;)<br>return ip_stats</pre><h4>Step 7 — Visualize Output</h4><p><strong>File Modified:</strong> src/utils.py</p><p><strong>Purpose:</strong> Plots a scatter graph showing failed attempts and failure ratio, color-coded by malicious status.</p><p><strong>How AI/ML Helps:</strong> Visual confirmation helps validate the AI’s judgment. Also useful for analysts.</p><p><strong>File: src/utils.py (continued)</strong></p><pre>import matplotlib.pyplot as plt<br>def plot_stats(ip_stats):<br>plt.figure(figsize=(8, 6))<br>plt.scatter(ip_stats[&#39;failed_attempts&#39;], ip_stats[&#39;fail_ratio&#39;],<br>c=ip_stats[&#39;malicious&#39;], cmap=&#39;coolwarm&#39;, edgecolors=&#39;k&#39;)<br>plt.xlabel(&quot;Failed Attempts&quot;)<br>plt.ylabel(&quot;Failure Ratio&quot;)<br>plt.title(&quot;SSH Brute Force Detection&quot;)<br>plt.grid(True)<br>plt.tight_layout()<br>plt.savefig(&quot;output/analysis_plot.png&quot;)</pre><h4>Step 8 — Execute Main Pipeline</h4><p><strong>File Created:</strong> main.py</p><p><strong>Purpose:</strong> Orchestrates the entire process — parsing logs, training model, detecting anomalies, tuning alerts, and visualizing results.</p><p><strong>How AI/ML Helps:</strong> Seamlessly combines each AI/ML-powered step into an automated defense mechanism.</p><p><strong>File: main.py</strong></p><pre>from src.utils import extract_ip_stats, plot_stats<br>from src.detect_attack import detect_attack<br>from src.train_model import train_model<br>from src.parse_logs import parse_log<br>from src.alert_tuner import tune_alerts # Make sure alert_tuning.py exists<br>import sys<br>import os<br>import pandas as pd<br># Add &#39;src&#39; to Python path<br>sys.path.insert(0, os.path.join(os.path.dirname(__file__), &#39;src&#39;))<br># Step 1: Load log data<br>log_file = &#39;dataset/ssh_bruteforce_dataset.log&#39;<br>df = parse_log(log_file)<br># Step 2: Train the model<br>train_model(df)<br># Step 3: Detect malicious IPs using Isolation Forest<br>ip_stats = detect_attack(df)<br># Step 4: Apply rule-based tuning<br>ip_stats = tune_alerts(ip_stats, fail_ratio_thresh=0.95, attempt_thresh=100)<br># ✅ Sync malicious column with final alert logic<br>ip_stats[&quot;malicious&quot;] = ip_stats[&quot;alert&quot;]<br># Step 5: Save final tuned CSVs<br>ip_stats.to_csv(&quot;output/all_ip_stats_with_labels.csv&quot;, index=False)<br>ip_stats[ip_stats[&quot;malicious&quot;] == 1].to_csv(&quot;output/tuned_malicious_ips.csv&quot;, index=False)<br># Step 6: Plotting<br>plot_stats(ip_stats)</pre><p><a href="http://main.py/"><strong>Main.py</strong></a><strong> Code execution:</strong></p><h3>Output Graph:</h3><p>Saved at:<br>output/analysis_plot.png — This is a scatter plot showing failed SSH login attempts vs. failure ratio, with color-coded indicators for malicious vs benign IPs. It visually highlights anomalies using the Isolation Forest model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*wEdd2tyS1-YjE2EripA6xw.png" /></figure><h4>CSV: malicious_ips.csv</h4><p>Saved at:<br> output/malicious_ips.csv — Contains the final list of detected IPs flagged as malicious. It includes:</p><ul><li>IP address</li><li>Total attempts</li><li>Failed attempts</li><li>Fail ratio</li><li>Malicious label</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*PNLSVyX0NByX-kG-oTSJWw.png" /></figure><h4>CSV: all_ip_stats_with_labels.csv</h4><p>Saved at:<br> output/all_ip_stats_with_labels.csv — Stores results of <em>all</em> IPs evaluated by the model, not just the malicious ones. Useful for audit and review. Contains:</p><ul><li>IP address</li><li>Total attempts</li><li>Failed attempts</li><li>Fail ratio</li><li>Malicious label</li><li>AI-driven alert status</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*K3s2hYtQdzTg4D629Bw8rQ.png" /></figure><h4>CSV: alert_tuning.csv</h4><p>Saved at:<br> output/alert_tuning.csv — Logs AI-tuned alerting behavior. Helps understand how dynamic thresholds are adjusted over time and which IPs were affected. Fields:</p><ul><li>IP</li><li>Fail ratio</li><li>Threshold used</li><li>Alert generated (Yes/No)</li><li>Reason for decision output/analysis_plot.png</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*v2dSrCQWdkYMY5YpCW5dcw.png" /></figure><p>#AI&amp;ML #cybersecurity # blueteam #projects</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f50362f36da" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>