Friday, August 21, 2026

From Hidden Connections to Network Intelligence: Upgrading a Python DNS Monitor into an EDR-Ready Network Detection Tool

In an earlier project, I built a small Python utility for investigating the hidden network activity of a Windows PC. In case you have not read the original article, here is the link:  Tracking Your PC’s Hidden Connections with ipconfig /displaydns

The basic idea was simple: Windows maintains a DNS resolver cache, and by running:

ipconfig /displaydns

we can see domains that the computer has recently resolved.

That simple technique is surprisingly useful.

A computer may be communicating with dozens or even hundreds of domains without the user explicitly opening those websites. Browsers, applications, Windows services, update mechanisms, cloud applications, background processes, and potentially malicious software can all generate DNS activity.

However, there is an important limitation.

DNS cache information is not the same thing as live network connection monitoring.

The original program was therefore useful as a lightweight investigation tool, but it can be taken much further.

In this upgraded version, the goal is to build a broader Network Intelligence and Command-and-Control (C2) Detection capability using Python.

Instead of simply asking:

"What domains has this PC recently resolved?"

the program can begin answering:

"Which process is communicating with which destination, what domain is associated with it, is that destination suspicious, and does the activity correlate with other security events?"


1. The Original Approach

The original Python program was based around the Windows DNS cache.

Python can execute:

import subprocess

result = subprocess.run(
    ["ipconfig", "/displaydns"],
    capture_output=True,
    text=True
)

print(result.stdout)

This retrieves information from the Windows DNS resolver cache.

A typical record contains information such as:

Record Name . . . . . : example.com
Record Type . . . . . : 1
Time To Live  . . . . : 120
Data Length . . . . . : 4
A (Host) Record . . . : 93.184.xxx.xxx

From this information, a Python application can extract:

  • Domain name

  • Record type

  • TTL

  • IP address

The program can then display the information in a table or export it for further analysis.

For troubleshooting and basic security investigation, this is already useful.

But there is much more information available on a Windows endpoint.


2. DNS Cache Is Not Live Network Monitoring

Before expanding the program, it is important to understand the limitation of ipconfig /displaydns.

The command shows information currently retained in the Windows DNS cache.

It does not necessarily tell us:

  • Which process made the DNS request

  • Whether the connection is still active

  • Which local port is being used

  • Which remote port is being used

  • Whether the communication uses TCP or UDP

  • Whether the process is legitimate

  • Whether the application connected directly to an IP address

  • How long the connection lasted

  • Whether the connection was encrypted

Therefore, the upgraded program should not simply be called a "hidden connection monitor."

A better description is:

Network Intelligence

The objective is to combine several sources of endpoint information.

DNS
 │
 ├── Domain
 ├── Resolved IP
 └── DNS activity
       │
       ▼
Network Connections
 │
 ├── Local IP
 ├── Local Port
 ├── Remote IP
 ├── Remote Port
 └── Protocol
       │
       ▼
Process
 │
 ├── PID
 ├── Process Name
 ├── Parent Process
 ├── Command Line
 └── File Hash
       │
       ▼
Threat Intelligence
 │
 ├── IOC
 ├── Reputation
 └── Detection Rules
       │
       ▼
Correlation
       │
       ▼
Risk Score / Alert

This produces much richer security information.


3. From a Python Utility to a Security Sensor

The original application was essentially a utility that collected information when the user requested it.

The upgraded architecture can operate more like a security sensor.

                 Windows PC
                     │
          ┌──────────┼──────────┐
          │          │          │
        DNS       Processes   Network
          │          │          │
          └──────────┼──────────┘
                     │
              Python Collector
                     │
              Normalize Events
                     │
               Local Buffer
                     │
                     ▼
              Security Server
                     │
          ┌──────────┼───────────┐
          │          │           │
       Detection   Correlation  IOC
          │          │           │
          └──────────┼───────────┘
                     │
                  Database
                     │
                     ▼
              Security Dashboard

The important architectural principle is that the endpoint collects telemetry while the central system can perform more expensive analysis and correlation.


4. Collecting DNS Information

DNS information remains one of the most useful sources.

The program can convert raw Windows information into structured events.

Instead of storing:

ipconfig /displaydns

output as a large block of text, the application can generate something like:

{
    "event_type": "dns_observation",
    "domain": "example.com",
    "resolved_ip": "93.184.xxx.xxx",
    "timestamp": "2026-08-21T15:32:10"
}

Structured telemetry makes the information easier to:

  • Search

  • Filter

  • Correlate

  • Store

  • Enrich

  • Detect against

The DNS cache therefore becomes one source of network intelligence rather than the entire monitoring system.


5. Adding Live Network Connections

The next major improvement is to collect actual network connection information.

Windows can provide information such as:

Local Address
Local Port
Remote Address
Remote Port
Protocol
Connection State
PID

Conceptually:

TCP

192.168.1.25:52144
        │
        ▼
185.xxx.xxx.xxx:443
        │
        ▼
PID 4216

The PID is particularly important.

It allows the network connection to be associated with the process responsible for it.

For example:

PID: 4216
Process: powershell.exe
Remote IP: 185.xxx.xxx.xxx
Remote Port: 443

Now the program knows considerably more than simply:

"The computer connected to 185.xxx.xxx.xxx."

It knows:

"powershell.exe created a connection to 185.xxx.xxx.xxx:443."

That is much more useful from a security perspective.


6. Process-to-Network Correlation

This is where the project becomes significantly more powerful.

Imagine that the endpoint reports:

Process Created

powershell.exe
PID: 4216
Parent: winword.exe

A few seconds later:

Network Connection

PID: 4216
Remote: 185.xxx.xxx.xxx:443

And DNS telemetry reports:

Domain:

suspicious-example.com

Resolved IP:

185.xxx.xxx.xxx

Instead of treating these as three unrelated events, the detection system can correlate them.

The result could be displayed as:

HIGH RISK ACTIVITY

WINWORD.EXE
      │
      └──► powershell.exe
               │
               └──► suspicious-example.com
                         │
                         └──► 185.xxx.xxx.xxx:443

This type of relationship is far more useful than a simple list of DNS records.


7. Why Process Attribution Matters

An IP address alone does not tell the entire story.

For example:

chrome.exe → 142.250.xxx.xxx:443

could be completely normal.

But:

rundll32.exe → 185.xxx.xxx.xxx:8080

could deserve investigation.

And:

powershell.exe
      │
      └──► 185.xxx.xxx.xxx:443

could become highly suspicious when combined with other indicators.

The security question therefore changes from:

