Campus Network: VLAN Uplinks Through an AP and Auto Authentication

Published 2026-10-09 15:16 2179 words 11 min read

Madobi Nanami avatar

Madobi Nanami

Nanami 的个人技术博客,记录网络、运维、虚拟化与逆向的实践。

Introduction My dorm building was renovated during the summer after freshman year. When term started again the facilities were new, but someone had broken the network wall plate! For someone who...

Introduction

My dorm building was renovated during the summer after freshman year. When term started again the facilities were new, but someone had broken the network wall plate! For someone who depends on wired, low-latency, link-aggregated connectivity, that is infuriating. The school’s APs are weak and high-latency, and every connection requires re-authenticating through the Captive Protocol, which is painful. The initial answer I got was that everything would be fixed before mid-October, and mid-October is almost here with nobody having shown up to do the work. While mulling it over I turned my attention to the AP installed in every dorm and wondered whether something could be done there. Hence this article.

Environment and Goal

The APs connect through PoE aggregation switches on each floor, one AP per dorm. Normally downstream STA devices join over WiFi and then authenticate on the school’s Captive Protocol portal to get online. My plan is to plug the cable that feeds the AP into my own OpenWrt router and get wired access.

Read This First

Warning: this is a pure stunt article. This way of getting online is neither appropriate nor recommended. Besides being a hassle, modifying school network equipment behind the school’s back could get you held responsible by the school. Enjoy the read, but do not copy it! If you ignore this warning, you are on your own!


Let’s Start

1. Mapping the Network

Plugging the cable straight into the router, I found DHCP hands out an address

Router obtaining an address over DHCP after the AP cable is plugged in
Router obtaining an address over DHCP after the AP cable is plugged in

3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1492 qdisc fq_codel state UP group default qlen 1000
    link/ether 00:e0:4c:d0:1f:f7 brd ff:ff:ff:ff:ff:ff
    inet 172.17.255.165/18 brd 172.17.255.255 scope global eth1
       valid_lft forever preferred_lft forever
    inet6 fe80::2e0:4cff:fed0:1ff7/64 scope link proto kernel_ll 
       valid_lft forever preferred_lft forever

Normally, a downstream STA trying to reach the internet is 302-redirected to the portal site, but trying from my PC did not do that. I then connected a phone to the school WiFi, obtained the portal address, and tested DNS from the router side, where DNS turned out to work.

root@X-wrt-School:~# nslookup *.edu.cn
Server:         127.0.0.1
Address:        127.0.0.1:53

Non-authoritative answer:
Name:   *.edu.cn
Address: 211.*.*.*

Non-authoritative answer:

Trying to ping the portal server directly failed

root@X-wrt-School:~# ping 211.*.*.*
PING 211.*.*.* (211.*.*.*): 56 data bytes
^C
--- 211.*.*.* ping statistics ---
6 packets transmitted, 0 packets received, 100% packet loss

2. Analysing the Routing Policy

The DHCP address the router receives is in 172.0.0.0/8, while a STA that joins over WiFi gets an address in 10.0.0.0/8, which does not match. STAs with that range can reach the portal directly, but the router cannot. So we can infer that there is a firewall between downstream devices and the portal server, and it may only allow the 10.0.0.0/8 range. Since a STA joining over WiFi gets a 10.0.0.0/8 address, the router must be able to obtain one as well somehow. The most likely mechanism is VLAN. Capturing traffic at the router with Wireshark revealed three VLANs. Their subnets are:

VLAN IDNetwork
60210.130.0.0/16
60410.140.0.0/16
60610.150.0.0/16

Joining the three WLANs the AP broadcasts showed how subnets map to ISPs:

VLAN IDNetworkISP
60210.130.0.0/16CTNET
60410.140.0.0/16CMCC
60610.150.0.0/16CUNIQ

With that information in hand, we can start configuring the router.

3. Configuring Interfaces

  1. Open the LuCI WebUI, go to Network -> Interfaces -> Devices and click Add device configuration...
  2. Set Device type to VLAN (802.1q), then enter the VLAN ID and interface name.

