1 /** 2 * OpenSSL support. 3 * 4 * License: 5 * This Source Code Form is subject to the terms of 6 * the Mozilla Public License, v. 2.0. If a copy of 7 * the MPL was not distributed with this file, You 8 * can obtain one at http://mozilla.org/MPL/2.0/. 9 * 10 * Authors: 11 * Vladimir Panteleev <vladimir@thecybershadow.net> 12 */ 13 14 module ae.net.ssl.openssl; 15 16 import ae.net.asockets; 17 import ae.net.ssl; 18 import ae.utils.exception : CaughtException; 19 import ae.utils.meta : enumLength; 20 import ae.utils.text; 21 22 import std.conv : to; 23 import std.exception : enforce, errnoEnforce; 24 import std.functional; 25 import std.socket; 26 import std.string; 27 28 //import deimos.openssl.rand; 29 import deimos.openssl.ssl; 30 import deimos.openssl.err; 31 32 version(Win64) 33 { 34 pragma(lib, "ssleay32"); 35 pragma(lib, "libeay32"); 36 } 37 else 38 { 39 pragma(lib, "ssl"); 40 version(Windows) 41 { pragma(lib, "eay"); } 42 else 43 { pragma(lib, "crypto"); } 44 } 45 46 debug(OPENSSL) import std.stdio : stderr; 47 48 // *************************************************************************** 49 50 shared static this() 51 { 52 SSL_load_error_strings(); 53 SSL_library_init(); 54 OpenSSL_add_all_algorithms(); 55 } 56 57 // *************************************************************************** 58 59 class OpenSSLProvider : SSLProvider 60 { 61 override SSLContext createContext(SSLContext.Kind kind) 62 { 63 return new OpenSSLContext(kind); 64 } 65 66 override SSLAdapter createAdapter(SSLContext context, IConnection next) 67 { 68 auto ctx = cast(OpenSSLContext)context; 69 assert(ctx, "Not an OpenSSLContext"); 70 return new OpenSSLAdapter(ctx, next); 71 } 72 } 73 74 class OpenSSLContext : SSLContext 75 { 76 SSL_CTX* sslCtx; 77 Kind kind; 78 79 this(Kind kind) 80 { 81 this.kind = kind; 82 83 const(SSL_METHOD)* method; 84 85 final switch (kind) 86 { 87 case Kind.client: 88 method = SSLv23_client_method().sslEnforce(); 89 break; 90 case Kind.server: 91 method = SSLv23_server_method().sslEnforce(); 92 break; 93 } 94 sslCtx = SSL_CTX_new(method).sslEnforce(); 95 } 96 97 override void setCipherList(string[] ciphers) 98 { 99 SSL_CTX_set_cipher_list(sslCtx, ciphers.join(":").toStringz()).sslEnforce(); 100 } 101 102 override void enableDH(int bits) 103 { 104 typeof(&get_rfc3526_prime_2048) func; 105 106 switch (bits) 107 { 108 case 1536: func = &get_rfc3526_prime_1536; break; 109 case 2048: func = &get_rfc3526_prime_2048; break; 110 case 3072: func = &get_rfc3526_prime_3072; break; 111 case 4096: func = &get_rfc3526_prime_4096; break; 112 case 6144: func = &get_rfc3526_prime_6144; break; 113 case 8192: func = &get_rfc3526_prime_8192; break; 114 default: assert(false, "No RFC3526 prime available for %d bits".format(bits)); 115 } 116 117 DH* dh; 118 scope(exit) DH_free(dh); 119 120 dh = DH_new().sslEnforce(); 121 dh.p = func(null).sslEnforce(); 122 ubyte gen = 2; 123 dh.g = BN_bin2bn(&gen, gen.sizeof, null); 124 SSL_CTX_set_tmp_dh(sslCtx, dh).sslEnforce(); 125 } 126 127 override void enableECDH() 128 { 129 auto ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1).sslEnforce(); 130 scope(exit) EC_KEY_free(ecdh); 131 SSL_CTX_set_tmp_ecdh(sslCtx, ecdh).sslEnforce(); 132 } 133 134 override void setCertificate(string path) 135 { 136 SSL_CTX_use_certificate_chain_file(sslCtx, toStringz(path)) 137 .sslEnforce("Failed to load certificate file " ~ path); 138 } 139 140 override void setPrivateKey(string path) 141 { 142 SSL_CTX_use_PrivateKey_file(sslCtx, toStringz(path), SSL_FILETYPE_PEM) 143 .sslEnforce("Failed to load private key file " ~ path); 144 } 145 146 override void setPeerVerify(Verify verify) 147 { 148 static const int[enumLength!Verify] modes = 149 [ 150 SSL_VERIFY_NONE, 151 SSL_VERIFY_PEER, 152 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, 153 ]; 154 SSL_CTX_set_verify(sslCtx, modes[verify], null); 155 } 156 157 override void setPeerRootCertificate(string path) 158 { 159 auto szPath = toStringz(path); 160 SSL_CTX_load_verify_locations(sslCtx, szPath, null).sslEnforce(); 161 162 if (kind == Kind.server) 163 { 164 auto list = SSL_load_client_CA_file(szPath).sslEnforce(); 165 SSL_CTX_set_client_CA_list(sslCtx, list); 166 } 167 } 168 169 override void setFlags(int flags) 170 { 171 SSL_CTX_set_options(sslCtx, flags).sslEnforce(); 172 } 173 } 174 175 static this() 176 { 177 ssl = new OpenSSLProvider(); 178 } 179 180 // *************************************************************************** 181 182 class OpenSSLAdapter : SSLAdapter 183 { 184 SSL* sslHandle; 185 OpenSSLContext context; 186 187 this(OpenSSLContext context, IConnection next) 188 { 189 this.context = context; 190 super(next); 191 192 sslHandle = sslEnforce(SSL_new(context.sslCtx)); 193 SSL_set_bio(sslHandle, r.bio, w.bio); 194 195 if (next.state == ConnectionState.connected) 196 initialize(); 197 } 198 199 override void onConnect() 200 { 201 initialize(); 202 super.onConnect(); 203 } 204 205 private final void initialize() 206 { 207 final switch (context.kind) 208 { 209 case OpenSSLContext.Kind.client: SSL_connect(sslHandle).sslEnforce(); break; 210 case OpenSSLContext.Kind.server: SSL_accept (sslHandle).sslEnforce(); break; 211 } 212 } 213 214 MemoryBIO r; // BIO for incoming ciphertext 215 MemoryBIO w; // BIO for outgoing ciphertext 216 217 override void onReadData(Data data) 218 { 219 debug(OPENSSL) stderr.writefln("OpenSSL: Got %d incoming bytes from network", data.length); 220 221 if (next.state == ConnectionState.disconnecting) 222 return; 223 224 assert(r.data.length == 0, "Would clobber data"); 225 r.set(data.contents); 226 debug(OPENSSL) stderr.writefln("OpenSSL: r.data.length = %d", r.data.length); 227 228 try 229 { 230 if (queue.length) 231 flushQueue(); 232 233 while (true) 234 { 235 static ubyte[4096] buf; 236 debug(OPENSSL) auto oldLength = r.data.length; 237 auto result = SSL_read(sslHandle, buf.ptr, buf.length); 238 debug(OPENSSL) stderr.writefln("OpenSSL: SSL_read ate %d bytes and spat out %d bytes", oldLength - r.data.length, result); 239 flushWritten(); 240 if (result > 0) 241 super.onReadData(Data(buf[0..result])); 242 else 243 { 244 sslError(result, "SSL_read"); 245 break; 246 } 247 } 248 enforce(r.data.length == 0, "SSL did not consume all read data"); 249 } 250 catch (CaughtException e) 251 { 252 debug(OPENSSL) stderr.writeln("Error while processing incoming data: " ~ e.msg); 253 disconnect(e.msg, DisconnectType.error); 254 } 255 } 256 257 Data[] queue; /// Queue of outgoing plaintext 258 259 override void send(Data[] data, int priority = DEFAULT_PRIORITY) 260 { 261 foreach (datum; data) 262 if (datum.length) 263 { 264 debug(OPENSSL) stderr.writefln("OpenSSL: Got %d outgoing bytes from program", datum.length); 265 queue ~= datum; 266 } 267 268 flushQueue(); 269 } 270 271 /// Encrypt outgoing plaintext 272 /// queue -> SSL_write -> w 273 void flushQueue() 274 { 275 while (queue.length) 276 { 277 debug(OPENSSL) auto oldLength = w.data.length; 278 auto result = SSL_write(sslHandle, queue[0].ptr, queue[0].length.to!int); 279 debug(OPENSSL) stderr.writefln("OpenSSL: SSL_write ate %d bytes and spat out %d bytes", queue[0].length, w.data.length - oldLength); 280 if (result > 0) 281 { 282 // "SSL_write() will only return with success, when the 283 // complete contents of buf of length num has been written." 284 queue = queue[1..$]; 285 } 286 else 287 { 288 sslError(result, "SSL_write"); 289 break; 290 } 291 } 292 flushWritten(); 293 } 294 295 /// Flush any accumulated outgoing ciphertext to the network 296 void flushWritten() 297 { 298 if (w.data.length) 299 { 300 next.send([Data(w.data)]); 301 w.clear(); 302 } 303 } 304 305 override void disconnect(string reason, DisconnectType type) 306 { 307 SSL_shutdown(sslHandle); 308 flushWritten(); 309 super.disconnect(reason, type); 310 } 311 312 override void onDisconnect(string reason, DisconnectType type) 313 { 314 SSL_shutdown(sslHandle); 315 r.clear(); 316 w.clear(); 317 super.onDisconnect(reason, type); 318 } 319 320 alias send = super.send; 321 322 void sslError(int ret, string msg) 323 { 324 auto err = SSL_get_error(sslHandle, ret); 325 switch (err) 326 { 327 case SSL_ERROR_WANT_READ: 328 case SSL_ERROR_ZERO_RETURN: 329 return; 330 case SSL_ERROR_SYSCALL: 331 errnoEnforce(false, msg ~ " failed"); 332 assert(false); 333 default: 334 sslEnforce(false, "%s failed - error code %s".format(msg, err)); 335 } 336 } 337 338 override OpenSSLCertificate getHostCertificate() 339 { 340 return new OpenSSLCertificate(SSL_get_certificate(sslHandle).sslEnforce()); 341 } 342 343 override OpenSSLCertificate getPeerCertificate() 344 { 345 return new OpenSSLCertificate(SSL_get_peer_certificate(sslHandle).sslEnforce()); 346 } 347 } 348 349 class OpenSSLCertificate : SSLCertificate 350 { 351 X509* x509; 352 353 this(X509* x509) 354 { 355 this.x509 = x509; 356 } 357 358 override string getSubjectName() 359 { 360 char[256] buf; 361 X509_NAME_oneline(X509_get_subject_name(x509), buf.ptr, buf.length); 362 buf[$-1] = 0; 363 return buf.ptr.to!string(); 364 } 365 } 366 367 // *************************************************************************** 368 369 /// TODO: replace with custom BIO which hooks into IConnection 370 struct MemoryBIO 371 { 372 @disable this(this); 373 374 this(const(void)[] data) 375 { 376 bio_ = BIO_new_mem_buf(cast(void*)data.ptr, data.length.to!int); 377 } 378 379 void set(const(void)[] data) 380 { 381 BUF_MEM *bptr = BUF_MEM_new(); 382 if (data.length) 383 { 384 BUF_MEM_grow(bptr, data.length); 385 bptr.data[0..bptr.length] = cast(char[])data; 386 } 387 BIO_set_mem_buf(bio, bptr, BIO_CLOSE); 388 } 389 390 void clear() { set(null); } 391 392 @property BIO* bio() 393 { 394 if (!bio_) 395 { 396 bio_ = sslEnforce(BIO_new(BIO_s_mem())); 397 BIO_set_close(bio_, BIO_CLOSE); 398 } 399 return bio_; 400 } 401 402 const(void)[] data() 403 { 404 BUF_MEM *bptr; 405 BIO_get_mem_ptr(bio, &bptr); 406 return bptr.data[0..bptr.length]; 407 } 408 409 private: 410 BIO* bio_; 411 } 412 413 T sslEnforce(T)(T v, string message = null) 414 { 415 if (v) 416 return v; 417 418 { 419 MemoryBIO m; 420 ERR_print_errors(m.bio); 421 string msg = (cast(char[])m.data).idup; 422 423 if (message) 424 msg = message ~ ": " ~ msg; 425 426 throw new Exception(msg); 427 } 428 } 429 430 // *************************************************************************** 431 432 unittest 433 { 434 void testServer(string host, ushort port) 435 { 436 auto c = new TcpConnection; 437 auto ctx = ssl.createContext(SSLContext.Kind.client); 438 auto s = ssl.createAdapter(ctx, c); 439 440 s.handleConnect = 441 { 442 debug(OPENSSL) stderr.writeln("Connected!"); 443 s.send(Data("GET / HTTP/1.0\r\n\r\n")); 444 }; 445 s.handleReadData = (Data data) 446 { 447 debug(OPENSSL) { stderr.write(cast(string)data.contents); stderr.flush(); } 448 }; 449 c.connect(host, port); 450 socketManager.loop(); 451 } 452 453 testServer("www.openssl.org", 443); 454 }