"Where is the computer communicating?"

to:

"Which process is communicating, where is it communicating, and what else was happening on the endpoint at the same time?"

That is the foundation of process-aware network detection.


8. Adding IOC Matching

The next layer is Indicator of Compromise matching.

The central detection system can maintain intelligence containing:

Malicious IP addresses
Malicious domains
Malicious URLs
File hashes
Known C2 infrastructure
Threat actor infrastructure

When an endpoint reports:

185.xxx.xxx.xxx

the system can check whether the destination is known.

Conceptually:

Network Event
     │
     ▼
IOC Database
     │
     ├── No Match → Continue Monitoring
     │
     └── Match → Raise Risk

A matching event can then be correlated with:

  • Process information

  • User information

  • Endpoint identity

  • DNS activity

  • Authentication events

  • File activity

  • Other network events

This is much more powerful than maintaining a manually checked list of suspicious addresses.


9. Reputation Enrichment

Network destinations can also be enriched using external threat-intelligence and reputation services.

For example:

185.xxx.xxx.xxx
       │
       ├── Local IOC database
       ├── Threat intelligence
       └── Reputation service
              │
              ▼
          Risk Result

The resulting information could look like:

Destination:
185.xxx.xxx.xxx

Reputation:
Malicious

Confidence:
92%

Category:
Command and Control

Affected Endpoints:
7

The important point is that reputation should be treated as one signal, not as an automatic declaration that every connection is malicious.

A security product should combine reputation with behavioral evidence.


10. Detecting Potential C2 Activity

The ultimate objective is not simply to display network connections.

It is to identify potentially malicious communication.

Consider this sequence:

Microsoft Word
      │
      ▼
PowerShell starts
      │
      ▼
PowerShell contacts new domain
      │
      ▼
Domain resolves to suspicious IP
      │
      ▼
Connection established
      │
      ▼
Destination has poor reputation

Individually, some of these events might not be enough to trigger a high-severity alert.

Together, however, they form a much stronger behavioral signal.

A detection engine could produce:

Risk Score: 94/100
Severity: CRITICAL

Potential Command-and-Control Activity

Parent Process:
WINWORD.EXE

Child Process:
powershell.exe

Destination:
suspicious-example.com

Remote IP:
185.xxx.xxx.xxx

Remote Port:
443

This is the kind of correlation that makes network telemetry useful for EDR and SOC analysis.


11. Network Intelligence Dashboard

A dedicated dashboard can present the information in a way that is useful to security analysts.

For example:

┌──────────────────────────────────────────────────────────────┐
│ NETWORK INTELLIGENCE                                        │
├──────────────────────────────────────────────────────────────┤
│ Endpoint  Process       PID    Destination       Risk        │
├──────────────────────────────────────────────────────────────┤
│ PC-001    chrome.exe    4521   142.250.x.x:443    LOW         │
│ PC-001    powershell    6214   185.x.x.x:443      HIGH        │
│ PC-002    svchost.exe   1120   13.x.x.x:443       LOW         │
│ PC-003    rundll32.exe  3384   91.x.x.x:8080      CRITICAL    │
└──────────────────────────────────────────────────────────────┘

Selecting a connection could reveal:

Endpoint
Process
PID
Parent Process
Command Line
File Hash
Digital Signature
Local Address
Remote Address
Remote Port
Protocol
DNS Domain
IOC Status
Reputation
MITRE ATT&CK Mapping
Risk Score
Related Events

The analyst can then move from:

Connection → Process → Process Tree → DNS → IOC → Alert → Incident

without manually investigating each data source.


12. DNS Cache Still Has a Place

The original ipconfig /displaydns technique should not be discarded.

It remains useful as one source of information.

The expanded architecture can use:

Network Intelligence
│
├── DNS Cache
├── DNS Events
├── Network Connections
├── Listening Ports
├── Process Attribution
├── IOC Matching
├── Reputation
└── C2 Correlation

The original Python script therefore becomes the foundation of a much broader monitoring system.

The important change is that DNS cache data is now treated as one telemetry source among several.


13. Listening Ports

Another useful addition is monitoring listening ports.

For example:

PID  Process       Local Address      Port
------------------------------------------------
812  svchost.exe   0.0.0.0            135
1040 service.exe   0.0.0.0            8080
4216 powershell    127.0.0.1          5000

A newly opened listening port can become interesting when combined with:

  • a new process

  • an unsigned executable

  • unusual parent process

  • suspicious service installation

  • persistence activity

  • external network exposure

This allows the program to detect changes in the endpoint's network exposure.


14. Network Events Should Be Structured

A network event can be represented as JSON:

{
    "event_type": "network_connection",
    "agent_id": "HOST-00123",
    "timestamp": "2026-08-21T15:32:10",
    "process": "powershell.exe",
    "pid": 4216,
    "parent_process": "winword.exe",
    "local_ip": "192.168.1.25",
    "local_port": 52144,
    "remote_ip": "185.xxx.xxx.xxx",
    "remote_port": 443,
    "protocol": "TCP"
}

A DNS observation can be represented separately:

{
    "event_type": "dns_observation",
    "agent_id": "HOST-00123",
    "timestamp": "2026-08-21T15:32:08",
    "domain": "suspicious-example.com",
    "resolved_ip": "185.xxx.xxx.xxx"
}

The detection engine can then correlate these records based on:

  • Endpoint

  • PID

  • Timestamp

  • IP address

  • Domain

  • Process

  • User

This is considerably easier than attempting to analyze raw command output.


15. PostgreSQL for Centralized Telemetry

For a small standalone Python application, SQLite is perfectly adequate.

As the number of monitored endpoints grows, however, centralized PostgreSQL storage becomes much more attractive.

The architecture can look like:

Endpoints
    │
    ▼
Python Endpoint Collectors
    │
    ▼
HTTPS
    │
    ▼
Central Security Server
    │
    ├── Process Events
    ├── DNS Events
    ├── Network Connections
    ├── Authentication Events
    ├── File Events
    ├── IOC Matches
    └── Alerts
            │
            ▼
        PostgreSQL

This provides a foundation for historical searches across many endpoints.


16. Threat Hunting

Once network telemetry is centrally stored, analysts can perform searches that are difficult to accomplish with a simple local script.

For example:

Which computers contacted this IP?

185.xxx.xxx.xxx

Which processes contacted this domain?

suspicious-example.com

Which PowerShell processes made external connections?

powershell.exe
       ↓
External destination

Which endpoints contacted an IOC?

IOC
 ↓
Historical search
 ↓
Affected endpoints

