Loading...

Threats

Botnets: how they work and defend

Discover what botnets are, how they work, legal and illegal uses, how to detect them and defend against cyber threats.

botnets cyber security

Table of contents

  • What is a botnet?
  • How a botnet works
  • Legal applications of botnets
  • Illegal applications of botnets
  • How to detect a botnet
  • How to defend against a botnet

In the world of cyber security, few terms are as feared and misunderstood as botnet. The word conjures up images of hacker attacks, compromised computers, and invisible malware working silently in the background. But what exactly is a botnet? And why can it be used for both legal and illegal purposes?

In this article, we’ll explore in detail what a botnet is, how it works, its legitimate and criminal applications, how to detect one in your network, and most importantly, how to defend yourself. We’ll also look at practical examples, including code snippets and real tools used by security professionals.

What is a botnet?

A botnet is a network of devices infected with malware, remotely controlled by an operator known as the botmasteror herder. The term comes from “robot” and “network,” referring to how these devices (called bots or zombies) act automatically and silently on behalf of a central controller.

How a botnet is created

The formation of a botnet typically follows these stages:

  1. Initial infection – Malware is distributed via phishing, drive-by downloads, or vulnerabilities in software or exposed IoT devices.
  2. C&C connection – Once infected, the device connects to a Command and Control server to receive instructions.
  3. Propagation – Some botnet malware is self-replicating and can infect other hosts in the same or external networks.
  4. Execution – The botmaster can issue global or targeted commands to the entire botnet.

Common architectures

  • Client-Server
    Each bot connects to a central C&C server.
  • Peer-to-Peer (P2P)
    Bots communicate and distribute commands among themselves.
  • Social media-based
    Botmasters may post encoded instructions on Twitter or Telegram.
  • Blockchain-based botnets
    Use decentralized ledgers to hide C&C mechanisms.

Technical example: bot connecting to a C&C server

Here’s a basic Python script simulating a bot client connecting to a C&C server.

import socket

def bot_connect():

    host = '192.168.0.100'  # IP of C&C server

    port = 4444             # port used by the bot

    try:

        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:

            s.connect((host, port))

            s.sendall(b'BOT READY')

            data = s.recv(1024)

            print('Command received:', data.decode())

    except Exception as e:

        print('Connection error:', e)

bot_connect()

Real-world botnets use encryption, anti-analysis techniques, and persistence mechanisms. This code is only for educational purposes.

Real-world examples

  • Mirai
    Exploited IoT devices with default credentials to infect millions and conduct massive DDoS attacks in 2016.
  • Emotet
    Began as a banking trojan and evolved into a modular botnet delivering ransomware.
  • RustBot
    A modern P2P botnet written in Rust, targeting Windows and Linux.

How a botnet works

The operation of a botnet is a structured and multi-phase process, allowing an attacker to control thousands or even millions of devices from a single interface. Let’s explore the key steps, architectures, and a basic Python example to clarify.

1. Infection phase

The botnet begins with infection, often via:

  • Phishing emails with malicious attachments
  • Exploits in vulnerable software or systems
  • Malicious downloaders from shady websites
  • IoT devices with default credentials or open ports

Once the bot malware is installed, the device becomes part of the botnet.

2. Connection to Command and Control (C&C)

The infected bot will:

  • Connect to a C&C server
  • Use HTTP, DNS tunneling, IRC, Telegram, or encrypted channels
  • Send periodic heartbeat signals
  • Receive commands like “start DDoS”, “download payload”, “steal credentials”

Some botnets use decentralized P2P systems instead of a single C&C point.

3. Propagation (optional)

Advanced botnets spread automatically:

  • Scanning for vulnerable IPs or open ports
  • Brute-forcing credentials on SSH, RDP, Telnet
  • Infecting other IoT or LAN devices
  • Downloading new modules (stealers, miners, ransomware)

4. Command execution

