Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

Command and control: seeing and stopping it

After this lesson: I can recognise a command and control beacon in a proxy log and explain how to detect it.

65 min lesson14 commandsDetection engineering lab: Suricata rules, Sigma rules and Zeek-style logs on one private Ubuntu VM

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

A quiet program that keeps phoning home

An attacker's program on a server is no use to them unless it can take orders. So it calls out, again and again, and asks whether there is anything to do.

Those calls are often the only thing the defenders can see. In this lesson you send harmless calls of that shape inside your own lab copy and learn which signs give them away.

By the end of this lesson

Note

I can recognise a command and control beacon in a proxy log and explain how to detect it.

Key words

WordWhat it means
Command and controlhow an attacker's program receives orders
Beacona check-in sent on a schedule
Sleepthe wait between two check-ins
Jitterrandom change added to the sleep
Proxy loga record of each web request leaving a network

The cells students fill in are left blank in this preview.

Starter

Have a go

Starter

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

The one rule

Important

Send check-ins only inside your own lab copy, to the listener you start. Never build or run a real command and control tool. Testing a real network needs the owner's written permission, and unauthorised access is an offence under the Computer Misuse Act 1990.

A beacon sleeps, wakes and asks

Command and control is the link between an attacker and their program. The program sends a beacon, a small check-in, then waits: its sleep. Most add jitter, so the waits differ.

It usually travels over web traffic, sometimes DNS. In an office, web requests leave through a proxy, so the proxy log is where a defender sees them.

Worked example: what gives a beacon away

SignIn the proxy logEasy for the attacker to change?
User-AgentA program's name, such as updater/1.4Yes, one setting
DestinationA host few machines ever visitSomewhat, it costs a new server
RhythmGaps that hardly varySomewhat, with more jitter
SizeThe same small request every timeHarder, the protocol sets it

The cells students fill in are left blank in this preview.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Move into the lab's folder and make emu

Command
cd ~/detect && mkdir -p emu

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the stand-in proxy, part 1

Command
printf '%s\n' 'import http.server, time, uuid' 'LOG = open("emu/proxy.log", "a", buffering=1)' 'FIELDS = ["ts", "uid", "id.orig_h", "id.orig_p", "id.resp_h", "id.resp_p", "method", "host", "uri", "user_agent", "request_body_len", "status_code"]' 'if LOG.tell() == 0:' '    LOG.write("#path" + chr(9) + "http" + chr(10) + "#fields" + chr(9) + chr(9).join(FIELDS) + chr(10))' 'class Proxy(http.server.BaseHTTPRequestHandler):' '    def do_POST(self):' '        size = int(self.headers.get("Content-Length", 0))' '        self.rfile.read(size)' '        self.send_response(200)' '        self.end_headers()' '        self.wfile.write(b"ok")' '        row = ["%.6f" % time.time(), "C" + uuid.uuid4().hex[:17], self.client_address[0], str(self.client_address[1]), "127.0.0.1", "8080",' '               "POST", self.headers.get("Host", "-"), self.path, self.headers.get("User-Agent", "-"), str(size), "200"]' '        LOG.write(chr(9).join(row) + chr(10))' > emu/listener.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the stand-in proxy, part 2

Command
printf '%s\n' '    def log_message(self, *args):' '        pass' 'print("listening on 127.0.0.1:8080, logging to emu/proxy.log", flush=True)' 'http.server.HTTPServer(("127.0.0.1", 8080), Proxy).serve_forever()' >> emu/listener.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the harmless check-in sender

Command
printf '%s\n' 'import random, sys, time, urllib.request' 'count, base, jitter, agent = int(sys.argv[1]), float(sys.argv[2]), float(sys.argv[3]), sys.argv[4]' 'r = random.Random(136)' 'for i in range(count):' '    request = urllib.request.Request("http://127.0.0.1:8080/api/check", data=b"id=emu", method="POST",' '                                     headers={"Host": "cdn-update.example", "User-Agent": agent})' '    urllib.request.urlopen(request).read()' '    if i < count - 1:' '        time.sleep(base * (1 + r.uniform(-jitter, jitter)))' 'print("sent", count, "check-ins about every", base, "s with", int(jitter * 100), "per cent jitter as", agent)' > emu/pulse.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Start the proxy with an empty log