Which domains appeared for the first time today?

First Seen = Today

This turns the project from a simple monitoring utility into a threat-hunting data source.


17. Offline Collection

Network telemetry should also survive temporary server or network failures.

A robust endpoint collector should therefore use local buffering:

Windows
   │
   ▼
Python Collector
   │
   ▼
Local Queue
   │
   ├── Server Available
   │        │
   │        ▼
   │      Upload
   │
   └── Server Unavailable
            │
            ▼
       Store Locally
            │
            ▼
        Retry Later

This is especially important for security telemetry.

Losing an hour of events because a server was temporarily unavailable could mean losing the evidence needed to reconstruct an incident.


18. What the Upgraded Program Can Now Answer

The original program essentially answered:

"What domains are currently in the Windows DNS cache?"

The upgraded architecture can answer much more.

Which process generated the network activity?

powershell.exe

Where did it connect?

185.xxx.xxx.xxx:443

What domain resolved to that address?

suspicious-example.com

Is the destination known?

IOC Match: YES

Is the destination suspicious?

Reputation: Malicious

What launched the process?

WINWORD.EXE
      ↓
powershell.exe

Did other endpoints contact the same destination?

7 endpoints

What is the overall risk?

CRITICAL

This is a major evolution from a DNS-cache viewer.


19. From Script to Network Security Platform

The progression can be summarized as:

Original Program

ipconfig /displaydns
        │
        ▼
DNS Cache
        │
        ▼
Display Results

becomes:

Upgraded Architecture

DNS
 │
 ├───────────────┐
 │               │
 ▼               ▼
Domains       Resolved IPs
 │               │
 └───────┬───────┘
         │
         ▼
Network Connections
         │
         ▼
Process Attribution
         │
         ▼
IOC / Reputation
         │
         ▼
Behavioral Correlation
         │
         ▼
Risk Scoring
         │
         ▼
Threat Detection
         │
         ▼
SOC / Threat Hunting

The difference is substantial.

The program is no longer simply looking for "hidden connections."

It is building a relationship between:

Process + DNS + Network + Threat Intelligence + Behavior.


20. Future Enhancements

There are several directions in which this project can continue to evolve.

DNS

  • DNS query monitoring

  • DNS tunneling detection

  • High-entropy domain detection

  • Newly registered domain detection

  • Suspicious TLD detection

  • Repeated failed DNS queries

Network

  • TCP/UDP connection tracking

  • Listening-port monitoring

  • Process-to-network mapping

  • Connection duration

  • Destination reputation

  • External versus internal communication

Process

  • Parent/child process relationships

  • Command-line analysis

  • Digital signatures

  • File hashes

  • Process reputation

  • Suspicious process behavior

Detection

  • IOC matching

  • Sigma-style rules

  • Behavioral rules

  • C2 detection

  • Beaconing detection

  • Lateral movement detection

Threat Hunting

  • Historical search

  • First-seen/last-seen tracking

  • Endpoint-wide searches

  • IOC retro-hunting

  • Process-to-network investigation


Conclusion

The original Python DNS-cache project demonstrated a simple but useful idea: a Windows computer is constantly communicating with services and systems that may not be obvious to the person using it.

ipconfig /displaydns provides a surprisingly useful window into that activity.

But DNS cache information is only the beginning.

By combining:

DNS + network connections + process attribution + listening ports + IOC matching + reputation + behavioral correlation + centralized storage

a relatively simple Python utility can evolve into a much more capable Network Intelligence and C2 Detection system.

The most important conceptual change is this:

Don't just show me where the computer is connecting. Show me what is connecting, where it is connecting, what domain is associated with it, whether the destination is suspicious, and how that activity relates to everything else happening on the endpoint.

That is the difference between a basic network utility and a security monitoring platform.

The original program started with one command:

ipconfig /displaydns

The upgraded concept turns that single source of information into a complete investigation chain:

DNS
 ↓
Network
 ↓
Process
 ↓
Threat Intelligence
 ↓
Correlation
 ↓
Risk
 ↓
Detection
 ↓
Investigation

And that is where Python becomes particularly interesting for cybersecurity: a small script can start as a diagnostic utility and, with the right architecture, evolve into a serious security telemetry and threat-hunting component.

Wednesday, July 8, 2026

Windows Threat Analyzer – A Python-Based Host Detection Platform for Windows Event Logs

 

Windows systems generate thousands of security events every day. Most of those events go unnoticed unless an analyst manually reviews Event Viewer or a SIEM platform collects and correlates them.

That challenge inspired the development of Windows Threat Analyzer (WTA)—an open-source Python application that transforms raw Windows Event Logs into actionable security alerts, risk scores, and MITRE ATT&CK-mapped detections.

Rather than replacing enterprise SIEM platforms, Windows Threat Analyzer focuses on demonstrating how host-based detection engineering can be implemented using native Windows telemetry and Sysmon. The detections are constantly getting enriched and new detection rules are being added each day.


Why Build Windows Threat Analyzer?

Windows already records a wealth of security information, but manually reviewing those logs is difficult and time-consuming.

Windows Threat Analyzer aims to:

  • Continuously monitor Windows Event Logs

  • Detect suspicious activity using rule-based analytics

  • Correlate related events

  • Assign risk scores

  • Map detections to MITRE ATT&CK techniques

  • Present results through an easy-to-understand graphical interface

The project demonstrates practical cybersecurity concepts while remaining lightweight and fully written in Python.


Current Detection Coverage

The latest version currently supports more than twenty detection rules covering common attack techniques observed during Windows intrusions.

Authentication Monitoring

The analyzer detects authentication-related events such as:

  • Multiple failed logon attempts

  • Possible brute-force attacks

  • Administrator logons

  • Assignment of special privileges

These detections help identify suspicious authentication activity and privileged account usage.


Account Management Detection

Windows Threat Analyzer monitors changes to user accounts, including:

  • New local user creation

  • User deletion

  • Addition of users to the Administrators group

These activities are frequently associated with persistence or privilege escalation.


Persistence Techniques

Attackers often attempt to survive system reboots by creating persistence mechanisms.

Current detections include:

  • Windows service installation

  • Scheduled task creation

  • WMI Event Filters

  • WMI Event Consumers

  • WMI Filter Bindings

These events provide valuable indicators that unauthorized persistence may have been established.


PowerShell Monitoring

PowerShell remains one of the most abused administration tools in modern attacks.

The analyzer currently detects:

  • Encoded PowerShell execution

  • Suspicious PowerShell module logging

These detections help identify potentially malicious script execution.


