Translation

This post is also available in Simplified Chinese.

success

ZJU finally deployed WPA2 and 802.1X, so browser-based authentication is no longer necessary.

Recently, ZJUWLAN kept disconnecting for no apparent reason. The campus network required opening a browser to log in and then displayed a small “login successful” window—which i3wm tiled like an ordinary window. This was unbearable for a would-be perfectionist, so I wondered whether a script could perform the login directly and opened Chrome’s developer tools to investigate.

The login page is simply a form. Submitting it calls check1(frm) from js/srun_portal.js, whose source even includes helpful comments:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
function check1(frm) // pop-up authentication
{
    if (frm.username.value == "") {
        alert("The username cannot be empty; please enter a username");
        frm.username.focus();
        return false;
    }

    if (frm.password.value == "") {
        alert("The password cannot be empty; please enter a password");
        frm.password.focus();
        return false;
    }

    var res1 = "";

    var e = Encrypt(frm.password.value);
    var save_me = (frm.save_me.checked) ? 1 : 0;
    var d = "action=login&username=" + $("input[name='username']").val() +
        "&password=" + frm.password.value +
        "&ac_id=" + $("input[name='ac_id']").val() +
        "&user_ip=" + $("input[name='user_ip']").val() +
        "&nas_ip=" + $("input[name='nas_ip']").val() +
        "&user_mac=" + $("input[name='user_mac']").val() +
        "&save_me=" + save_me +
        "&ajax=1";
    // Submit the POST synchronously with AJAX
    $.ajax({
        type: "post",
        url: "/include/auth_action.php",
        action: 'login',
        data: d,
        async: false,
        success: function (res) {
            res1 = res;
        }
    });

    var p = /^login_ok,/;
    if (p.test(res1))// Authentication succeeded; open a small window
    {
        var arr = res1.split(",");
        if (arr[1] != "")// Store the cookie used for dual-stack authentication
        {
            setCookie("double_stack_login", arr[1]);
        }
        if (arr[2] != "")// Store the username/password cookie
        {
            setCookie("login", arr[2]);
        }
        window.open("user_logout.html", "", "width=400,height=300,left=0,top=0,resizable=1");// Open a small window
        setTimeout("redirect()", 2000); // Redirect to the requested URL
        //alert('Login successful');
        //window.location.href="http://202.117.1.166:8080/xjtu/index.do?method=mXJTU";
    }
    else {
        alert(res1); // Display the error message
    }

    return false;
}

The JavaScript contains little of substance. We only need to POST the form data to /include/auth_action.php; a response beginning with login_ok, indicates success. This is easy to implement in Python:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#!/usr/bin/env python3
import requests
from bs4 import BeautifulSoup
import sys

ZJU_WLAN = 'https://net.zju.edu.cn'
ZJU_INDEX = '/'
ZJU_AUTH = '/include/auth_action.php'

HTTP = {
    'Host': 'net.zju.edu.cn',
    'Connection': 'keep-alive',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134'
}

XHR = {
    'Host': 'net.zju.edu.cn',
    'Connection': 'keep-alive',
    'Origin': 'https://net.zju.edu.cn',
    'X-Requested-With': 'XMLHttpRequest',
    'Content-Type': 'application/x-www-form-urlencoded',
    'Referer': 'https://net.zju.edu.cn/srun_portal_pc.php?&ac_id=3',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134'
}

def main():
    if len(sys.argv) != 3:
        print('usage: %s <username> <password>')
        exit()
    username = sys.argv[1]
    password = sys.argv[2]
    zju_session = requests.session()
    index = zju_session.get(ZJU_WLAN+ZJU_INDEX, headers=HTTP)
    soup = BeautifulSoup(index.content, "html.parser")
    ac_id = soup.find('input', {'name': 'ac_id'})['value']
    user_ip = soup.find('input', {'name': 'user_ip'})['value']
    nas_ip = soup.find('input', {'name': 'nas_ip'})['value']
    user_mac = soup.find('input', {'name': 'user_mac'})['value']
    data = {
        'action': 'login',
        'username': username,
        'password': password,
        'ac_id': ac_id,
        'user_ip': user_ip,
        'nas_ip': nas_ip,
        'user_mac': user_mac,
        'save_me': 0,
        'ajax': 1
    }
    auth = zju_session.post(ZJU_WLAN+ZJU_AUTH, data=data, headers=XHR)
    result = auth.content.decode('utf8')
    if result[:9] == 'login_ok,':
        print('[+] Login succeed!')
    else:
        print('[-] Failed '+result)