The botmaster can send instructions to:

  • The entire botnet
  • A group of bots by IP range or country
  • Specific targets (e.g., only Windows devices)

Botnet architectures

a) Client-Server

  • Bots connect to a central server
  • Easy to build, easy to take down

b) Peer-to-Peer (P2P)

  • Bots communicate among themselves
  • Very resilient, harder to disrupt

c) Social media-based

  • Uses posts on platforms like Twitter, Telegram, or YouTube as C&C
  • Difficult to detect without harming normal users

d) Domain Generation Algorithm (DGA)

  • Bots generate daily domains to find the C&C
  • Difficult for defenders to predict and blacklist

Technical example: simple bot and C&C in Python

Bot (client)

# bot.py

import socket

def connect_to_cnc():

    server = ('127.0.0.1', 9999)

    try:

        s = socket.socket()

        s.connect(server)

        s.sendall(b'BOT ACTIVE')

        command = s.recv(1024)

        print("Received command:", command.decode())

    except:

        print("Failed to connect")

connect_to_cnc()

C&C server

# cnc.py

import socket

def cnc_server():

    s = socket.socket()

    s.bind(('0.0.0.0', 9999))

    s.listen(5)

    print("C&C server running...")

    conn, addr = s.accept()

    print("Connection from", addr)

    data = conn.recv(1024)

    print("Received:", data.decode())

    conn.send(b'attack http://target.com')

    conn.close()

cnc_server()

This is just a proof-of-concept, not for real-world use.

Real-world example: Mirai

Mirai targeted IoT devices with open Telnet and default credentials. Each bot scanned the internet for more victims. Once grown, the botnet launched huge DDoS attacks—like the 2016 one that disrupted Dyn DNS, taking down Twitter, Netflix, and GitHub.

Legal applications of botnets

While “botnet” often brings to mind DDoS attacks and data breaches, in legal contexts, we refer to coordinated networks of agents or devices used for ethical, productive, or scientific purposes. The key difference is user consentand intent.

1. Volunteer distributed computing

One of the most well-known legal uses of botnet-like networks is volunteer computing.

Real-world examples:

  • Folding@home
    Simulates protein folding to aid research on diseases.
  • SETI@home
    Scanned radio signals for signs of extraterrestrial life.
  • BOINC
    An open-source platform for building distributed academic projects.

Volunteers install a client that connects to a central controller, fetches a task, processes it, and sends back results. A positive-use botnet.

2. Stress testing and load simulations

IT teams use bot frameworks to simulate traffic during performance and load testing.

Tools:

  • Apache JMeter
  • Locust
  • Gatling
  • Artillery

Each “bot” behaves like a real user, allowing developers to test scalability, latency, and failure points in web infrastructure.

3. Cyber security labs and malware research

Security professionals use botnet-like setups for:

  • Simulated attacks in isolated networks
  • Malware behavioral analysis in sandbox environments
  • Anomaly detection training
  • Red team exercises

These networks are often referred to as honeynets, testbeds, or controlled botnets, and they play a crucial role in threat intelligence and cyber defense.

4. IoT orchestration and smart automation

In smart homes, factories, or farms, botnet-like systems are used for:

  • Environmental monitoring
  • Irrigation control
  • Smart lighting and heating
  • Automated industrial processes

All devices connect to a central controller and execute commands—forming a constructive, legal botnet for automation and optimization.

Technical example: legal bot client

# client_legit_bot.py

import requests

def simulate_user_task():

    task = requests.get("https://server.myproject.org/gettask").json()

    result = {"client_id": "alpha01", "result": task['data'][::-1]}  # example: reverse a string

    requests.post("https://server.myproject.org/submit", json=result)

simulate_user_task()

This code simulates a legal client receiving a task from a controller, processing it, and sending back results. Useful for legitimate testing and research.

Code simulates a legal client

Illegal applications of botnets

Criminal botnets are central tools in modern cybercrime, offering scalable and automated ways to carry out a wide range of attacks and frauds.