Windows Defender Integration

Instead of ignoring Microsoft Defender, Windows Threat Analyzer incorporates Defender detections into its analysis.

Current support includes:

  • Defender malware detection events

This allows security analysts to view antivirus detections alongside other Windows security events.


Sysmon-Powered Detection

When Sysmon is installed, Windows Threat Analyzer gains access to much richer telemetry.

Current Sysmon detections include:

  • Process Injection

  • CreateRemoteThread activity

  • Suspicious process memory access

  • Credential dumping attempts

  • Process Hollowing

  • Alternate Data Stream creation

  • Unsigned driver loading

  • Suspicious DLL loading

  • Named Pipe activity associated with known offensive tooling

These detections significantly improve visibility into post-exploitation techniques that standard Windows logs often miss.


Credential Theft Detection

One notable capability is monitoring access to LSASS, the Windows process responsible for storing authentication credentials.

Unauthorized access to LSASS is commonly associated with credential dumping tools.

The analyzer watches for suspicious memory access patterns that may indicate attempts to extract credentials.


Event Correlation

Individual Windows events rarely tell the whole story.

Windows Threat Analyzer correlates related events occurring within a configurable time window.

For example:

  • Administrator privileges assigned

  • User added to Administrators group

Instead of generating isolated alerts, the application links related activity together, providing additional context for analysts.


MITRE ATT&CK Mapping

Each supported detection is mapped to relevant MITRE ATT&CK techniques where applicable.

Examples include:

  • Credential Dumping

  • Process Injection

  • Process Hollowing

  • WMI Event Subscription

  • Alternate Data Streams

This mapping helps analysts understand how detected behavior aligns with established attacker techniques.


Risk Scoring

Rather than displaying hundreds of disconnected alerts, Windows Threat Analyzer calculates a cumulative host risk score.

The score reflects the overall severity of observed activity and helps prioritize investigation.

Risk levels currently include:

  • Informational

  • Low

  • Medium

  • High

  • Critical


Reporting

Collected data can be exported for documentation or further analysis.

Supported export formats include:

  • CSV

  • JSON

  • PDF

These reports are useful for incident documentation and offline analysis.


User Interface

The desktop application provides a security operations–style dashboard featuring:

  • Live event monitoring

  • Alert management

  • Timeline visualization

  • Search and filtering

  • Risk overview

  • Event deduplication

  • Alert acknowledgment

The interface is designed to make Windows security events easier to interpret without requiring direct interaction with Event Viewer.


Current Detection Summary

At the time of writing, Windows Threat Analyzer includes:

  • 24 numbered detection rules

  • Dynamic Named Pipe detections

  • Windows Security Event monitoring

  • Sysmon behavioral detections

  • Event correlation

  • MITRE ATT&CK mapping

  • Risk scoring

  • Timeline visualization

  • PDF, CSV, and JSON reporting

The project continues to expand as additional detection rules and analysis capabilities are implemented.


Looking Ahead

Windows Threat Analyzer is an ongoing project focused on improving host-based threat detection using Windows-native telemetry.

Future development areas may include:

  • Additional Sysmon detections

  • Registry persistence monitoring

  • Ransomware behavior detection

  • Threat intelligence enrichment

  • Sigma rule compatibility

  • YARA integration

  • Machine learning–assisted anomaly detection

  • Expanded ATT&CK coverage

  • Multi-host monitoring


Final Thoughts

Building detection tools provides valuable insight into how Windows records security events and how attackers interact with operating systems.

Windows Threat Analyzer demonstrates that meaningful security analytics can be built using Python, SQLite, Windows Event Logs, and Sysmon without requiring enterprise infrastructure.

As development continues, the project aims to expand its detection coverage while remaining a practical platform for learning detection engineering, Windows internals, and defensive cybersecurity.

Thank you for following the project's progress. Feedback, suggestions, and contributions are always welcome as Windows Threat Analyzer continues to evolve.

Tuesday, June 30, 2026

Safeguarding Data: How File Integrity Monitoring Defeats Ransomware

 Imagine waking up to a frantic IT department and a glowing red screen demanding a Bitcoin ransom to unlock your company’s critical files. This is the reality of a ransomware attack.

While modern ransomware uses sophisticated encryption, it almost always leaves a massive, telltale footprint: unauthorized file modifications and sudden file extension changes. To catch these cyberattacks before they cripple an organization, security teams rely on a vital line of defense: File Integrity Monitoring (FIM). Here is how FIM works and why it is one of the most effective tools for spotting ransomware in its tracks.

The Ransomware Tell: File Extension Changes

When ransomware infiltrates a system, its primary goal is to encrypt as many valuable files as possible. To do this efficiently, the malware typically follows a specific operational routine:

  1. Accesses a file (e.g., financials.xlsx).

  2. Encrypts the contents using complex cryptographic keys.

  3. Renames the file by appending a unique extension (e.g., financials.xlsx.locked or financials.xlsx.crypted).

By changing the file extension, the ransomware signals to itself—and to the victim—which files have been successfully locked. While some advanced ransomware encrypts files without changing the extension, the vast majority still rely on this tactic to stay organized and exert psychological pressure on the victim.

If hundreds or thousands of files suddenly change their extensions within a few seconds, it is a definitive sign of a massive security breach.

Enter File Integrity Monitoring (FIM)

File Integrity Monitoring (FIM) is an internal security control that continuously scans, validates, and verifies the integrity of operating system and application files. It establishes a baseline of what a "healthy" file system looks like and raises an immediate alarm the moment a file is altered, created, or deleted without authorization.

How FIM Works: The Baseline and the Hash

FIM operates on a simple but incredibly powerful mathematical concept: cryptographic hashing.

[Original File] ----> (Hashing Algorithm) ----> [Unique Hash Value (Baseline)]
                                                       |
                                            (Continuous Comparison)
                                                       |
[Modified File] ----> (Hashing Algorithm) ----> [New Hash Value] ---> ALERT!
  • The Baseline: When FIM is first deployed, it takes a snapshot of the system. It passes every critical file through a hashing algorithm (like SHA-256) to generate a unique digital fingerprint (a hash).

  • The Verification: The FIM tool continuously or periodically recalculates these hashes.

  • The Detection: If a file's content is altered—even by a single character or byte—its calculated hash will completely change. FIM detects this mismatch instantly.

How FIM Catches Ransomware Red-Handed

While traditional antivirus software looks for known malware signatures, FIM looks at behavior and results. This makes it exceptionally good at catching zero-day (previously unknown) ransomware.

