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
| Word | What it means |
|---|---|
| Command and control | how an attacker's program receives orders |
| Beacon | a check-in sent on a schedule |
| Sleep | the wait between two check-ins |
| Jitter | random change added to the sleep |
| Proxy log | a 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 questionsThe 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
| Sign | In the proxy log | Easy for the attacker to change? |
|---|---|---|
| User-Agent | A program's name, such as updater/1.4 | Yes, one setting |
| Destination | A host few machines ever visit | Somewhat, it costs a new server |
| Rhythm | Gaps that hardly vary | Somewhat, with more jitter |
| Size | The same small request every time | Harder, the protocol sets it |
The cells students fill in are left blank in this preview.
Check
Have a go
Check
3 questionsMove into the lab's folder and make emu
cd ~/detect && mkdir -p emuShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the stand-in proxy, part 1
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.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the stand-in proxy, part 2
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.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the harmless check-in sender
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.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Start the proxy with an empty log
rm -f emu/proxy.log && python3 emu/listener.py & sleep 1Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Send 8 check-ins as updater/1.4
python3 emu/pulse.py 8 1 0.3 updater/1.4Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Match the known User-Agent
grep -c updater/1.4 emu/proxy.logShown here, not run. Press Start lab to type it into your own lab’s terminal.
Send 8 more with a browser's User-Agent
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
grep -c updater/1.4 emu/proxy.logShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the rhythm check
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.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Check the rhythm of each sender
python3 emu/rhythm.py emu/proxy.logShown 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
python3 emu/pulse.py 8 1 0.9 updater/1.5Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Check the rhythm again
python3 emu/rhythm.py emu/proxy.logShown here, not run. Press Start lab to type it into your own lab’s terminal.
Check
Have a go
Check
3 questionsFix 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
pkill -f emu/listener.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Try it: how far jitter spreads the waits
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.
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