1. DDoS (Distributed Denial of Service) attacks

Botnets are often used to perform DDoS attacks, overwhelming targets with traffic from thousands of infected devices.

Real-world case:

  • The Dyn DNS attack (2016) by Mirai botnet caused outages on Netflix, Twitter, Reddit with over 1 Tbps of traffic.

2. Spam and phishing campaigns

Bots act as spam relays, sending out phishing emails with malicious attachments or links.

Purposes:

  • Stealing credentials
  • Installing trojans or ransomware
  • Spreading malware like Emotet or Qakbot

3. Click fraud

Bots simulate human interaction to click on ads, committing advertising fraud and inflating revenue for shady website operators.

4. Cryptocurrency mining

Botnets hijack the host system’s CPU/GPU to mine crypto (especially Monero, due to its CPU-minability).

Sample code:

import os

os.system("xmrig -o pool.minexmr.com:4444 -u YOUR_WALLET -p x -k")

This runs a miner in the background, draining resources without consent.

5. Credential and data theft

Bots may log keystrokes, capture screenshots, or steal browser cookies to exfiltrate:

  • Credit cards and banking info
  • Passwords and tokens
  • Corporate secrets and documents

Data is sold on darknet markets.

6. Ransomware delivery

Botnets distribute ransomware payloads in multi-stage attacks:

  1. Initial infection (e.g., via phishing)
  2. Malware loader activates ransomware
  3. Files are encrypted and ransom demanded

7. Cyber espionage and APT

Advanced botnets are used in state-sponsored cyber espionage, often targeting governments and companies.

Capabilities:

  • Monitor user activity
  • Exfiltrate files
  • Control microphones/webcams
  • Install sabotage tools

APT groups like Fancy Bear and APT41 have used botnets in long-term campaigns.

Technical example: simple keylogger bot module

# Keylogger (educational purpose)

import pynput.keyboard

def on_press(key):

    with open("log.txt", "a") as f:

        f.write(str(key) + "\n")

listener = pynput.keyboard.Listener(on_press=on_press)

listener.start()

In real attacks, such data is encrypted and sent to a remote C&C server.

How to detect a botnet

Detecting a botnet is difficult, especially when dealing with stealthy or encrypted communication, but a combination of network monitoring, log correlation, and anomaly detection can help expose infected systems.

1. Indicators of Compromise (IoC)

  • Unusual CPU/network usage
  • Unknown processes running
  • Outbound traffic to strange IPs or ports
  • Unauthorized email activity
  • Antivirus/firewall disable attempts
  • Unusual port usage (e.g., 6667 IRC, 1337 TCP)
  • Logs with repetitive access patterns or rare behaviors

2. Network traffic analysis

Tools:

  • Wireshark
  • Zeek (Bro)
  • Suricata
  • tcpdump

Zeek example:

zeek -r suspicious_traffic.pcap

This provides a detailed breakdown of protocols, IPs, and suspicious behavior.

Wireshark filters:

ip.dst == 185.234.219.167

dns.qry.name contains ".xyz"

Useful to catch DNS tunneling or C&C beaconing.

3. Log correlation

Use SIEM tools like:

  • Splunk, Graylog, Kibana
  • Sysmon + Windows Event Viewer
  • Auditd on Linux

Correlate logs across time and source to identify coordinated or repetitive behavior.

4. Process behavior monitoring

Tools:

  • Process Explorer
  • Autoruns
  • Sysinternals Suite

Look for:

  • Programs running from temp or obscure folders
  • Child processes from unknown origins
  • Registry keys that persist malware

5. Sandbox malware analysis

Try:

  • Cuckoo Sandbox
  • Any.Run
  • Hybrid Analysis
  • Joe Sandbox

They allow you to isolate and monitor malware behavior, C&C attempts, registry changes, etc.

6. Python script: monitor suspicious ports

import psutil