When ransomware begins changing file extensions and modifying data, FIM triggers an alert based on several anomalous behaviors:

1. Mass Rename and Extension Alerts

FIM doesn't just watch the insides of a file; it watches the metadata. If a rule is set to monitor a directory for file creation or renaming, FIM will instantly flag a sudden burst of new, unrecognized extensions (like .locky, .onion, or random string extensions).

2. High-Velocity Modification

Human beings and standard applications modify files at a relatively predictable pace. Ransomware operates at machine speed, modifying hundreds of files per second. FIM tools integrated with Security Information and Event Management (SIEM) systems will detect this high-velocity spike and sound the alarm.

3. Unauthorized Process Activity

FIM can track who or what changed a file. If a critical database file is suddenly modified not by the authorized database application, but by an unknown binary running out of a temporary folder, FIM flags it as highly suspicious.

Moving from Detection to Automated Response

In the context of a ransomware attack, seconds matter. Simply getting an email alert that 10,000 files have been encrypted is a post-mortem, not a defense.

Modern, advanced FIM solutions are paired with Automated Incident Response. When FIM detects a sudden wave of unauthorized file extension changes and hash mismatches, it can trigger automated playbooks to isolate the threat:

  • Isolating the Host: Automatically cutting the infected machine off from the local network and the internet to prevent the ransomware from spreading laterally to other servers.

  • Killing the Process: Force-terminating the unauthorized cryptographic process responsible for the rapid file changes.

  • Locking Accounts: Disabling the user account or credentials being used to write those changes, especially if the ransomware is attacking network shared drives.

Conclusion

File extension changes are the calling card of ransomware, representing the moment the trap springs shut. By implementing File Integrity Monitoring, organizations gain a continuous, watchful eye over their most sensitive data. FIM turns the ransomware's own noisy behavior against it, giving security teams the visibility they need to detect, isolate, and neutralize the threat before it turns into a catastrophic outage.

Thursday, June 25, 2026

How I Successfully Switched GitHub Accounts on My Local PC After Authentication and 403 Errors


Introduction

Recently, I needed to switch my local Git environment from one Git hosting account to another. My original setup was configured for an older developer account, but I wanted to push code to a repository owned by a different account.

At first, the process seemed straightforward—just update the Git username and email. However, I encountered multiple authentication issues, including:

  • Logon failed errors

  • Credential Manager conflicts

  • GitHub 403 permission errors

  • Personal Access Token (PAT) permission problems

This article documents the troubleshooting process and the final solution that worked.


Initial Configuration

My local Git configuration was still pointing to my old account:

git config --global user.name
# old_username

git config --global user.email
# old_email@example.com

The target repository was a newly created repository under a different account.


Step 1: Update Local Git Identity

I updated the Git username and email to match the new Git hosting account:

git config --global user.name "new_username"
git config --global user.email "new_email@example.com"

Verification:

git config --global user.name
git config --global user.email

This successfully updated the commit author information for future commits.

However, pushing to the remote repository still failed.


Step 2: Verify the Remote Repository

I checked the repository remote URL:

git remote -v

Output:

origin https://github.com/new_username/project_repository.git (fetch)
origin https://github.com/new_username/project_repository.git (push)

The remote was already configured correctly.


Step 3: Investigate Authentication Failures

Attempting to push resulted in:

Logon failed, use ctrl+c to cancel basic credential prompt.

This suggested that Git was using cached credentials from a previous configuration.

I checked Git's credential configuration:

git config --list --show-origin | findstr credential

Output:

file:"C:\ProgramData\Git\config" credential.helper=manager

The culprit was Git Credential Manager.


Step 4: Remove Git Credential Manager

Opening:

C:\ProgramData\Git\config

revealed:

[credential]
    helper = manager

I removed:

[credential]
    helper = manager

and saved the file.

Verification:

git config --list --show-origin | findstr credential

Output:

credential.https://dev.azure.com.usehttppath=true

The Credential Manager entry was gone.


Step 5: Push Again

After removing the Credential Manager configuration, Git finally prompted for credentials:

Username for 'https://github.com':

I entered:

new_username

Then:

Password for 'https://new_username@github.com':

I entered a GitHub Personal Access Token (PAT).

Unfortunately, I still received:

remote: Permission denied
fatal: The requested URL returned error: 403

Step 6: Discover the Real Problem

The issue was not the repository.

The issue was the token.

Inspecting the token revealed:

Repository access:
This token does not have access to any repositories.

Repository permissions:
This token does not have any repository permissions.

The token could authenticate the account but could not authorize repository actions such as pushing commits.


Step 7: Create a Proper Personal Access Token

I generated a new token with repository permissions.

For fine-grained tokens, the important settings were:

Repository access:
All repositories

and

Contents:
Read and Write

Without "Contents: Read and Write," GitHub rejects push operations with a 403 error.


Step 8: Push Successfully

After generating a properly configured PAT, I executed:

git push -u origin main

Git prompted for:

Username:
new_username

Password:
<Personal Access Token>

The result:

Counting objects: 22, done.
Compressing objects: 100% (18/18), done.
Writing objects: 100% (22/22), done.

[new branch] main -> main
Branch main set up to track remote branch main from origin.

Success.

The repository was successfully pushed under the new account.


Important Lesson: Git Identity vs GitHub Authentication

One of the biggest takeaways from this process is understanding the difference between:

Git Identity

git config --global user.name
git config --global user.email

These values determine:

  • Commit author

  • Commit email

  • How commits appear in Git history

GitHub Authentication

Username + Personal Access Token

These determine:

  • Which account is authenticated

  • Which repositories can be accessed

  • Whether pushes are authorized

Changing the Git identity does not automatically change GitHub authentication.


Final Thoughts

Switching GitHub accounts on a local machine can involve more than changing a username and email. Credential managers, cached authentication data, and token permissions can all introduce unexpected issues.

The solution ultimately required:

  1. Updating Git identity

  2. Verifying the remote repository

  3. Removing Git Credential Manager configuration

  4. Creating a PAT with correct repository permissions

  5. Authenticating using the new account

Once these steps were completed, pushing to the remote repository worked as expected.

Hopefully, this walkthrough helps other developers avoid the same troubleshooting process and better understand the distinction between Git configuration and repository authorization.

Sunday, August 31, 2025

Understanding Malware: Features, Analysis, and Mitigation

 Malware (short for malicious software) is any software intentionally designed to cause damage to systems, exfiltrate data, disrupt operations, or gain unauthorized access. For a cybersecurity engineer or professional, understanding how malware works is the foundation of effective malware analysis and defense. Without insight into typical malware behaviors, defensive strategies become guesswork. With proper understanding, however, detection, analysis, and mitigation become far more effective.


