最近由于做题需要,得在Windows下使用OpenSSL,以前一直是通过MSYS/MinGW来编译的,编译完成后可以得到libcrypto.alibssl.a两个静态库(也会生成dll但是我一般喜欢用静态的),用gcc编译代码的时候加上-lssl -lcrypto就能用。然而这些库只能用在MinGW里,没法用在Visual Studio里,而MinGW对Win32 API的支持是实在不敢称赞。所以今天研究了一下用VC编译的方法。

工具

  • Visual Studio 2017
  • OpenSSL 1.1.1a
  • ActivePerl 5.26.1

步骤

0x0.看了一下OpenSSL的说明,在Windows平台上的编译是通过nmake调用cl和link来自动编译的。在VS2017里选上C++的工作负载之后,就会安装上cl、link、nmake这些工具。可以参考微软的说明:How to get the command-line tools

0x1.通常这些工具的路径并不在$PATH里,而微软也提供了构建环境的脚本,只要在命令提示符里运行这些脚本就能配置好环境。脚本位于VS2017安装目录下的VC\Auxiliary\Build里。启动命令提示符后,运行vcvarsall.bat [目标架构],设置环境(亲测PowerShell没用,得进到cmd,这里选择了x64架构)。

0x2.进入OpenSSL的目录,用perl运行Configure脚本:perl .\Configure VC-WIN64A no-asm。(目标平台VC-WIN64A,由于我没装NASM所以用no-asm选项不使用汇编源码)

0x3.运行nmake编译,nmake test测试,之后等着就行了。(活这么久还是第一次见直接命令行用cl编译程序…)

0x4.编译完成后如果运行nmake install_sw,就会把产生的lib、dll、exe复制到安装目录(默认是%ProgramW6432%\OpenSSL),注意不要运行nmake install,否则会安装上一堆html的文档页面。

0x5.使用的时候,要设置项目的属性,在包含目录和库目录里分别加上OpenSSL安装路径下的include和lib文件夹。并在源代码中添加上对应的预处理指令

1
2
#pragma comment(lib, "libcrypto.lib")
#pragma comment(lib, "libssl.lib")

0x6.上面那样链接的是动态的dll库,运行的时候需要bin文件夹下的libcrypto-1_1-x64.dlllibssl-1_1-x64.dll,没有这两个dll程序就运行不了了。不知道为什么,OpenSSL编译产生了静态库libcrypto_static.liblibssl_static.lib,但是没有安装到lib下,手工把这两个文件复制过来,就可以通过下面的方法链接静态库了

1
2
#pragma comment(lib, "libcrypto_static.lib")
#pragma comment(lib, "libssl_static.lib")

0x7.最后吐槽一句:M$的软件真tnd难用 (除了VSCode)

ZJUWLAN autoconnect(Windows)

success

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

OpenSSL装好之后顺便重续了一下之前写的ZJUWLAN自动认证程序,Windows平台和Unix的差别主要在头文件上,以及使用socket之前要先启动一下,其他代码基本相同:

  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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
/*
 * 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 <string.h>
#include <WinSock2.h>
#include <Ws2tcpip.h>
#include <openssl/ssl.h>

#define DEBUG

#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "libcrypto_static.lib")
#pragma comment(lib, "libssl_static.lib")

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; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36";

#define T_SUCCESS 0
#define T_INFO 1
#define T_ERROR 2

void output(int type, const char *fmt, ...)
{
    va_list args;

    switch (type)
    {
    case T_SUCCESS:
        printf("[+] ");
        break;
    case T_ERROR:
        printf("[-] ");
        break;
    default:
        printf("[i] ");
        break;
    }
    va_start(args, fmt);
    vprintf(fmt, args);
    va_end(args);
    putchar('\n');
    if (type == T_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(T_ERROR, "SSL_CTX_new() failed");
    }
    result = SSL_CTX_set_min_proto_version(ctx, TLS1_VERSION);
    if (result == 0)
    {
        SSL_CTX_free(ctx);
        output(T_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(T_ERROR, "SSL_new() failed");
    }
    result = SSL_set_fd(ssl, fd);
    if (result != 1)
    {
        output(T_ERROR, "SSL_set_fd() failed");
    }
    result = SSL_connect(ssl);
    if (result != 1)
    {
        output(T_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;
    unsigned char n1, n2;

    printed = 0;
    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, content_len;
    char data_buf[256];

    printed = 0;
    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, this_send;
    int result;

    send = 0;
    output(T_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(T_ERROR, "SSL_write_ex() failed");
        }
        send += this_send;
        output(T_INFO, "Sent %ld/%ld bytes", send, size);
    }
    return;
}

void recv_result(SSL *ssl, char *buf, size_t size)
{
    size_t recv, this_recv;
    int result;

    recv = 0;
    output(T_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(T_INFO, "%ld bytes receivied", recv);
    }
    buf[recv] = '\0';
#ifdef DEBUG
    puts(buf);
#endif
    return;
}

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

int main(int argc, char *argv[], char *envp[])
{
    WORD myVersionRequest;
    WSADATA wsaData;
    SOCKET auth_sock;
    int result, post_size, err;
    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(T_INFO, "Usage: %s <username> <password>", argv[0]);
        exit(1);
    }
    username = "just-a-test-username";
    password = "just-a-test-password-0123456789abcdef";
    if (argc > 2)
    {
        password = argv[2];
    }
    if (argc > 1)
    {
        username = argv[1];
    }
    myVersionRequest = MAKEWORD(1, 1);
    err = WSAStartup(myVersionRequest, &wsaData);
    if (err)
    {
        output(T_ERROR, "WSAStartup() failed.");
    }
    memset(post_buf, 0, sizeof(post_buf));
    init_ssl();
    ctx = create_ctx();
    resolve_result = gethostbyname(net_zju_host);
    if (resolve_result == NULL)
    {
        output(T_ERROR, "gethostbyname() failed");
    }
    if (resolve_result->h_addrtype != AF_INET)
    {
        output(T_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(T_INFO, "Using the IP address %s", net_zju_ip);
    auth_sock = socket(AF_INET, SOCK_STREAM, 0);
    if (auth_sock < 0)
    {
        output(T_ERROR, "socket() failed");
    }
    result = connect(auth_sock, (struct sockaddr *)&net_zju_addr, sizeof(struct sockaddr));
    if (result != 0)
    {
        output(T_ERROR, "connect() failed");
    }
    output(T_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(T_SUCCESS, "Auth succeed");
    }
    else
    {
        pos = strstr(recv_buf, "\r\n\r\n");
        if (pos != NULL)
        {
            output(T_ERROR, "Auth failed, %s", pos + 4);
        }
        else
        {
            output(T_ERROR, "Auth failed");
        }
    }
    final_ssl(ssl, ctx);
    return 0;
}

估计也没几个人电脑上有OpenSSL…所以我上传了一个编译完的程序,通过命令行传递用户名和密码运行。也可以在手工修改这个程序.rdata里面username和password的默认值之后,直接双击运行。