Note: you need one VLAN port per user; otherwise, with identical interface parameters, every DHCP request ends up with the same address. If you need multiple VlanIf interfaces on one port, you must change the MAC address of the 2nd and later VlanIf interfaces to a value different from the interface’s own.

Creating an 802.1q VLAN device and entering the VLAN ID
Creating an 802.1q VLAN device and entering the VLAN ID

  1. When all interfaces are created, click Save & Apply.
    All interfaces configured
    All interfaces configured
  2. Switch to the Interfaces tab and click Add new interface...
  3. Choose DHCP Client as the protocol, enter any name you like, and select the VlanIf interface you just created
  4. Go to Advanced Settings and untick Use default gateway

Note: this step matters. If you leave it ticked, the system will add a default route towards that interface’s gateway, which will break the router’s normal internet access! For privacy, you may also want to change Hostname to send when requesting DHCP under General Settings to Do not send a hostname.

  1. When all interfaces are created, click Save & Apply. If every interface gets an address, this part is done.
    Creating a DHCP Client interface with the default gateway unticked
    Creating a DHCP Client interface with the default gateway unticked

Note: on some aarch64 devices, the SoC may restrict you to one VlanIf device per VID. If creating a DHCP Client on a VlanIf fails with DEVICE_CLAIM_FAILED, that is likely the reason. In that case the best approach is: create one VlanIf interface and let multiple users join through MAC VLANs.

4. Trying to Log In

From the analysis above we have the IP address of the Captive Protocol portal, so we can simply pick a MAC VlanIf interface as the egress and add a route to the portal to test it.

ip r add 211.*.*.*/32 via 10.150.0.1 dev lan1.cuniq-***

With the route in place, log in from a downstream device

Campus network Captive Portal login page
Campus network Captive Portal login page
It logged in. Entering the correct campus account and password works.
Campus network authentication success page
Campus network authentication success page
That completes the Captive Protocol portal validation.

5. Making It Persistent

I logged the campus account out, opened BurpSuite and captured the traffic. The login flow turned out to be:

  1. Get the client IP — extract the ip field from the CONFIG blob embedded in the portal page
  2. Get the Challenge Token — GET /cgi-bin/get_challenge?username=<account@domain>&ip=<IP>&callback=cb, which returns a 64-byte hex token (valid for 60 seconds)
  3. HMAC-MD5 — hmd5 = HMAC-MD5 (key=password, msg=token), reverse-engineered from the A(n,t,r) function in the md5 v2.10.0 library inside all.min.js; with two arguments it actually calls HMAC
  4. Encrypt the user info — encrypt the JSON with XXTEA (delta=0x9E3779B9) using the token as the key, then encode it with the custom Base64 alphabet LVoJPiCN2R8G90yg+hmFHuacZ1OWMnrsSTXkYpUq/3dlbfKwv6xztjI7DeBE45QA and prefix it with {SRBX1}
  5. Checksum and login — chksum = SHA1(token+username + token+hmd5 + token+acid + token+ip + token+n + token+type + token+info), then GET /cgi-bin/srun_portal to start a JSONP login

Based on that reverse engineering, here is a login script

GATEWAY=""
CPURL=""

# Set IP route to captive protocol server
ip route add 211.*.*.* via $GATEWAY dev $INTERFACE
echo "Route added, sleep 5s..."
sleep 5

set -euo pipefail

# Get AC_ID from captive protocol url
AUTH_HOST="$(printf '%s\n' "$CPURL" | sed -nE 's#^https?://([^/]+)/.*#\1#p')"
ACID="$(printf '%s\n' "$CPURL" | sed -nE 's/.*ac_id=([0-9]+).*/\1/p')"
[ -z "$ACID" ] && ACID="1"

echo "=== Srun Portal Login ==="
echo "Captive Protocol Server: $AUTH_HOST"
echo "ac_id:      $ACID"
echo "Username:     ${USERNAME}${DOMAIN}"
echo ""

python3 - "$AUTH_HOST" "$ACID" "$USERNAME" "$PASSWORD" "$DOMAIN" << 'PYTHON_SCRIPT'
import sys, json, hmac, hashlib, base64, re, urllib.request, urllib.parse, time