Typical Features of Malware

While malware comes in many forms (viruses, worms, trojans, ransomware, spyware, rootkits, etc.), most share common features:

  1. Persistence Mechanisms

    • Registry modifications, scheduled tasks, startup scripts, or bootkits to survive reboots.

  2. Obfuscation and Evasion

    • Code packing, encryption, polymorphism, or anti-VM/anti-debugging checks to avoid detection.

  3. Command-and-Control (C2) Communication

    • DNS queries, HTTP/HTTPS requests, or custom protocols to communicate with a remote attacker.

  4. Privilege Escalation

    • Exploiting vulnerabilities or misconfigurations to gain higher access rights.

  5. Lateral Movement

    • Propagating across networks using exploits, stolen credentials, or file shares.

  6. Data Exfiltration

    • Harvesting sensitive files, credentials, keystrokes, or screenshots.

  7. Payload Execution

    • Ransomware encrypting files, spyware stealing data, or destructive malware wiping systems.


Why Understanding Malware Behavior Matters

A cybersecurity professional’s ability to defend against malware depends on their ability to think like an attacker. Malware analysis—whether static (examining code and binaries) or dynamic (observing malware in a sandbox or lab)—provides critical insights into:

  • Indicators of Compromise (IoCs) such as file hashes, registry keys, domains, and IP addresses.

  • Tactics, Techniques, and Procedures (TTPs) that map to frameworks like MITRE ATT&CK.

  • Detection Opportunities in logs, network traffic, or endpoint activity.

  • Weak Points in malware design that defenders can exploit for mitigation.

In short: knowing how malware behaves is the key to stopping it.


Case Study: WannaCry Ransomware

One of the most infamous malware outbreaks was the WannaCry ransomware attack in May 2017. It spread rapidly across the globe, exploiting a vulnerability in the Windows SMB protocol (EternalBlue, leaked from NSA tools).

Key Features Demonstrated by WannaCry:

  • Exploit and Propagation: Used EternalBlue to spread without user interaction.

  • Persistence and Encryption: Encrypted user files and demanded ransom payments in Bitcoin.

  • C2 Communication: Contacted hardcoded domains for instructions. Interestingly, a researcher discovered a “kill switch” domain that, when registered, stopped the spread.

Lessons Learned:

  • Unpatched systems remain the biggest vulnerability.

  • Ransomware can cripple critical infrastructure (hospitals, telecoms, government services).

  • Incident response speed and global collaboration are crucial.

WannaCry demonstrated how malware features—exploit delivery, lateral movement, payload execution, and C2—combine to create large-scale impact. It also underscored the value of understanding malware behaviors in order to recognize and stop such attacks quickly.

How to Safely Obtain Malware Samples for Analysis

For malware analysis training and research, it is critical to use legitimate, trusted sources that provide samples in a controlled manner. Never download samples from unverified websites. Below are safe options widely used by researchers:

  1. TheZoo (GitHub project)

    • A collection of live and decompiled malware samples, provided for educational and research purposes.

  2. MalwareBazaar (by abuse.ch)

    • A community-driven platform for sharing and downloading verified malware samples.

  3. VX Underground

    • Large repository of malware samples and related research material.

  4. Any.Run Malware Trends

    • Interactive sandbox environment where samples can be downloaded after free registration.

Best Practices When Handling Samples:

  • Use a dedicated analysis environment (isolated VMs or air-gapped lab).

  • Never run malware on your host OS or on production networks.

  • Take snapshots of your VMs before testing.

  • Store samples in password-protected archives (common password: infected).

  • Always follow your organization’s ethical and legal guidelines when accessing or analyzing samples.

Effective Mitigation Strategies

1. Preventive Controls

  • Regular Patching: Keep OS and applications updated to close vulnerabilities.

  • Least Privilege: Limit user rights to reduce the impact of compromise.

  • Application Whitelisting: Only allow trusted software to run.

2. Detection Controls

  • Endpoint Detection and Response (EDR): Monitor for suspicious processes, memory injections, or abnormal behavior.

  • Network Monitoring: Watch for unusual DNS lookups, beaconing patterns, or data exfiltration attempts.

  • Threat Intelligence: Use IoCs and TTPs from previous incidents to hunt for new infections.

3. Response Controls

  • Incident Response Plans: Ensure a structured process for containment, eradication, and recovery.

  • Backups: Maintain offline or immutable backups to recover from ransomware.

  • Forensics and Analysis: Investigate malware samples to learn and strengthen defenses.

4. User Awareness

  • Security Training: Educate staff about phishing, social engineering, and safe browsing.

  • Simulated Attacks: Run phishing simulations and red-team exercises.


Conclusion

Malware continues to evolve, but its core features remain predictable: persistence, evasion, communication, escalation, and payload delivery. By studying how malware works, cybersecurity professionals gain the knowledge needed to anticipate attacks, detect infections early, and respond effectively.

Successful malware analysis is not about tools alone—it’s about understanding the adversary’s mindset. With this knowledge, organizations can implement strong preventive, detective, and responsive measures to reduce risk and ensure resilience against evolving threats.

Benign C++ Simulator — Source Code and Feature Discussion

Below is a safe, single-file C++ simulator you can include in your lab to emulate common malware network behaviors for testing with INetSim. It is intentionally non-destructive and only performs DNS lookups, HTTP/HTTPS GETs, and printed simulated actions. Build and run only in isolated lab environments.

// safe-fake-malware-simulator.cpp
// Purpose: A *benign* simulator for malware network behavior for lab/testing with INetSim.
// - DOES NOT perform destructive actions, persistence, propagation, or privilege escalation.
// - Only performs harmless DNS lookups and HTTP GET requests to a user-specified host/IP.
// - Use in isolated, offline lab networks only.

// Build: sudo apt update && sudo apt install -y libcurl4-openssl-dev
// Compile: g++ -std=c++17 -O2 -o fake_beacon safe-fake-malware-simulator.cpp -lcurl
// Run (example): ./fake_beacon --target inetsim.local --interval 10 --count 5

#include <iostream>
#include <string>
#include <thread>
#include <chrono>
#include <cstdlib>
#include <vector>
#include <cstring>
#include <netdb.h>
#include <arpa/inet.h>
#include <curl/curl.h>
#include <random>

static size_t write_callback(void* contents, size_t size, size_t nmemb, void* userp) {
    // Discard body (we only want headers/status). This keeps the program non-destructive.
    (void)contents; (void)userp; return size * nmemb;
}

