1 module requests.ssl_adapter;
2 
3 import std.stdio;
4 import std.string;
5 import std.format;
6 import std.typecons;
7 import core.stdc.stdlib;
8 import core.sys.posix.dlfcn;
9 import std.experimental.logger;
10 
11 version(Windows) {
12     import core.sys.windows.windows;
13     alias DLSYM = GetProcAddress;
14 } else {
15     alias DLSYM = dlsym;
16 }
17 
18 /*
19  * /usr/include/openssl/tls1.h:# define TLS_ANY_VERSION 0x10000
20  */
21 
22 immutable int TLS_ANY_VERSION = 0x10000;
23 immutable int TLS1_VERSION = 0x0301;
24 immutable int TLS1_2_VERSION = 0x0303;
25 
26 struct SSL {};
27 struct SSL_CTX {};
28 struct SSL_METHOD {};
29 
30 //
31 // N  - function name, R - return type, A - args
32 //
33 string SSL_Function_decl(string N, R, A...)() {
34     string F = "extern (C) @nogc nothrow %s function %s adapter_%s;".format(R.stringof, A.stringof, N);
35     return F;
36 }
37 string SSL_Function_set_i(string N, R, A...)() {
38     string F = "openssl.adapter_%s = cast(typeof(openssl.adapter_%s))DLSYM(cast(void*)openssl._libssl, \"%s\");".format(N, N, N);
39     return F;
40 }
41 string CRYPTO_Function_set_i(string N, R, A...)() {
42     string F = "openssl.adapter_%s = cast(typeof(openssl.adapter_%s))DLSYM(cast(void*)openssl._libcrypto, \"%s\");".format(N, N, N);
43     return F;
44 }
45 
46 private alias Version = Tuple!(int, "major", int, "minor");
47 
48 immutable static OpenSSL openssl;
49 
50 static this() {
51     if ( openssl._libssl !is null ) {
52         return;
53     }
54     version(OSX) {
55         openssl._libssl = cast(typeof(openssl._libssl))dlopen("libssl.dylib", RTLD_LAZY);
56         openssl._libcrypto = cast(typeof(openssl._libcrypto))dlopen("libcrypto.dylib", RTLD_LAZY);
57     } else
58     version(linux) {
59         immutable string[] libsslname = [
60             "libssl.so",
61             "libssl.so.1.1",
62             "libssl.so.1.0.2",
63             "libssl.so.1.0.1",
64             "libssl.so.1.0.0"
65         ];
66         foreach(lib; libsslname) {
67             openssl._libssl = cast(typeof(openssl._libssl))dlopen(lib.ptr, RTLD_LAZY);
68             if ( openssl._libssl !is null ) {
69                 debug(requests) tracef("will use %s".format(lib));
70                 break;
71             }
72         }
73         immutable string[] libcryptoname = [
74             "libcrypto.so",
75             "libcrypto.so.1.1",
76             "libcrypto.so.1.0.2",
77             "libcrypto.so.1.0.1",
78             "libcrypto.so.1.0.0"
79         ];
80         foreach(lib; libcryptoname) {
81             openssl._libcrypto = cast(typeof(openssl._libcrypto))dlopen(lib.ptr, RTLD_LAZY);
82             if ( openssl._libcrypto !is null ) {
83                 debug(requests) tracef("will use %s".format(lib));
84                 break;
85             }
86         }
87     } else
88     version(Windows) {
89         openssl._libssl = cast(typeof(openssl._libssl))LoadLibrary("libssl32.dll");
90         openssl._libcrypto = cast(typeof(openssl._libcrypto))LoadLibrary("libeay32.dll");
91     } else {
92         throw new Exception("loading openssl: unsupported system");
93     }
94     if ( openssl._libssl is null ) {
95         error("warning: failed to load libssl - first access over https will fail");
96         return;
97     }
98     if ( openssl._libcrypto is null ) {
99         error("warning: failed to load libcrypto - first access over https will fail");
100         return;
101     }
102     openssl._ver = openssl.OpenSSL_version_detect();
103 
104     mixin(SSL_Function_set_i!("SSL_library_init", int));
105     mixin(CRYPTO_Function_set_i!("OpenSSL_add_all_ciphers", void));
106     mixin(CRYPTO_Function_set_i!("OpenSSL_add_all_digests", void));
107     mixin(SSL_Function_set_i!("SSL_load_error_strings", void));
108 
109     mixin(SSL_Function_set_i!("OPENSSL_init_ssl", int, ulong, void*));
110     mixin(CRYPTO_Function_set_i!("OPENSSL_init_crypto", int, ulong, void*));
111 
112     mixin(SSL_Function_set_i!("TLSv1_client_method", SSL_METHOD*));
113     mixin(SSL_Function_set_i!("TLSv1_2_client_method", SSL_METHOD*));
114     mixin(SSL_Function_set_i!("TLS_method", SSL_METHOD*));
115     mixin(SSL_Function_set_i!("SSLv23_client_method", SSL_METHOD*));
116     mixin(SSL_Function_set_i!("SSL_CTX_new", SSL_CTX*, SSL_METHOD*));
117     mixin(SSL_Function_set_i!("SSL_CTX_set_default_verify_paths", int, SSL_CTX*));
118     mixin(SSL_Function_set_i!("SSL_CTX_load_verify_locations", int, SSL_CTX*, char*, char*));
119     mixin(SSL_Function_set_i!("SSL_CTX_set_verify", void, SSL_CTX*, int, void*));
120     mixin(SSL_Function_set_i!("SSL_CTX_use_PrivateKey_file", int, SSL_CTX*, const char*, int));
121     mixin(SSL_Function_set_i!("SSL_CTX_use_certificate_file", int, SSL_CTX*, const char*, int));
122     mixin(SSL_Function_set_i!("SSL_CTX_set_cipher_list", int, SSL_CTX*, const char*));
123     mixin(SSL_Function_set_i!("SSL_CTX_ctrl", long, SSL_CTX*, int, long, void*));
124     mixin(SSL_Function_set_i!("SSL_new", SSL*, SSL_CTX*));
125     mixin(SSL_Function_set_i!("SSL_set_fd", int, SSL*, int));
126     mixin(SSL_Function_set_i!("SSL_connect", int, SSL*));
127     mixin(SSL_Function_set_i!("SSL_write", int, SSL*, const void*, int));
128     mixin(SSL_Function_set_i!("SSL_read", int, SSL*, void*, int));
129     mixin(SSL_Function_set_i!("SSL_free", void, SSL*));
130     mixin(SSL_Function_set_i!("SSL_CTX_free", void, SSL_CTX*));
131     mixin(SSL_Function_set_i!("SSL_get_error", int, SSL*, int));
132     mixin(SSL_Function_set_i!("SSL_ctrl", long, SSL*, int, long, void*));
133     mixin(CRYPTO_Function_set_i!("ERR_reason_error_string", char*, ulong));
134     mixin(CRYPTO_Function_set_i!("ERR_get_error", ulong));
135 
136     void delegate()[Version] init_matrix;
137     init_matrix[Version(1,0)] = &openssl.init1_0;
138     init_matrix[Version(1,1)] = &openssl.init1_1;
139     auto init = init_matrix.get(openssl._ver, null);
140     if ( init is null ) {
141         throw new Exception("loading openssl: unknown version for init");
142     }
143     init();
144 }
145 
146 struct OpenSSL {
147 
148     private {
149         Version         _ver;
150         void*           _libssl;
151         void*           _libcrypto;
152 
153         // openssl 1.0.x init functions
154         mixin(SSL_Function_decl!("SSL_library_init", int));
155         mixin(SSL_Function_decl!("OpenSSL_add_all_ciphers", void));
156         mixin(SSL_Function_decl!("OpenSSL_add_all_digests", void));
157         mixin(SSL_Function_decl!("SSL_load_error_strings", void));
158 
159         // openssl 1.1.x init functions
160         mixin(SSL_Function_decl!("OPENSSL_init_ssl", int, ulong, void*));
161         mixin(SSL_Function_decl!("OPENSSL_init_crypto", int, ulong, void*));
162 
163         // all other functions
164         mixin(SSL_Function_decl!("TLSv1_client_method", SSL_METHOD*));
165         mixin(SSL_Function_decl!("TLSv1_2_client_method", SSL_METHOD*));
166         mixin(SSL_Function_decl!("TLS_method", SSL_METHOD*));
167         mixin(SSL_Function_decl!("SSLv23_client_method", SSL_METHOD*));
168         mixin(SSL_Function_decl!("SSL_CTX_new", SSL_CTX*, SSL_METHOD*));
169         mixin(SSL_Function_decl!("SSL_CTX_set_default_verify_paths", int, SSL_CTX*));
170         mixin(SSL_Function_decl!("SSL_CTX_load_verify_locations", int, SSL_CTX*, char*, char*));
171         mixin(SSL_Function_decl!("SSL_CTX_set_verify", void, SSL_CTX*, int, void*));
172         mixin(SSL_Function_decl!("SSL_CTX_use_PrivateKey_file", int, SSL_CTX*, const char*, int));
173         mixin(SSL_Function_decl!("SSL_CTX_use_certificate_file", int, SSL_CTX*, const char*, int));
174         mixin(SSL_Function_decl!("SSL_CTX_set_cipher_list", int, SSL_CTX*, const char*));
175         mixin(SSL_Function_decl!("SSL_CTX_ctrl", long, SSL_CTX*, int, long, void*));
176         mixin(SSL_Function_decl!("SSL_new", SSL*, SSL_CTX*));
177         mixin(SSL_Function_decl!("SSL_set_fd", int, SSL*, int));
178         mixin(SSL_Function_decl!("SSL_connect", int, SSL*));
179         mixin(SSL_Function_decl!("SSL_write", int, SSL*, const void*, int));
180         mixin(SSL_Function_decl!("SSL_read", int, SSL*, void*, int));
181         mixin(SSL_Function_decl!("SSL_free", void, SSL*));
182         mixin(SSL_Function_decl!("SSL_CTX_free", void, SSL_CTX*));
183         mixin(SSL_Function_decl!("SSL_get_error", int, SSL*, int));
184         mixin(SSL_Function_decl!("SSL_ctrl", long, SSL*, int, long, void*));
185         mixin(SSL_Function_decl!("ERR_reason_error_string", char*, ulong));
186         mixin(SSL_Function_decl!("ERR_get_error", ulong));
187     }
188 
189     Version reportVersion() const @nogc nothrow pure {
190         return _ver;
191     };
192 
193     private Version OpenSSL_version_detect() const {
194         ulong function() OpenSSL_version_num = cast(ulong function())DLSYM(cast(void*)_libcrypto, "OpenSSL_version_num".ptr);
195         if ( OpenSSL_version_num ) {
196             auto v = OpenSSL_version_num() & 0xffffffff;
197             return Version((v>>>20) & 0xff, (v>>>28) & 0xff);
198         }
199         return Version(1, 0);
200     }
201 
202     private void init1_0() const {
203         adapter_SSL_library_init();
204         adapter_OpenSSL_add_all_ciphers();
205         adapter_OpenSSL_add_all_digests();
206         adapter_SSL_load_error_strings();
207     }
208     private void init1_1() const {
209         /**
210         Standard initialisation options
211 
212         #define OPENSSL_INIT_LOAD_SSL_STRINGS       0x00200000L
213 
214         # define OPENSSL_INIT_LOAD_CRYPTO_STRINGS    0x00000002L
215         # define OPENSSL_INIT_ADD_ALL_CIPHERS        0x00000004L
216         # define OPENSSL_INIT_ADD_ALL_DIGESTS        0x00000008L
217         **/
218         enum OPENSSL_INIT_LOAD_SSL_STRINGS = 0x00200000L;
219         enum OPENSSL_INIT_LOAD_CRYPTO_STRINGS = 0x00000002L;
220         enum OPENSSL_INIT_ADD_ALL_CIPHERS = 0x00000004L;
221         enum OPENSSL_INIT_ADD_ALL_DIGESTS = 0x00000008L;
222         adapter_OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS, null);
223         adapter_OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS | OPENSSL_INIT_ADD_ALL_DIGESTS | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, null);
224     }
225 
226     SSL_METHOD* TLSv1_client_method() const {
227         if ( adapter_TLSv1_client_method is null ) {
228             throw new Exception("openssl not initialized - is it installed?");
229         }
230         return adapter_TLSv1_client_method();
231     }
232     SSL_METHOD* TLSv1_2_client_method() const {
233         if ( adapter_TLSv1_2_client_method is null ) {
234             throw new Exception("openssl not initialized - is it installed?");
235         }
236         return adapter_TLSv1_2_client_method();
237     }
238     SSL_METHOD* SSLv23_client_method() const {
239         if ( adapter_SSLv23_client_method is null ) {
240             throw new Exception("can't complete call to SSLv23_client_method");
241         }
242         return adapter_SSLv23_client_method();
243     }
244     SSL_METHOD* TLS_method() const {
245         if ( adapter_TLS_method !is null ) {
246             return adapter_TLS_method();
247         }
248         if ( adapter_SSLv23_client_method !is null ) {
249             return adapter_SSLv23_client_method();
250         }
251         throw new Exception("can't complete call to TLS_method");
252     }
253     SSL_CTX* SSL_CTX_new(SSL_METHOD* method) const {
254         if ( adapter_SSL_CTX_new is null ) {
255             throw new Exception("openssl not initialized - is it installed?");
256         }
257         return adapter_SSL_CTX_new(method);
258     }
259     int SSL_CTX_set_default_verify_paths(SSL_CTX* ctx) const @nogc nothrow {
260         return adapter_SSL_CTX_set_default_verify_paths(ctx);
261     }
262     int SSL_CTX_load_verify_locations(SSL_CTX* ctx, char* CAFile, char* CAPath) const @nogc nothrow {
263         return adapter_SSL_CTX_load_verify_locations(ctx, CAFile, CAPath);
264     }
265     void SSL_CTX_set_verify(SSL_CTX* ctx, int mode, void* callback) const @nogc nothrow {
266         adapter_SSL_CTX_set_verify(ctx, mode, callback);
267     }
268     int SSL_CTX_use_PrivateKey_file(SSL_CTX* ctx, const char* file, int type) const @nogc nothrow {
269         return adapter_SSL_CTX_use_PrivateKey_file(ctx, file, type);
270     }
271     int SSL_CTX_use_certificate_file(SSL_CTX* ctx, const char* file, int type) const @nogc nothrow {
272         return adapter_SSL_CTX_use_certificate_file(ctx, file, type);
273     }
274     int SSL_CTX_set_cipher_list(SSL_CTX* ssl_ctx, const char* c) const @nogc nothrow {
275         return adapter_SSL_CTX_set_cipher_list(ssl_ctx, c);
276     }
277     /*
278      *
279      * # define SSL_CTRL_SET_MIN_PROTO_VERSION          123
280      * # define SSL_CTRL_SET_MAX_PROTO_VERSION          124
281     */
282     enum int SSL_CTRL_SET_MIN_PROTO_VERSION = 123;
283     enum int SSL_CTRL_SET_MAX_PROTO_VERSION = 124;
284     int SSL_CTX_set_min_proto_version(SSL_CTX* ctx, int v) const @nogc nothrow {
285         int r = cast(int)adapter_SSL_CTX_ctrl(ctx, SSL_CTRL_SET_MIN_PROTO_VERSION, cast(long)v, null);
286         return r;
287     }
288     int SSL_CTX_set_max_proto_version(SSL_CTX* ctx, int v) const @nogc nothrow {
289         int r = cast(int)adapter_SSL_CTX_ctrl(ctx, SSL_CTRL_SET_MAX_PROTO_VERSION, cast(long)v, null);
290         return r;
291     }
292     SSL* SSL_new(SSL_CTX* ctx) const @nogc nothrow {
293         return adapter_SSL_new(ctx);
294     }
295     int SSL_set_fd(SSL* ssl, int fd) const @nogc nothrow {
296         return adapter_SSL_set_fd(ssl, fd);
297     }
298     int SSL_connect(SSL* ssl) const @nogc nothrow {
299         return adapter_SSL_connect(ssl);
300     }
301     int SSL_read(SSL* ssl, void *b, int n) const @nogc nothrow {
302         return adapter_SSL_read(ssl, b, n);
303     }
304     int SSL_write(SSL* ssl, const void *b, int n) const @nogc nothrow {
305         return adapter_SSL_write(ssl, b, n);
306     }
307     void SSL_free(SSL* ssl) const @nogc nothrow @trusted {
308         adapter_SSL_free(ssl);
309     }
310     void SSL_CTX_free(SSL_CTX* ctx) const @nogc nothrow @trusted {
311         adapter_SSL_CTX_free(ctx);
312     }
313     int SSL_get_error(SSL* ssl, int err) const @nogc nothrow {
314         return adapter_SSL_get_error(ssl, err);
315     }
316     long SSL_set_tlsext_host_name(SSL* ssl, const char* host) const @nogc nothrow {
317         enum int SSL_CTRL_SET_TLSEXT_HOSTNAME = 55;
318         enum long TLSEXT_NAMETYPE_host_name = 0;
319         return adapter_SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME,TLSEXT_NAMETYPE_host_name, cast(void*)host);
320     }
321     char* ERR_reason_error_string(ulong code) const @nogc nothrow {
322         return adapter_ERR_reason_error_string(code);
323     }
324     ulong ERR_get_error() const @nogc nothrow {
325         return adapter_ERR_get_error();
326     }
327 }
328 /*
329 int main() {
330     import std.socket;
331 
332     auto v = openssl.reportVersion();
333     writefln("openSSL v.%s.%s", v.major, v.minor);
334     openssl.SSL_library_init();
335     writeln("InitSSL - ok");
336     SSL_CTX* ctx = openssl.SSL_CTX_new(openssl.TLSv1_client_method());
337     writefln("SSL_CTX_new = %x", ctx);
338     int r = openssl.adapter_SSL_CTX_set_default_verify_paths(ctx);
339     writefln("SSL_CTX_set_default_verify_paths = %d(%s)", r, r==1?"ok":"fail");
340     r = openssl.adapter_SSL_CTX_load_verify_locations(ctx, cast(char*)null, cast(char*)null);
341     writefln("SSL_CTX_load_verify_locations - ok");
342     openssl.SSL_CTX_set_verify(ctx, 0, null);
343     writefln("SSL_CTX_set_verify - ok");
344     //r = openssl.SSL_CTX_use_PrivateKey_file(ctx, null, 0);
345     //writefln("SSL_CTX_use_PrivateKey_file = %d(%s)", r, r==1?"ok":"fail");
346     //r = openssl.SSL_CTX_use_certificate_file(ctx, cast(char*), 0);
347     //writefln("SSL_CTX_use_certificate_file = %d(%s)", r, r==1?"ok":"fail");
348     SSL* ssl = openssl.SSL_new(ctx);
349     writefln("SSL_new = %x", ssl);
350     auto s = new Socket(AddressFamily.INET, SocketType.STREAM, ProtocolType.TCP);
351     Address[] a = getAddress("ns.od.ua", 443);
352     writeln(a[0]);
353     s.connect(a[0]);
354     r = openssl.SSL_set_fd(ssl, s.handle);
355     writefln("SSL_set_fd = %d(%s)", r, r==1?"ok":"fail");
356     r = openssl.SSL_connect(ssl);
357     writefln("SSL_connect = %d(%s)", r, r==1?"ok":"fail");
358     if ( r < 0 ) {
359         writefln("code: %d", openssl.SSL_get_error(ssl, r));
360     }
361     string req = "GET / HTTP/1.0\n\n";
362     r = openssl.SSL_write(ssl, cast(void*)req.ptr, cast(int)req.length);
363     writefln("SSL_write = %d", r);
364     do {
365         ubyte[]  resp = new ubyte[](1024);
366         r = openssl.SSL_read(ssl, cast(void*)resp.ptr, cast(int)1024);
367         writefln("SSL_read = %d", r);
368         if ( r > 0 ) {
369             writeln(cast(string)resp);
370         }
371     } while(r > 0);
372     openssl.SSL_free(ssl);
373     openssl.SSL_CTX_free(ctx);
374     s.close();
375     return 0;
376 }
377 */