翻译

本文另有 英文版本。

success

浙三本终于有了 WPA2 和 802.1x,再也不需要打开网页登录了。

最近 ZJUWLAN 总是莫名掉线,而且三本的垃圾网还要专门打开浏览器登陆,登陆完成之后还弹出来一个登陆成功的小窗口,用 i3wm 的话小窗口还直接被平铺……对于我这种伪完美主义者&强迫症来说简直无可忍受,于是突发奇想,能不能直接用脚本登陆上去,于是打开了 Chrome 的开发者工具,仔细研究了一番。

登陆页面就是一个 form,点击提交的时候,会调用 js/srun_portal.js 里面的 check1(frm),代码如下,居然还贴心地给出了注释:

 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) //弹窗认证
{
    if (frm.username.value == "") {
        alert("用户名不能为空,请输入用户名");
        frm.username.focus();
        return false;
    }

    if (frm.password.value == "") {
        alert("密码不能为空,请输入密码");
        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";
    //这里要用AJAX同步提交POST
    $.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))//认证成功,弹出小窗口
    {
        var arr = res1.split(",");
        if (arr[1] != "")//写入用于双栈认证的COOKIE
        {
            setCookie("double_stack_login", arr[1]);
        }
        if (arr[2] != "")//写入用户名密码COOKIE
        {
            setCookie("login", arr[2]);
        }
        window.open("user_logout.html", "", "width=400,height=300,left=0,top=0,resizable=1");//弹出小窗口
        setTimeout("redirect()", 2000); //重定向到输入的网址
        //alert('登录成功');
        //window.location.href="http://202.117.1.166:8080/xjtu/index.do?method=mXJTU";
    }
    else {
        alert(res1); //提示错误信息
    }

    return false;
}

JS 基本没有什么内容,只需要把表单的内容 POST 到 /include/auth_action.php 这个路径就行了,如果返回的信息是 login_ok, 开头的话,就说明登陆成功了,直接 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()

后来试了试,发现最初访问 https://net.zju.edu.cn/srun_portal_pc.php?&ac_id=3 这一步并没有什么用处,连个 cookie 都没给设,真不愧是三本的垃圾网……不过好歹还给跳转到了 HTTPS,说明网络中心基本的安全意识还是有的 hhh。

所以实际上只需要直接把 JS 里生成的那串数据 POST 过去就行了,正好最近在学习网络编程,于是改用 C 实现了一个登陆程序,输入用户名和密码作为参数就能登陆。写的比较烂,如有不妥之处还请多多指教(output 函数参考了 Nginx 中对于 ngx_log_stderr 函数的可变长度参数的实现,装个逼加个许可证 hhh):

  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