std::vector<std::string> resolve_hostname(const std::string &host) {
    std::vector<std::string> addrs;
    struct addrinfo hints, *res, *p;
    std::memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_UNSPEC; // IPv4 or IPv6
    hints.ai_socktype = SOCK_STREAM;

    int rv = getaddrinfo(host.c_str(), nullptr, &hints, &res);
    if (rv != 0) {
        std::cerr << "[DNS] getaddrinfo: " << gai_strerror(rv) << "\n";
        return addrs;
    }

    char ipstr[INET6_ADDRSTRLEN];
    for (p = res; p != nullptr; p = p->ai_next) {
        void *addr;
        if (p->ai_family == AF_INET) { // IPv4
            struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr;
            addr = &(ipv4->sin_addr);
        } else { // IPv6
            struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr;
            addr = &(ipv6->sin6_addr);
        }
        inet_ntop(p->ai_family, addr, ipstr, sizeof(ipstr));
        addrs.push_back(std::string(ipstr));
    }
    freeaddrinfo(res);
    return addrs;
}

std::string get_random_user_agent() {
    static const std::vector<std::string> user_agents = {
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
        "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko",
        "curl/7.68.0",
        "Python-urllib/3.8",
        "Java/1.8.0_291",
        "Go-http-client/1.1",
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15"
    };
    
    static std::random_device rd;
    static std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(0, user_agents.size() - 1);
    
    return user_agents[dis(gen)];
}

int http_get(const std::string &url, long &http_code, long timeout_sec) {
    CURL *curl = curl_easy_init();
    if (!curl) return -1;
    
    curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
    curl_easy_setopt(curl, CURLOPT_NOBODY, 0L); // fetch body (but our callback discards it)
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout_sec);
    curl_easy_setopt(curl, CURLOPT_USERAGENT, get_random_user_agent().c_str());
    
    // Follow redirects in a controlled manner
    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
    curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 3L);
    
    // For lab use only: disable SSL verification (to work with self-signed certs)
    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
    
    CURLcode res = curl_easy_perform(curl);
    if (res != CURLE_OK) {
        std::cerr << "[HTTP] curl error: " << curl_easy_strerror(res) << "\n";
        curl_easy_cleanup(curl);
        return -1;
    }
    
    curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
    curl_easy_cleanup(curl);
    return 0;
}

void simulate_icmp_ping(const std::string& target_ip) {
    std::cout << "[ICMP] Simulating ping to " << target_ip << " (no actual packets sent)\n";
    std::cout << "[ICMP] Would send: ping -c 1 " << target_ip << " (simulated only)\n";
}

void simulate_dns_query(const std::string& domain) {
    std::cout << "[DNS-TUNNEL] Simulating DNS query for " << domain << ".sub.example.com\n";
    std::cout << "[DNS-TUNNEL] Would resolve: " << domain << ".sub.example.com (simulated only)\n";
}

void usage(const char *prog) {
    std::cout << "Safe Fake " << prog << " - benign INetSim traffic simulator\n";
    std::cout << "Usage: " << prog << " --target <host-or-ip> [--interval <seconds>] [--count <n>] [--https]\n";
    std::cout << "Example: " << prog << " --target inetsim.local --interval 10 --count 5 --https\n";
    std::cout << "Options:\n";
    std::cout << "  --target    Target hostname or IP address (required)\n";
    std::cout << "  --interval  Seconds between beacons (default: 5)\n";
    std::cout << "  --count     Number of beacons (0 = run forever, default: 0)\n";
    std::cout << "  --https     Use HTTPS instead of HTTP\n";
    std::cout << "  --icmp      Simulate ICMP ping requests\n";
    std::cout << "  --dns-tunnel Simulate DNS tunneling attempts\n";
}

int main(int argc, char** argv) {
    if (argc < 3) {
        usage(argv[0]);
        return 1;
    }

    std::string target;
    int interval = 5; // seconds between beacons
    int count = 0; // 0 = run forever
    bool use_https = false;
    bool simulate_icmp = false;
    bool simulate_dns_tunnel = false;

    for (int i = 1; i < argc; ++i) {
        std::string a = argv[i];
        if (a == "--target" && i + 1 < argc) { target = argv[++i]; }
        else if (a == "--interval" && i + 1 < argc) { interval = std::atoi(argv[++i]); }
        else if (a == "--count" && i + 1 < argc) { count = std::atoi(argv[++i]); }
        else if (a == "--https") { use_https = true; }
        else if (a == "--icmp") { simulate_icmp = true; }
        else if (a == "--dns-tunnel") { simulate_dns_tunnel = true; }
        else { usage(argv[0]); return 1; }
    }

    if (target.empty()) { usage(argv[0]); return 1; }

    std::cout << "[INFO] Starting benign simulator. Target=" << target 
              << " interval=" << interval << "s count=" << count 
              << " HTTPS=" << (use_https ? "yes" : "no") << "\n";
    std::cout << "[WARNING] This tool should only be used in isolated lab environments!\n";

    curl_global_init(CURL_GLOBAL_DEFAULT);

    int iterations = 0;
    while (count == 0 || iterations < count) {
        ++iterations;
        std::cout << "\n[BEACON] Iteration " << iterations << "\n";

        // 1) DNS lookup
        std::cout << "[DNS] Resolving: " << target << "\n";
        auto addrs = resolve_hostname(target);
        if (addrs.empty()) {
            std::cout << "[DNS] No addresses found or resolution failed.\n";
        } else {
            for (const auto &ip : addrs) std::cout << "[DNS] -> " << ip << "\n";
            
            // Use first resolved IP for ICMP simulation
            if (simulate_icmp && !addrs.empty()) {
                simulate_icmp_ping(addrs[0]);
            }
        }

        // 2) HTTP/HTTPS GET to target
        std::string url = target;
        if (url.find("://") == std::string::npos) {
            url = (use_https ? "https://" : "http://") + url + "/";
        }

        long code = 0;
        std::cout << "[HTTP] GET " << url << " (User-Agent: " << get_random_user_agent() << ")\n";
        if (http_get(url, code, 10) == 0) {
            std::cout << "[HTTP] Response code: " << code << "\n";
        } else {
            std::cout << "[HTTP] Request failed.\n";
        }

        // 3) Simulate DNS tunneling if enabled
        if (simulate_dns_tunnel) {
            simulate_dns_query(target);
        }

        // 4) Simulated "beacon" payload (harmless)
        std::cout << "[SIM] Local status: {\"host\":\"simulated-host\", \"uptime\":\"0d0h\", \"note\":\"benign-test\"}\n";

        // Sleep with improved jitter algorithm
        static std::random_device rd;
        static std::mt19937 gen(rd());
        std::uniform_int_distribution<> dis(-interval, interval);
        
        int jitter = dis(gen);
        int sleep_for = std::max(1, interval + jitter);
        std::cout << "[SLEEP] Sleeping " << sleep_for << " seconds (base: " << interval << "s, jitter: " << jitter << "s)...\n";
        std::this_thread::sleep_for(std::chrono::seconds(sleep_for));
    }

    curl_global_cleanup();
    std::cout << "[INFO] Finished. Total iterations: " << iterations << "\n";
    return 0;
}

