Translation

This post is also available in Simplified Chinese.

I recently needed OpenSSL on Windows for a challenge. I had always built it through MSYS/MinGW, which produces the static libraries libcrypto.a and libssl.a (as well as DLLs, although I generally prefer static linking). Programs compiled with GCC can use them with -lssl -lcrypto. These libraries only work with MinGW, however, and cannot be used by Visual Studio; MinGW’s Win32 API support is hardly praiseworthy either. I therefore investigated how to build OpenSSL with Visual C++.

Tools

  • Visual Studio 2017
  • OpenSSL 1.1.1a
  • ActivePerl 5.26.1

Procedure

0x0. According to the OpenSSL documentation, Windows builds use nmake to invoke cl and link. Installing Visual Studio 2017’s C++ workload provides all three tools. See Microsoft’s How to get the command-line tools.

0x1. These tools are normally absent from $PATH. Microsoft supplies scripts that configure the build environment when run from Command Prompt. They are located under VC\Auxiliary\Build in the VS2017 installation directory. Open cmd and run vcvarsall.bat [target architecture]; PowerShell did not work in my testing. I selected x64.

Configuring the build environment with vcvarsall.bat

0x2. Enter the OpenSSL directory and run its Configure script with Perl: perl .\Configure VC-WIN64A no-asm. The target is VC-WIN64A; because I did not have NASM installed, no-asm disables assembly sources.

0x3. Run nmake to compile and nmake test to test, then wait. This was the first time I had seen cl used directly from the command line.

Building OpenSSL with nmake

0x4. After compilation, nmake install_sw copies the generated libraries, DLLs, and executables into the installation directory, which defaults to %ProgramW6432%\OpenSSL. Do not run nmake install unless you also want a large collection of HTML documentation installed.

0x5. To use OpenSSL, add its include and lib directories to the project’s include and library paths, then add the corresponding linker directives to the source code.

OpenSSL project properties in Visual Studio

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

0x6. The directives above link against the dynamic libraries, so the program needs libcrypto-1_1-x64.dll and libssl-1_1-x64.dll from the bin directory at runtime. OpenSSL also produces libcrypto_static.lib and libssl_static.lib, but for some reason does not install them under lib. Copy them there manually and link the static libraries as follows.

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

0x7. One final complaint: Microsoft’s software is incredibly awkward to use—except VS Code.

ZJUWLAN autoconnect(Windows)

success

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

After installing OpenSSL, I updated my earlier ZJUWLAN automatic-authentication program. The Windows version mainly differs from Unix in its headers and the need to initialize Winsock before using sockets; the rest of the code is essentially identical:

  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
/*
 * 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 = 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(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);
    }
}

void recv_result(SSL *ssl, char *buf, size_t size)
{
    size_t recv = 0, this_recv;
    int result;
    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
}

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[])
{
    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;
}

Since few people are likely to have OpenSSL installed on their Windows machines, I uploaded a compiled program that accepts the username and password as command-line arguments. Alternatively, modify the default username and password values in the executable’s .rdata section and launch it directly.