auth_host, ac_id, username_raw, password, domain = sys.argv[1:6]
username = username_raw + domain
base_url = f"http://{auth_host}"

# ---- HTTP GET with retry ----
def http_get(url, timeout=15, retries=5):
    last_err = None
    for attempt in range(1, retries + 1):
        try:
            req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
            with urllib.request.urlopen(req, timeout=timeout) as resp:
                return resp.read().decode('utf-8')
        except Exception as e:
            last_err = e
            wait = attempt * 3
            print(f"  [retry {attempt}/{retries}] {e} — waiting {wait}s...", file=sys.stderr)
            time.sleep(wait)
    raise last_err

def parse_jsonp(body):
    m = re.search(r'\((\{.*\})\)', body, re.S)
    return json.loads(m.group(1)) if m else json.loads(body)

# ---- XXTEA Enc ----
def xxtea_encrypt(text, key):
    if text == '':
        return ''
    def str_to_ints(s, append_len):
        c = len(s)
        v = []
        for i in range(0, c, 4):
            n = (ord(s[i]) if i < c else 0)
            n |= (ord(s[i+1]) if i+1 < c else 0) << 8
            n |= (ord(s[i+2]) if i+2 < c else 0) << 16
            n |= (ord(s[i+3]) if i+3 < c else 0) << 24
            v.append(n & 0xFFFFFFFF)
        if append_len:
            v.append(c)
        return v

    def ints_to_str(v):
        chars = []
        for val in v:
            chars.append(chr(val & 0xff))
            chars.append(chr((val >> 8) & 0xff))
            chars.append(chr((val >> 16) & 0xff))
            chars.append(chr((val >> 24) & 0xff))
        return ''.join(chars)

    v = str_to_ints(text, True)
    k = str_to_ints(key, False)
    if len(k) < 4:
        k.extend([0] * (4 - len(k)))
    n = len(v) - 1
    z, y = v[n], v[0]
    DELTA = 0x9E3779B9
    M = 0xFFFFFFFF
    q = 6 + 52 // (n + 1)
    d = 0
    while q > 0:
        d = (d + DELTA) & M
        e = (d >> 2) & 3
        for p in range(n):
            y = v[p + 1]
            m = ((z >> 5) ^ (y << 2)) & M
            m = (m + (((y >> 3) ^ ((z << 4) & M)) ^ (d ^ y))) & M
            m = (m + (k[(p & 3) ^ e] ^ z)) & M
            z = v[p] = (v[p] + m) & M
        p = n
        y = v[0]
        m = ((z >> 5) ^ (y << 2)) & M
        m = (m + (((y >> 3) ^ ((z << 4) & M)) ^ (d ^ y))) & M
        m = (m + (k[(p & 3) ^ e] ^ z)) & M
        z = v[n] = (v[n] + m) & M
        q -= 1
    return ints_to_str(v)

# ---- Custom Base64 ----
CUSTOM = 'LVoJPiCN2R8G90yg+hmFHuacZ1OWMnrsSTXkYpUq/3dlbfKwv6xztjI7DeBE45QA'
STD    = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
def custom_b64(data_bytes):
    std_b64 = base64.b64encode(data_bytes).decode('ascii')
    return std_b64.translate(str.maketrans(STD, CUSTOM))

# ---- Step 0: Get Client IP ----
try:
    page = http_get(f"{base_url}/srun_portal_pc?ac_id={ac_id}&theme=pro")
    m = re.search(r'ip\s*:\s*"([^"]+)"', page)
    client_ip = m.group(1) if m else ''
except Exception as e:
    print(f"[!] Failed to get client IP: {e}", file=sys.stderr)
    sys.exit(1)
if not client_ip:
    print("[!] Could not parse client IP from portal page", file=sys.stderr)
    sys.exit(1)
print(f"Client IP: {client_ip}")