suspicious_ports = [6667, 1337, 23, 445, 5555]

for conn in psutil.net_connections(kind='inet'):

    if conn.status == 'ESTABLISHED':

        ip, port = conn.raddr

        if port in suspicious_ports:

            print(f"[!] Suspicious connection found: {ip}:{port}")

Use it on servers or endpoints to detect live suspicious connections.

7. Threat intelligence feeds

Use sources like:

  • AbuseIPDB
  • AlienVault OTX
  • VirusTotal API
  • MalwareBazaar

to match suspicious activity with known botnet indicators.

How to defend against a botnet

Botnet defense is a layered process involving prevention, detection, containment, and long-term protection.

1. Prevent infection

a) Update everything

  • Keep OS, firmware, and apps up to date.
  • Change default credentials on IoT devices.

b) Reliable antivirus

  • Tools: ESET, Kaspersky, Bitdefender, Malwarebytes.
  • Enable real-time scanning.

c) Firewalls

  • Use personal firewalls and corporate firewalls with DPI.
  • Block unused ports (e.g., 6667, 23, 135).

d) User training

  • Teach phishing awareness, USB safety, and basic hygiene.
  • Try simulation platforms like GoPhish.

2. Monitoring and detection

a) IDS/IPS tools

  • Use Suricata, Snort, or Zeek.
  • Snort DDoS detection example:

alert icmp any any -> any any (msg:”Possible ICMP flood”; dsize: >800; sid:1000001;)

b) Centralized log management

  • Implement SIEM tools: Splunk, ELK, Graylog.
  • Correlate events and raise alerts on suspicious activity.

3. Containment

  • Immediately isolate infected systems (e.g., VLAN, VPN kill).
  • Block outbound C&C connections using firewalls and DNS filters.
  • Disable remote interfaces (RDP, SSH, SMB).

4. Removal and remediation

  • Use rescue disks (e.g., Kaspersky Rescue CD) for offline scanning.
  • Clean registry autostarts with tools like Autoruns.
  • For rootkit-level infections, reinstall the OS.

5. Advanced protection and resilience

a) Network segmentation

  • Separate IoT, servers, and clients.
  • Use ACLs to limit lateral movement.

b) Zero Trust

  • Authenticate every device, even inside the LAN.
  • Tools: Okta, Azure AD, OPA.

c) Threat intelligence

  • Use feeds like AbuseIPDB, OTX, and ThreatFox.
  • Block malicious IPs dynamically.

Python example: auto-block malicious IPs

import requests

import subprocess

def fetch_bad_ips():

    data = requests.get("https://feodotracker.abuse.ch/downloads/ipblocklist.txt").text

    return [line for line in data.splitlines() if not line.startswith('#')]

for ip in fetch_bad_ips():

    subprocess.run(["iptables", "-A", "OUTPUT", "-d", ip, "-j", "DROP"])

Questions and answers

  1. What is a botnet in simple terms?
    A network of infected devices remotely controlled by a hacker to perform coordinated tasks.
  2. Which devices can become part of a botnet?
    Computers, smartphones, routers, cameras, smart TVs, and more.
  3. Can botnets be used legally?
    Yes, when users consent—such as in volunteer computing projects.
  4. How do devices get infected?
    Via phishing, malicious downloads, or unpatched software vulnerabilities.
  5. What does a Command and Control server do?
    It sends instructions to infected bots in the network.
  6. How can I tell if my device is part of a botnet?
    Look for high resource usage, strange connections, and unwanted actions.
  7. Can I remove a bot from my device?
    Yes, using antivirus tools—though professional help may be needed for advanced threats.
  8. What happens if my router is infected?
    It could be used for DDoS or to infect other devices on your network.
  9. Are botnets always active?
    Not necessarily—they can stay dormant until activated by the botmaster.
  10. What’s the most dangerous botnet ever?
    Mirai, which disrupted major online services using IoT devices.

To top