if __name__ == '__main__':
    main()

Further testing showed that the initial request to https://net.zju.edu.cn/srun_portal_pc.php?&ac_id=3 served no purpose and did not even set a cookie. At least it redirected to HTTPS, showing that the network center had some basic security awareness.

In practice, the program only needs to POST the data string generated by the JavaScript. Since I was learning network programming, I reimplemented the login client in C; it accepts a username and password as arguments. The code is rough, so corrections are welcome. The variadic output function is based on Nginx’s ngx_log_stderr implementation, and I added a license for good measure:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
/*
 * Copyright (c) 2018, Nagi
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <stdio.h>
#include <netdb.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <openssl/ssl.h>

const char net_zju_host[] = "net.zju.edu.cn";
const char net_zju_auth_path[] = "/include/auth_action.php";
const char net_zju_ok[] = "login_ok,";
const char *user_agent = "Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134";

#define SUCCESS 0
#define INFO 1
#define ERROR 2

void output(int type, const char *fmt, ...)
{
    va_list args;
    switch (type) {
    case SUCCESS: printf("\e[32m[+] "); break;
    case ERROR: printf("\e[31m[-] "); break;
    default: printf("\e[33m[!] "); break;
    }
    va_start(args, fmt);
    vprintf(fmt, args);
    va_end(args);
    puts("\e[0m");
    if (type == ERROR) exit(1);
}

void init_ssl()
{
    SSL_load_error_strings();
    SSL_library_init();
}

SSL_CTX *create_ctx()
{
    SSL_CTX *ctx;
    int result;
    ctx = SSL_CTX_new(TLS_method());
    if (ctx == NULL) output(ERROR, "SSL_CTX_new() failed");
    result = SSL_CTX_set_min_proto_version(ctx, TLS1_VERSION);
    if (result == 0) {
        SSL_CTX_free(ctx);
        output(ERROR, "SSL_CTX_set_min_proto_version() failed");
    }
    return ctx;
}

SSL *connect_ssl(SSL_CTX *ctx, int fd)
{
    SSL *ssl;
    int result;
    ssl = SSL_new(ctx);
    if (ssl == NULL) output(ERROR, "SSL_new() failed");
    result = SSL_set_fd(ssl, fd);
    if (result != 1) output(ERROR, "SSL_set_fd() failed");
    result = SSL_connect(ssl);
    if (result != 1) output(ERROR, "SSL handshake failed");
    return ssl;
}

static const char urlencode_chars[] = {
    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,
    1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,
    1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,
    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};

int urlencode(const char *in, char *out)
{
    int i, printed = 0;
    unsigned char n1, n2;
    for (i = 0; in[i] != '\0'; i++) {
        if (urlencode_chars[(unsigned)in[i]] != 0) {
            n1 = ((unsigned char)in[i]) >> 4;
            n2 = ((unsigned char)in[i]) & 0xF;
            out[printed++] = '%';
            out[printed++] = n1 > 9 ? '7' + n1 : '0' + n1;
            out[printed++] = n2 > 9 ? '7' + n2 : '0' + n2;
        } else out[printed++] = in[i];
    }
    out[printed] = '\0';
    return printed;
}

int generate_post(char *buf, char *username, char *password)
{
    int printed = 0, content_len;
    char data_buf[256];
    printed += sprintf(buf + printed, "POST %s HTTP/1.1\r\nHost: %s\r\nConnection: close\r\nOrigin: https://%s\r\n", net_zju_auth_path, net_zju_host, net_zju_host);
    printed += sprintf(buf + printed, "X-Requested-With: XMLHttpRequest\r\nContent-Type: application/x-www-form-urlencoded\r\nReferer: https://%s/srun_portal_pc.php?&ac_id=3\r\n", net_zju_host);
    printed += sprintf(buf + printed, "Accept-Encoding: gzip, deflate, br\r\nAccept-Language: zh-CN,zh;q=0.9\r\nUser-Agent: %s\r\n", user_agent);
    memset(data_buf, 0, sizeof(data_buf));
    content_len = 0;
    content_len += sprintf(data_buf + content_len, "action=login&username=");
    content_len += urlencode(username, data_buf + content_len);
    content_len += sprintf(data_buf + content_len, "&password=");
    content_len += urlencode(password, data_buf + content_len);
    content_len += sprintf(data_buf + content_len, "&ac_id=3&user_ip=&nas_ip=&user_mac=&save_me=0&ajax=1");
    printed += sprintf(buf + printed, "Content-Length: %d\r\n\r\n%s", content_len, data_buf);
    return printed;
}

void send_post(SSL *ssl, char *buf, size_t size)
{
    size_t send = 0, this_send;
    int result;
    output(INFO, "Sending the POST request to server");
#ifdef DEBUG
    puts(buf);
#endif
    while (send < size) {
        result = SSL_write_ex(ssl, buf + send, size - send, &this_send);
        if (result != 1) output(ERROR, "SSL_write_ex() failed");
        send += this_send;
        output(INFO, "Sent %ld/%ld bytes", send, size);
    }
}

void recv_result(SSL *ssl, char *buf, size_t size)
{
    size_t recv = 0, this_recv;
    int result;
    output(INFO, "Receiving the reply");
    while (1) {
        result = SSL_read_ex(ssl, buf + recv, size - recv, &this_recv);
        if (result != 1) break;
        recv += this_recv;
        output(INFO, "%ld bytes receivied", recv);
    }
    buf[recv] = '\0';
#ifdef DEBUG
    puts(buf);
#endif
}

void final_ssl(SSL *ssl, SSL_CTX *ctx)
{
    SSL_shutdown(ssl);
    SSL_free(ssl);
    SSL_CTX_free(ctx);
}

int main(int argc, char *argv[], char *envp[])
{
    int auth_sock, result, post_size;
    struct sockaddr_in net_zju_addr;
    char post_buf[1024], recv_buf[1024], net_zju_ip[16];
    char *username, *password, *pos;
    struct hostent *resolve_result;
    SSL_CTX *ctx;
    SSL *ssl;

    if (argc != 3) {
        output(INFO, "Usage: %s <username> <password>", argv[0]);
        exit(1);
    }
    username = argv[1];
    password = argv[2];
    memset(post_buf, 0, sizeof(post_buf));
    init_ssl();
    ctx = create_ctx();
    resolve_result = gethostbyname(net_zju_host);
    if (resolve_result == NULL) output(ERROR, "gethostbyname() failed");
    if (resolve_result->h_addrtype != AF_INET) output(ERROR, "Can't get IPv4 address");
    net_zju_addr.sin_family = AF_INET;
    net_zju_addr.sin_port = htons(443);
    memcpy(&(net_zju_addr.sin_addr), resolve_result->h_addr_list[0], 4);
    inet_ntop(AF_INET, &(net_zju_addr.sin_addr), net_zju_ip, sizeof(net_zju_ip));
    output(INFO, "Using the IP address %s", net_zju_ip);
    auth_sock = socket(AF_INET, SOCK_STREAM, 0);
    if (auth_sock < 0) output(ERROR, "socket() failed");
    result = connect(auth_sock, (struct sockaddr *)&net_zju_addr, sizeof(struct sockaddr));
    if (result != 0) output(ERROR, "connect() failed");
    output(INFO, "Connected to net.zju.edu.cn");
    ssl = connect_ssl(ctx, auth_sock);
    post_size = generate_post(post_buf, username, password);
    send_post(ssl, post_buf, (size_t)post_size);
    recv_result(ssl, recv_buf, sizeof(recv_buf));
    pos = strstr(recv_buf, net_zju_ok);
    if (pos != NULL) output(SUCCESS, "Auth succeed");
    else {
        pos = strstr(recv_buf, "\r\n\r\n");
        if (pos != NULL) output(ERROR, "Auth failed, %s", pos + 4);
        else output(ERROR, "Auth failed");
    }
    final_ssl(ssl, ctx);
    return 0;
}
1
$ gcc -O2 -Wall zjuwlan.c -o zjuwlan -lcrypto -lssl