Command
rm -f emu/proxy.log && python3 emu/listener.py & sleep 1

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Send 8 check-ins as updater/1.4

Command
python3 emu/pulse.py 8 1 0.3 updater/1.4

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Match the known User-Agent

Command
grep -c updater/1.4 emu/proxy.log

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Send 8 more with a browser's User-Agent

Command
python3 emu/pulse.py 8 1 0.3 "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Match the known User-Agent again

Command
grep -c updater/1.4 emu/proxy.log

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the rhythm check

Command
printf '%s\n' 'import statistics, sys' 'fields, seen = [], {}' 'for line in open(sys.argv[1]):' '    parts = line.rstrip(chr(10)).split(chr(9))' '    if parts[0] == "#fields":' '        fields = parts[1:]' '    elif not line.startswith("#"):' '        row = dict(zip(fields, parts))' '        key = (row["id.orig_h"], row["host"], row["user_agent"])' '        seen.setdefault(key, []).append((float(row["ts"]), row["request_body_len"]))' 'print("source host user_agent n median cv sizes verdict")' 'for key, rows in sorted(seen.items()):' '    ts = [t for t, size in rows]' '    gaps = [b - a for a, b in zip(ts, ts[1:])]' '    if len(ts) < 8:' '        continue' '    cv = statistics.pstdev(gaps) / statistics.mean(gaps)' '    sizes = len({size for t, size in rows})' '    verdict = "beacon-like" if cv < 0.25 else "check: one size" if sizes == 1 else "irregular"' '    print(*key, len(ts), round(statistics.median(gaps), 1), round(cv, 2), sizes, verdict)' > emu/rhythm.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Check the rhythm of each sender

Command
python3 emu/rhythm.py emu/proxy.log

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

A common mistake

Warning

Many people think blocking a beacon's User-Agent or address stops it. Both change with one setting, as the second run showed. Detect what is hard to change as well: the rhythm, the size and how rare the destination is.

Send 8 with 90 per cent jitter

Command
python3 emu/pulse.py 8 1 0.9 updater/1.5

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Check the rhythm again

Command
python3 emu/rhythm.py emu/proxy.log

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Fix it and detect it

The fix is to make calling out hard. Send all web traffic through a proxy, block what it does not know, and log every request. Log DNS too.

Then detect in layers: names from intelligence, rhythm, constant sizes and rare destinations. Stop the stand-in proxy when you finish.

Stop the stand-in proxy

Command
pkill -f emu/listener.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Try it: how far jitter spreads the waits

Code: python
base = 60
jitter = 0.3

shortest = base * (1 - jitter)
longest = base * (1 + jitter)
print("waits between", shortest, "and", longest, "seconds")
# Change jitter to 0.9, then press Run. Would module 105's fixed tolerance still work?

Make a free account to save your work and track your progress.

Assignment: judge a sender from its log

sleep_range(base, jitter) returns the shortest and longest wait, base times 1 minus jitter and 1 plus jitter, each rounded to 2 places, as a tuple.

cv(times) sorts the times, takes the gaps between them and returns the population standard deviation of the gaps divided by their mean, rounded to 2 places.

verdict(times, sizes, least=8, limit=0.25) returns "too few" when there are fewer than least times, "beacon-like" when cv(times) is below limit, "check: one size" when every size is the same, and "irregular" otherwise.

Code: python
def sleep_range(base, jitter):
    return (base, base)

def cv(times):
    return 0

def verdict(times, sizes, least=8, limit=0.25):
    return "irregular"

Make a free account to save your work and track your progress.

Exit quiz

Have a go

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teaching a class? Set this module for your students with a teacher guide, marked assignments and a lab for every student.