# ---- Step 1: Get Challenge Token ----
cb = f"srun{int(time.time()*1000)}"
params = urllib.parse.urlencode({'username': username, 'ip': client_ip, 'callback': cb})
resp = parse_jsonp(http_get(f"{base_url}/cgi-bin/get_challenge?{params}"))
if resp.get('error') != 'ok':
    print(f"[!] Failed to get challenge token: {resp}", file=sys.stderr)
    sys.exit(1)
token = resp['challenge']
print(f"Token:       {token[:16]}...")

# ---- Step 2: HMAC-MD5(key=password, msg=token) ----
hmd5 = hmac.new(password.encode('utf-8'), token.encode('utf-8'), hashlib.md5).hexdigest()

# ---- Step 3: Encrypted user info (XXTEA + Custom Base64) ----
info_json = json.dumps({
    'username': username,
    'password': password,
    'ip': client_ip,
    'acid': ac_id,
    'enc_ver': 'srun_bx1'
}, separators=(',', ':'))
encrypted = xxtea_encrypt(info_json, token).encode('latin-1')
info = '{SRBX1}' + custom_b64(encrypted)

# ---- Step 4: Calculate chksum = SHA1(token + ...) ----
n_val, type_val = 200, 1
chk = (token + username + token + hmd5 + token + ac_id +
       token + client_ip + token + str(n_val) +
       token + str(type_val) + token + info)
chksum = hashlib.sha1(chk.encode('utf-8')).hexdigest()

# ---- Step 5: Post Login Request ----
login_params = urllib.parse.urlencode({
    'action': 'login',
    'username': username,
    'password': '{MD5}' + hmd5,
    'os': 'Linux',
    'name': 'Linux',
    'double_stack': '0',
    'chksum': chksum,
    'info': info,
    'ac_id': ac_id,
    'ip': client_ip,
    'n': str(n_val),
    'type': str(type_val),
    'callback': cb
})
result = parse_jsonp(http_get(f"{base_url}/cgi-bin/srun_portal?{login_params}"))

err = result.get('error', '')
suc = result.get('suc_msg', '')

if err == 'ok' and suc == 'login_ok':
    print(f"\n[OK] Login successfully!")
    print(f"  User: {result.get('username', username)}")
    print(f"  IP:   {result.get('client_ip', client_ip)}")
    msg = result.get('ploy_msg', '')
    if msg:
        print(f"  Message: {msg}")
elif err == 'ok' and 'already_online' in suc:
    print(f"\n[OK] This IP is already online")
elif 'already_online' in err:
    print(f"\n[OK] This IP is already online")
else:
    print(f"\n[FAIL] Failed to login: {result.get('error_msg', err)}", file=sys.stderr)
    sys.exit(1)
PYTHON_SCRIPT

# Remove IP route
ip route del 211.*.*.* via $GATEWAY dev $INTERFACE

Fill in the parameters and run the script

Route added, sleep 5s...
=== Srun Portal Login ===
Captive Protocol Server: 211.*.*.*
ac_id:      2
Username:     ***

Client IP: 10.150.196.77
Token:       ***...

[OK] Login successfully!
  User: ***
  IP:   10.150.196.77
  Message: E0000: Login is successful.

As you can see, the login succeeds. All that’s left is an init.d script that runs the login on every boot. You can copy it as many times as you have users.

If your school also uses SRun (深渊) software, this script may help you too.

Create the init.d script

vim /etc/init.d/srun_login
chmod +x /etc/init.d/srun_login

Put the following into the script

#!/bin/sh /etc/rc.common

USE_PROCD=1
START=95
STOP=15

start_service() {
    procd_open_instance
    procd_set_param command /root/srun_login/srun_login.sh
    procd_set_param respawn ${respawn_threshold:-3600} ${respawn_timeout:-5} ${respawn_retry:-5}
    procd_set_param stdout 1
    procd_set_param stderr 1
    procd_close_instance
}

stop_service() {
}

Enable it on boot and start it

/etc/init.d/srun_login enable
/etc/init.d/srun_login start

I have already written about link aggregation with mwan3; see here. I won’t repeat it in this article.

With that, every bit of configuration is done.


Conclusion

I’m not a professional, so please point out any mistakes or omissions. Thanks for reading!


If you enjoyed this, leave a comment~

Random Posts

Loading...