Overall Purpose

This program is a benign malware network behavior simulator. Its sole purpose is to safely mimic the network traffic patterns of real malware—specifically, the "beaconing" activity to a Command & Control (C2) server—for the purpose of testing security tools like INetSim (a lab service that simulates internet services) in a controlled, isolated environment.

Crucially, it is completely harmless. It does not perform any destructive, persistent, or malicious actions. It only generates network traffic.

Detailed Breakdown by Component

1. The write_callback Function


static size_t write_callback(void* contents, size_t size, size_t nmemb, void* userp) {
    (void)contents; (void)userp; return size * nmemb;
}

  • What it does: This function is called by the libcurl library whenever it receives data (the HTML body) from the HTTP request.

  • The Key Detail: It discards all the data it receives. The (void)contents; line is a deliberate way to ignore the data, preventing it from being processed or saved to disk. This ensures the program is non-destructive.

2. The resolve_hostname Function


std::vector<std::string> resolve_hostname(const std::string &host) {
    // ... (code uses getaddrinfo) ...
    inet_ntop(p->ai_family, addr, ipstr, sizeof(ipstr));
    addrs.push_back(std::string(ipstr));
    // ...
}

  • What it does: This function performs a DNS lookup on the provided hostname (e.g., inetsim.local).

  • How it works: It uses the standard getaddrinfo() system call to query the system's DNS resolver. It correctly handles both IPv4 and IPv6 addresses (AF_UNSPEC), converts the binary address to a human-readable string (inet_ntop), and returns a list of all IP addresses associated with the hostname.

  • Why it's important: The first step for most malware is to resolve the domain name of its C2 server to an IP address. This simulates that exact behavior.

3. The get_random_user_agent Function


std::string get_random_user_agent() {
    static const std::vector<std::string> user_agents = { /* ... */ };
    // ... (random selection code) ...
    return user_agents[dis(gen)];
}

  • What it does: Returns a random string from a predefined list of web browser and tool User-Agents.

  • Why it's important: Real malware often randomizes its User-Agent to blend in with normal web traffic and avoid simple detection rules that look for a single, suspicious string. This adds a layer of realism.

4. The http_get Function


int http_get(const std::string &url, long &http_code, long timeout_sec) {
    CURL *curl = curl_easy_init();
    curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
    // ... (other options) ...
    CURLcode res = curl_easy_perform(curl);
    curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
}

  • What it does: This is the core function that performs an HTTP or HTTPS GET request to the target URL using the libcurl library.

  • Key Configuration:

    • CURLOPT_NOBODY, 0L: Fetches the body (but the callback discards it).

    • CURLOPT_FOLLOWLOCATION, 1L: Follows HTTP redirects (like a real browser would).

    • CURLOPT_SSL_VERIFYPEER, 0LDisables SSL certificate verification. This is critical for lab use where tools like INetSim use self-signed certificates, but it's a major security risk in the real world.

    • CURLOPT_USERAGENT: Uses the random User-Agent from the function above.

  • The Goal: It successfully connects to the target web server, completes the HTTP request, and retrieves the response status code (e.g., 200 OK, 404 Not Found). This simulates the malware "checking in" with its C2 server.

5. The main Function (The Orchestrator)

This is where the program's workflow is executed.

Phase 1: Argument Parsing

  • It reads command-line arguments like --target--interval, and --count.

  • It sets flags for optional behaviors like --https--icmp, and --dns-tunnel.

Phase 2: The Main Loop ("Beaconing")
The program enters a loop that runs for the specified number of counts (or forever if count=0). Each loop iteration represents one "beacon" or "check-in."

  1. DNS Resolution: It calls resolve_hostname(target) and prints the results. This is the first network call, simulating malware figuring out where to call home.

  2. ICMP Simulation (Optional): If the --icmp flag is used, it only prints a message simulating a ping. It does not send any actual ICMP packets. This tests monitoring for network discovery attempts.

  3. HTTP Request: It constructs the full URL (adding http:// or https:// if needed) and calls http_get. This is the core beaconing activity, simulating the malware requesting commands from its server.

  4. DNS Tunneling Simulation (Optional): If the --dns-tunnel flag is used, it only prints a message about making a DNS query. It does not perform actual DNS tunneling. This tests alerting for suspicious DNS patterns.

  5. Status Report: It prints a harmless, fake JSON status message to the console. This simulates the kind of data malware might report back to its operator (system info, uptime).

  6. Sleep with Jitter: This is a critical feature.

std::uniform_int_distribution<> dis(-interval, interval);
int jitter = dis(gen);
int sleep_for = std::max(1, interval + jitter);

    • It doesn't sleep for a fixed time. It adds a random "jitter" (e.g., for --interval 10, it might sleep for 7, 10, or 13 seconds).

    • Why? Real malware uses jitter to avoid being detected by simple timing-based signatures. A regular, metronomic beacon every 10 seconds is easy to spot. An irregular pattern is much stealthier.

Phase 3: Cleanup

  • After the loop finishes, it cleans up the libcurl resources and exits.


Summary: What the Program Actually Does on the Network

When you run ./fake_beacon --target inetsim.local --interval 10 --count 5, the program will:

  1. 5 times, roughly every 10 seconds (with some random variation):

  2. Query your DNS server for the IP address(es) of inetsim.local.

  3. Open a TCP connection to port 80 (HTTP) on the IP it received from DNS.

  4. Send a complete HTTP GET request for the path /, with a random User-Agent header.

  5. Read the HTTP response from the server (and immediately discard the content), only noting the status code.

  6. Print all of these actions to the console for you to see.

  7. Sleep until it's time for the next beacon.

It is a perfect, safe tool for generating traffic that will trigger security monitoring tools looking for: DNS queries to suspicious domains, beaconing HTTP traffic, and irregular network communication patterns—all without any risk to your system or network.