vibe.stream.openssl 18/477(3%) line coverage

      
10
20
30
40
50
60
70
80
90
100
110
120
130
140
150
160
170
180
190
200
210
220
230
240
250
260
270
280
290
300
310
320
330
340
350
360
370
380
390
400
410
420
430
440
450
460
470
480
490
500
510
520
530
540
550
560
570
580
590
600
610
620
630
640
650
660
670
680
690
700
710
720
730
740
750
760
770
780
790
800
810
820
830
840
850
860
870
880
890
900
910
920
930
940
950
960
970
980
990
1000
1010
1020
1030
1040
1050
1060
1070
1080
1090
1100
1110
1120
1130
1140
1150
1160
1170
1180
1190
1200
1210
1220
1230
1240
1250
1260
1270
1280
1290
1300
1310
1320
1330
1340
1350
1360
1370
1380
1390
1400
1410
1420
1430
1440
1450
1460
1470
1480
1490
1500
1510
1520
1530
1540
1550
1560
1570
1580
1590
1600
1610
1620
1630
1640
1650
1660
1670
1680
1690
1700
1710
1720
1730
1740
1750
1760
1770
1780
1790
1800
1810
1820
1830
1840
1850
1860
1870
1880
1890
1900
1910
1920
1930
1940
1950
1960
1970
1980
1990
2000
2010
2020
2030
2040
2050
2060
2070
2080
2090
2100
2110
2120
2130
2140
2150
2160
2170
2180
2190
2200
2210
2220
2230
2240
2250
2260
2270
2280
2290
2300
2310
2320
2330
2340
2350
2360
2370
2380
2390
2400
2410
2420
2430
2440
2450
2460
2470
2480
2490
2500
2510
2520
2530
2540
2550
2560
2570
2580
2590
2600
2610
2620
2630
2640
2650
2660
2670
2680
2690
2700
2710
2720
2730
2740
2750
2760
2770
2780
2790
2800
2810
2820
2830
2840
2850
2860
2870
2880
2890
2900
2910
2920
2930
2940
2950
2960
2970
2980
2990
3000
3010
3020
3030
3040
3050
3060
3070
3080
3090
3100
3110
3120
3130
3140
3150
3160
3170
3180
3190
3200
3210
3220
3230
3240
3250
3260
3270
3280
3290
3300
3310
3320
3330
3340
3350
3360
3370
3380
3390
3400
3410
3420
3430
3440
3450
3460
3470
3480
3490
3500
3510
3520
3530
3540
3550
3560
3570
3580
3590
3600
3610
3620
3630
3640
3650
3660
3670
3680
3690
3700
3710
3720
3730
3740
3750
3760
3770
3780
3790
3800
3810
3820
3830
3840
3850
3860
3870
3880
3890
3900
3910
3920
3930
3940
3950
3960
3970
3980
3990
4000
4010
4020
4030
4040
4050
4060
4070
4080
4090
4100
4110
4120
4130
4140
4150
4160
4170
4180
4190
4200
4210
4220
4230
4240
4250
4260
4270
4280
4290
4300
4310
4320
4330
4340
4350
4360
4370
4380
4390
4400
4410
4420
4430
4440
4450
4460
4470
4480
4490
4500
4510
4520
4530
4540
4550
4560
4570
4580
4590
4600
4610
4620
4630
4640
4650
4660
4670
4680
4690
4700
4710
4720
4730
4740
4750
4760
4770
4780
4790
4800
4810
4820
4830
4840
4850
4860
4870
4880
4890
4900
4910
4920
4930
4940
4950
4960
4970
4980
4990
5000
5010
5020
5030
5040
5050
5060
5070
5080
5090
5100
5110
5120
5130
5140
5150
5160
5170
5180
5190
5200
5210
5220
5230
5240
5250
5260
5270
5280
5290
5300
5310
5320
5330
5340
5350
5360
5370
5380
5390
5400
5410
5420
5430
5440
5450
5460
5470
5480
5490
5500
5510
5520
5530
5540
5550
5560
5570
5580
5590
5600
5610
5620
5630
5640
5650
5660
5670
5680
5690
5700
5710
5720
5730
5740
5750
5760
5770
5780
5790
5800
5810
5820
5830
5840
5850
5860
5870
5880
5890
5900
5910
5920
5930
5940
5950
5960
5970
5980
5990
6000
6010
6020
6030
6040
6050
6060
6070
6080
6090
6100
6110
6120
6130
6140
6150
6160
6170
6180
6190
6200
6210
6220
6230
6240
6250
6260
6270
6280
6290
6300
6310
6320
6330
6340
6350
6360
6370
6380
6390
6400
6410
6420
6430
6440
6450
6460
6470
6480
6490
6500
6510
6520
6530
6540
6550
6560
6570
6580
6590
6600
6610
6620
6630
6640
6650
6660
6670
6680
6690
6700
6710
6720
6730
6740
6750
6760
6770
6780
6790
6800
6810
6820
6830
6840
6850
6860
6870
6880
6890
6900
6910
6920
6930
6940
6950
6960
6970
6980
6990
7000
7010
7020
7030
7040
7050
7060
7070
7080
7090
7100
7110
7120
7130
7140
7150
7160
7170
7180
7190
7200
7210
7220
7230
7240
7250
7260
7270
7280
7290
7300
7310
7320
7330
7340
7350
7360
7370
7380
7390
7400
7410
7420
7430
7440
7450
7460
7470
7480
7490
7500
7510
7520
7530
7540
7550
7560
7570
7580
7590
7600
7610
7620
7630
7640
7650
7660
7670
7680
7690
7700
7710
7720
7730
7740
7750
7760
7770
7780
7790
7800
7810
7820
7830
7840
7850
7860
7870
7880
7890
7900
7910
7920
7930
7940
7950
7960
7970
7980
7990
8000
8010
8020
8030
8040
8050
8060
8070
8080
8090
8100
8110
8120
8130
8140
8150
8160
8170
8180
8190
8200
8210
8220
8230
8240
8250
8260
8270
8280
8290
8300
8310
8320
8330
8340
8350
8360
8370
8380
8390
8400
8410
8420
8430
8440
8450
8460
8470
8480
8490
8500
8510
8520
8530
8540
8550
8560
8570
8580
8590
8600
8610
8620
8630
8640
8650
8660
8670
8680
8690
8700
8710
8720
8730
8740
8750
8760
8770
8780
8790
8800
8810
8820
8830
8840
8850
8860
8870
8880
8890
8900
8910
8920
8930
8940
8950
8960
8970
8980
8990
9000
9010
9020
9030
9040
9050
9060
9070
9080
9090
9101
9111
9121
9130
9141
9150
916126
91741
918126
91941
9200
9210
9221
9231
9240
9251
9261
9270
9281
9290
9300
9310
9320
9330
9340
9350
9360
9370
9380
9390
9400
9410
9420
9430
9440
9450
9460
9470
9480
9490
9500
9510
9520
9530
9540
9550
9560
9570
9580
9590
9600
9610
9620
9630
9640
9650
9660
9670
9680
9690
9700
9710
9720
9730
9740
9750
9760
9770
9780
9790
9800
9810
9820
9830
9840
9850
9860
9870
9880
9890
9900
9910
9920
9930
9940
9950
9960
9970
9980
9990
10000
10010
10020
10030
10040
10050
10060
10070
10080
10090
10100
10110
10120
10130
10140
10150
10160
10170
10180
10190
10200
10210
10220
10230
10240
10250
10260
10270
10280
10290
10300
10310
10320
10330
10340
10350
10360
10370
10380
10390
10400
10410
10420
10430
10440
10450
10460
10470
10480
10490
10500
10510
10520
10530
10540
10550
10560
10570
10580
10590
10600
10610
10620
10630
10640
10650
10660
10670
10680
10690
10700
10710
10720
10730
10740
10750
10760
10770
10780
10790
10800
10810
10820
10830
10840
10850
10860
10870
10880
10890
10900
10910
10920
10930
10940
109572
109648
109724
109836
109912
11000
11010
11020
11030
11040
11050
11060
11070
11080
11090
11100
11110
11120
11130
11140
11150
11160
11170
11180
11190
11200
11210
11220
11230
11240
11250
11260
11270
11280
11290
11300
11310
11320
11330
11340
11350
11360
11370
11380
11390
11400
11410
11420
11430
11440
11450
11460
11470
11480
11490
11500
11510
11520
11530
11540
11550
11560
11570
11580
11590
11600
11610
11620
11630
11640
11650
11660
11670
11680
11690
11700
11710
11720
11730
11740
11750
11760
11770
11780
11790
11800
11810
11820
11830
11840
11850
11860
11870
11880
11890
11900
11910
11920
11930
11940
11950
11960
11970
11980
11990
12000
12010
12020
12030
12040
12050
12060
12070
12080
12090
12100
12110
12120
12130
12140
12150
12160
/** OpenSSL based SSL/TLS stream implementation Copyright: © 2012-2014 RejectedSoftware e.K. License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file. Authors: Sönke Ludwig */ module vibe.stream.openssl; version(Have_openssl): import vibe.core.log; import vibe.core.net; import vibe.core.stream; import vibe.core.sync; import vibe.stream.tls; import vibe.internal.interfaceproxy : InterfaceProxy; import std.algorithm; import std.array; import std.conv; import std.exception; import std.socket; import std.string; import core.stdc.string : strlen; import core.sync.mutex; import core.thread; /**************************************************************************************************/ /* Public types */ /**************************************************************************************************/ import deimos.openssl.bio; import deimos.openssl.err; import deimos.openssl.rand; import deimos.openssl.ssl; import deimos.openssl.stack; import deimos.openssl.x509v3; version (VibePragmaLib) { pragma(lib, "ssl"); version (Windows) pragma(lib, "eay"); } version (VibeUseOldOpenSSL) private enum haveECDH = false; else private enum haveECDH = OPENSSL_VERSION_NUMBER >= 0x10001000; version(VibeForceALPN) enum alpn_forced = true; else enum alpn_forced = false; enum haveALPN = OPENSSL_VERSION_NUMBER >= 0x10200000 || alpn_forced; // openssl 1.1.0 hack: provides a 1.0.x API in terms of the 1.1.x API version (VibeUseOpenSSL11) { extern(C) const(SSL_METHOD)* TLS_client_method(); alias SSLv23_client_method = TLS_client_method; extern(C) const(SSL_METHOD)* TLS_server_method(); alias SSLv23_server_method = TLS_server_method; // this does nothing in > openssl 1.1.0 void SSL_load_error_strings() {} extern(C) int OPENSSL_init_ssl(ulong opts, const void* settings); // # define SSL_library_init() OPENSSL_init_ssl(0, NULL) int SSL_library_init() { return OPENSSL_init_ssl(0, null); } //# define CRYPTO_num_locks() (1) int CRYPTO_num_locks() { return 1; } void CRYPTO_set_id_callback(T)(T t) { } void CRYPTO_set_locking_callback(T)(T t) { } // #define SSL_get_ex_new_index(l, p, newf, dupf, freef) \ // CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_SSL, l, p, newf, dupf, freef) extern(C) int CRYPTO_get_ex_new_index(int class_index, long argl, void *argp, CRYPTO_EX_new *new_func, CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func); int SSL_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func, CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func) { // # define CRYPTO_EX_INDEX_SSL 0 return CRYPTO_get_ex_new_index(0, argl, argp, new_func, dup_func, free_func); } extern(C) BIGNUM* BN_get_rfc3526_prime_2048(BIGNUM *bn); alias get_rfc3526_prime_2048 = BN_get_rfc3526_prime_2048; // # define sk_num OPENSSL_sk_num extern(C) int OPENSSL_sk_num(const void *); extern(C) int sk_num(const(_STACK)* p) { return OPENSSL_sk_num(p); } // # define sk_value OPENSSL_sk_value extern(C) void *OPENSSL_sk_value(const void *, int); extern(C) void* sk_value(const(_STACK)* p, int i) { return OPENSSL_sk_value(p, i); } } /** Creates an SSL/TLS tunnel within an existing stream. Note: Be sure to call finalize before finalizing/closing the outer stream so that the SSL tunnel is properly closed first. */ final class OpenSSLStream : TLSStream { @safe: private { InterfaceProxy!Stream m_stream; TLSContext m_tlsCtx; TLSStreamState m_state; SSLState m_tls; BIO* m_bio; ubyte[64] m_peekBuffer; TLSCertificateInformation m_peerCertificateInfo; X509* m_peerCertificate; } this(InterfaceProxy!Stream underlying, OpenSSLContext ctx, TLSStreamState state, string peer_name = null, NetworkAddress peer_address = NetworkAddress.init, string[] alpn = null) { m_stream = underlying; m_state = state; m_tlsCtx = ctx; m_tls = ctx.createClientCtx(); scope (failure) { () @trusted { SSL_free(m_tls); } (); m_tls = null; } m_bio = () @trusted { return BIO_new(&s_bio_methods); } (); enforce(m_bio !is null, "SSL failed: failed to create BIO structure."); m_bio.init_ = 1; m_bio.ptr = () @trusted { return cast(void*)this; } (); // lifetime is shorter than this, so no GC.addRange needed. m_bio.shutdown = 0; () @trusted { SSL_set_bio(m_tls, m_bio, m_bio); } (); if (state != TLSStreamState.connected) { OpenSSLContext.VerifyData vdata; vdata.verifyDepth = ctx.maxCertChainLength; vdata.validationMode = ctx.peerValidationMode; vdata.callback = ctx.peerValidationCallback; vdata.peerName = peer_name; vdata.peerAddress = peer_address; () @trusted { SSL_set_ex_data(m_tls, gs_verifyDataIndex, &vdata); } (); scope (exit) () @trusted { SSL_set_ex_data(m_tls, gs_verifyDataIndex, null); } (); final switch (state) { case TLSStreamState.accepting: //SSL_set_accept_state(m_tls); checkSSLRet(() @trusted { return SSL_accept(m_tls); } (), "Accepting SSL tunnel"); break; case TLSStreamState.connecting: // a client stream can override the default ALPN setting for this context if (alpn.length) setClientALPN(alpn); if (peer_name.length) () @trusted { return SSL_ctrl(m_tls, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name, cast(void*)peer_name.toStringz); } (); //SSL_set_connect_state(m_tls); checkSSLRet(() @trusted { return SSL_connect(m_tls); } (), "Connecting TLS tunnel"); break; case TLSStreamState.connected: break; } // ensure that the SSL tunnel gets terminated when an error happens during verification scope (failure) () @trusted { SSL_shutdown(m_tls); } (); m_peerCertificate = () @trusted { return SSL_get_peer_certificate(m_tls); } (); if (m_peerCertificate) { readPeerCertInfo(); auto result = () @trusted { return SSL_get_verify_result(m_tls); } (); if (result == X509_V_OK && (ctx.peerValidationMode & TLSPeerValidationMode.checkPeer)) { if (!verifyCertName(m_peerCertificate, GENERAL_NAME.GEN_DNS, vdata.peerName)) { version(Windows) import core.sys.windows.winsock2; else import core.sys.posix.netinet.in_; logDiagnostic("TLS peer name '%s' couldn't be verified, trying IP address.", vdata.peerName); char* addr; int addrlen; switch (vdata.peerAddress.family) { default: break; case AF_INET: addr = cast(char*)&vdata.peerAddress.sockAddrInet4.sin_addr; addrlen = vdata.peerAddress.sockAddrInet4.sin_addr.sizeof; break; case AF_INET6: addr = cast(char*)&vdata.peerAddress.sockAddrInet6.sin6_addr; addrlen = vdata.peerAddress.sockAddrInet6.sin6_addr.sizeof; break; } if (!verifyCertName(m_peerCertificate, GENERAL_NAME.GEN_IPADD, () @trusted { return addr[0 .. addrlen]; } ())) { logDiagnostic("Error validating TLS peer address"); result = X509_V_ERR_APPLICATION_VERIFICATION; } } } enforce(result == X509_V_OK, "Peer failed the certificate validation: "~to!string(result)); } //else enforce(ctx.verifyMode < requireCert); } } /** Read certificate info into the clientInformation field */ private void readPeerCertInfo() { X509_NAME* name = () @trusted { return X509_get_subject_name(m_peerCertificate); } (); int c = () @trusted { return X509_NAME_entry_count(name); } (); foreach (i; 0 .. c) { X509_NAME_ENTRY *e = () @trusted { return X509_NAME_get_entry(name, i); } (); ASN1_OBJECT *obj = () @trusted { return X509_NAME_ENTRY_get_object(e); } (); ASN1_STRING *val = () @trusted { return X509_NAME_ENTRY_get_data(e); } (); auto longName = () @trusted { return OBJ_nid2ln(OBJ_obj2nid(obj)).to!string; } (); auto valStr = () @trusted { return cast(string)val.data[0 .. val.length]; } (); // FIXME: .idup? m_peerCertificateInfo.subjectName.addField(longName, valStr); } m_peerCertificateInfo._x509 = m_peerCertificate; } ~this() { if (m_peerCertificate) () @trusted { X509_free(m_peerCertificate); } (); if (m_tls) () @trusted { SSL_free(m_tls); } (); } @property bool empty() { return leastSize() == 0; } @property ulong leastSize() { checkSSLRet(() @trusted { return SSL_peek(m_tls, m_peekBuffer.ptr, 1); } (), "Reading from TLS stream"); return () @trusted { return SSL_pending(m_tls); } (); } @property bool dataAvailableForRead() { return () @trusted { return SSL_pending(m_tls); } () > 0 || m_stream.dataAvailableForRead; } const(ubyte)[] peek() { auto ret = checkSSLRet(() @trusted { return SSL_peek(m_tls, m_peekBuffer.ptr, m_peekBuffer.length); } (), "Peeking TLS stream"); return ret > 0 ? m_peekBuffer[0 .. ret] : null; } size_t read(scope ubyte[] dst, IOMode mode) { size_t nbytes = 0; while (dst.length > 0) { int readlen = min(dst.length, int.max); auto ret = checkSSLRet(() @trusted { return SSL_read(m_tls, dst.ptr, readlen); } (), "Reading from TLS stream"); //logTrace("SSL read %d/%d", ret, dst.length); dst = dst[ret .. $]; nbytes += ret; if (mode == IOMode.immediate || mode == IOMode.once) break; } return nbytes; } alias read = Stream.read; size_t write(in ubyte[] bytes_, IOMode mode) { const(ubyte)[] bytes = bytes_; size_t nbytes = 0; while (bytes.length > 0) { int writelen = min(bytes.length, int.max); auto ret = checkSSLRet(() @trusted { return SSL_write(m_tls, bytes.ptr, writelen); } (), "Writing to TLS stream"); //logTrace("SSL write %s", cast(string)bytes[0 .. ret]); bytes = bytes[ret .. $]; nbytes += ret; if (mode == IOMode.immediate || mode == IOMode.once) break; } return nbytes; } alias write = Stream.write; void flush() { m_stream.flush(); } void finalize() { if( !m_tls ) return; logTrace("OpenSSLStream finalize"); () @trusted { SSL_shutdown(m_tls); SSL_free(m_tls); } (); m_tls = null; } private int checkSSLRet(int ret, string what) @safe { if (ret > 0) return ret; string desc; auto err = () @trusted { return SSL_get_error(m_tls, ret); } (); switch (err) { default: desc = format("Unknown error (%s)", err); break; case SSL_ERROR_NONE: desc = "No error"; break; case SSL_ERROR_ZERO_RETURN: desc = "SSL/TLS tunnel closed"; break; case SSL_ERROR_WANT_READ: desc = "Need to block for read"; break; case SSL_ERROR_WANT_WRITE: desc = "Need to block for write"; break; case SSL_ERROR_WANT_CONNECT: desc = "Need to block for connect"; break; case SSL_ERROR_WANT_ACCEPT: desc = "Need to block for accept"; break; case SSL_ERROR_WANT_X509_LOOKUP: desc = "Need to block for certificate lookup"; break; case SSL_ERROR_SYSCALL: case SSL_ERROR_SSL: return enforceSSL(ret, what); } const(char)* file = null, data = null; int line; int flags; c_ulong eret; char[120] ebuf; while( (eret = () @trusted { return ERR_get_error_line_data(&file, &line, &data, &flags); } ()) != 0 ){ () @trusted { ERR_error_string(eret, ebuf.ptr); } (); logDebug("%s error at %s:%d: %s (%s)", what, () @trusted { return to!string(file); } (), line, () @trusted { return to!string(ebuf.ptr); } (), flags & ERR_TXT_STRING ? () @trusted { return to!string(data); } () : "-"); } enforce(ret != 0, format("%s was unsuccessful with ret 0", what)); enforce(ret >= 0, format("%s returned an error: %s", what, desc)); return ret; } private int enforceSSL(int ret, string message) @safe { if (ret > 0) return ret; c_ulong eret; const(char)* file = null, data = null; int line; int flags; string estr; char[120] ebuf = 0; while ((eret = () @trusted { return ERR_get_error_line_data(&file, &line, &data, &flags); } ()) != 0) { () @trusted { ERR_error_string_n(eret, ebuf.ptr, ebuf.length); } (); estr = () @trusted { return ebuf.ptr.to!string; } (); // throw the last error code as an exception logDebug("OpenSSL error at %s:%d: %s (%s)", () @trusted { return file.to!string; } (), line, estr, flags & ERR_TXT_STRING ? () @trusted { return to!string(data); } () : "-"); if (!() @trusted { return ERR_peek_error(); } ()) break; } throw new Exception(format("%s: %s (%s)", message, estr, eret)); } @property TLSCertificateInformation peerCertificate() { return m_peerCertificateInfo; } @property X509* peerCertificateX509() { return m_peerCertificate; } @property string alpn() const { static if (!haveALPN) assert(false, "OpenSSL support not compiled with ALPN enabled. Use VibeForceALPN."); else { char[32] data; uint datalen; () @trusted { SSL_get0_alpn_selected(m_ssl, cast(const char*) data.ptr, &datalen); } (); logDebug("alpn selected: ", data.to!string); if (datalen > 0) return data[0..datalen].idup; else return null; } } /// Invoked by client to offer alpn private void setClientALPN(string[] alpn_list) { logDebug("SetClientALPN: ", alpn_list); import vibe.internal.allocator : dispose, makeArray, vibeThreadAllocator; ubyte[] alpn; size_t len; foreach (string alpn_val; alpn_list) len += alpn_val.length + 1; alpn = () @trusted { return vibeThreadAllocator.makeArray!ubyte(len); } (); size_t i; foreach (string alpn_val; alpn_list) { alpn[i++] = cast(ubyte)alpn_val.length; alpn[i .. i+alpn_val.length] = cast(immutable(ubyte)[])alpn_val; i += alpn_val.length; } assert(i == len); static if (haveALPN) SSL_set_alpn_protos(m_ssl, cast(const char*) alpn.ptr, cast(uint) len); () @trusted { vibeThreadAllocator.dispose(alpn); } (); } } /** Encapsulates the configuration for an SSL tunnel. Note that when creating an SSLContext with SSLContextKind.client, the peerValidationMode will be set to SSLPeerValidationMode.trustedCert, but no trusted certificate authorities are added by default. Use useTrustedCertificateFile to add those. */ final class OpenSSLContext : TLSContext { @safe: private { TLSContextKind m_kind; ssl_ctx_st* m_ctx; TLSPeerValidationCallback m_peerValidationCallback; TLSPeerValidationMode m_validationMode; int m_verifyDepth; TLSServerNameCallback m_sniCallback; TLSALPNCallback m_alpnCallback; } this(TLSContextKind kind, TLSVersion ver = TLSVersion.any) { m_kind = kind; const(SSL_METHOD)* method; c_long options = SSL_OP_NO_SSLv2|SSL_OP_NO_COMPRESSION| SSL_OP_SINGLE_DH_USE|SSL_OP_SINGLE_ECDH_USE; () @trusted { final switch (kind) { case TLSContextKind.client: final switch (ver) { case TLSVersion.any: method = SSLv23_client_method(); options |= SSL_OP_NO_SSLv3; break; case TLSVersion.ssl3: method = SSLv23_client_method(); options |= SSL_OP_NO_SSLv2|SSL_OP_NO_TLSv1_1|SSL_OP_NO_TLSv1|SSL_OP_NO_TLSv1_2; break; case TLSVersion.tls1: method = TLSv1_client_method(); break; //case TLSVersion.tls1_1: method = TLSv1_1_client_method(); break; //case TLSVersion.tls1_2: method = TLSv1_2_client_method(); break; case TLSVersion.tls1_1: method = SSLv23_client_method(); options |= SSL_OP_NO_SSLv3|SSL_OP_NO_TLSv1|SSL_OP_NO_TLSv1_2; break; case TLSVersion.tls1_2: method = SSLv23_client_method(); options |= SSL_OP_NO_SSLv3|SSL_OP_NO_TLSv1|SSL_OP_NO_TLSv1_1; break; case TLSVersion.dtls1: method = DTLSv1_client_method(); break; } break; case TLSContextKind.server: case TLSContextKind.serverSNI: final switch (ver) { case TLSVersion.any: method = SSLv23_server_method(); options |= SSL_OP_NO_SSLv3; break; case TLSVersion.ssl3: method = SSLv23_server_method(); options |= SSL_OP_NO_SSLv2|SSL_OP_NO_TLSv1_1|SSL_OP_NO_TLSv1|SSL_OP_NO_TLSv1_2; break; case TLSVersion.tls1: method = TLSv1_server_method(); break; case TLSVersion.tls1_1: method = SSLv23_server_method(); options |= SSL_OP_NO_SSLv3|SSL_OP_NO_TLSv1|SSL_OP_NO_TLSv1_2; break; case TLSVersion.tls1_2: method = SSLv23_server_method(); options |= SSL_OP_NO_SSLv3|SSL_OP_NO_TLSv1|SSL_OP_NO_TLSv1_1; break; //case TLSVersion.tls1_1: method = TLSv1_1_server_method(); break; //case TLSVersion.tls1_2: method = TLSv1_2_server_method(); break; case TLSVersion.dtls1: method = DTLSv1_server_method(); break; } options |= SSL_OP_CIPHER_SERVER_PREFERENCE; break; } } (); m_ctx = () @trusted { return SSL_CTX_new(method); } (); () @trusted { SSL_CTX_set_options!()(m_ctx, options); }(); if (kind == TLSContextKind.server) { setDHParams(); static if (haveECDH) setECDHCurve(); guessSessionIDContext(); } setCipherList(); maxCertChainLength = 9; if (kind == TLSContextKind.client) peerValidationMode = TLSPeerValidationMode.trustedCert; else peerValidationMode = TLSPeerValidationMode.none; // while it would be nice to use the system's certificate store, this // seems to be difficult to get right across all systems. The most // popular alternative is to use Mozilla's certificate store and // distribute it along with the library (e.g. in source code form. /*version (Posix) { enforce(SSL_CTX_load_verify_locations(m_ctx, null, "/etc/ssl/certs"), "Failed to load system certificate store."); } version (Windows) { auto store = CertOpenSystemStore(null, "ROOT"); enforce(store !is null, "Failed to load system certificate store."); scope (exit) CertCloseStore(store, 0); PCCERT_CONTEXT ctx; while((ctx = CertEnumCertificatesInStore(store, ctx)) !is null) { X509* x509cert; auto buffer = ctx.pbCertEncoded; auto len = ctx.cbCertEncoded; if (ctx.dwCertEncodingType & X509_ASN_ENCODING) { x509cert = d2i_X509(null, &buffer, len); X509_STORE_add_cert(SSL_CTX_get_cert_store(m_ctx), x509cert); } } }*/ } ~this() { () @trusted { SSL_CTX_free(m_ctx); } (); m_ctx = null; } /// The kind of SSL context (client/server) @property TLSContextKind kind() const { return m_kind; } /// Callback function invoked by server to choose alpn @property void alpnCallback(TLSALPNCallback alpn_chooser) { logDebug("Choosing ALPN callback"); m_alpnCallback = alpn_chooser; static if (haveALPN) { logDebug("Call select cb"); SSL_CTX_set_alpn_select_cb(m_ctx, &chooser, cast(void*)this); } } /// Get the current ALPN callback function @property TLSALPNCallback alpnCallback() const { return m_alpnCallback; } /// Invoked by client to offer alpn void setClientALPN(string[] alpn_list) { static if (!haveALPN) assert(false, "OpenSSL support not compiled with ALPN enabled. Use VibeForceALPN."); else { import vibe.utils.memory : allocArray, freeArray, manualAllocator; ubyte[] alpn; size_t len; foreach (string alpn_value; alpn_list) len += alpn_value.length + 1; alpn = allocArray!ubyte(manualAllocator(), len); size_t i; foreach (string alpn_value; alpn_list) { alpn[i++] = cast(ubyte)alpn_value.length; alpn[i .. i+alpn_value.length] = cast(ubyte[])alpn_value; i += alpn_value.length; } assert(i == len); SSL_CTX_set_alpn_protos(m_ctx, cast(const char*) alpn.ptr, cast(uint) len); freeArray(manualAllocator(), alpn); } } /** Specifies the validation level of remote peers. The default mode for TLSContextKind.client is TLSPeerValidationMode.trustedCert and the default for TLSContextKind.server is TLSPeerValidationMode.none. */ @property void peerValidationMode(TLSPeerValidationMode mode) { m_validationMode = mode; int sslmode; with (TLSPeerValidationMode) { if (mode == none) sslmode = SSL_VERIFY_NONE; else { sslmode |= SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE; if (mode & requireCert) sslmode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT; } } () @trusted { SSL_CTX_set_verify(m_ctx, sslmode, &verify_callback); } (); } /// ditto @property TLSPeerValidationMode peerValidationMode() const { return m_validationMode; } /** The maximum length of an accepted certificate chain. Any certificate chain longer than this will result in the SSL/TLS negitiation failing. The default value is 9. */ @property void maxCertChainLength(int val) { m_verifyDepth = val; // + 1 to let the validation callback handle the error () @trusted { SSL_CTX_set_verify_depth(m_ctx, val + 1); } (); } /// ditto @property int maxCertChainLength() const { return m_verifyDepth; } /** An optional user callback for peer validation. This callback will be called for each peer and each certificate of its certificate chain to allow overriding the validation decision based on the selected peerValidationMode (e.g. to allow invalid certificates or to reject valid ones). This is mainly useful for presenting the user with a dialog in case of untrusted or mismatching certificates. */ @property void peerValidationCallback(TLSPeerValidationCallback callback) { m_peerValidationCallback = callback; } /// ditto @property inout(TLSPeerValidationCallback) peerValidationCallback() inout { return m_peerValidationCallback; } @property void sniCallback(TLSServerNameCallback callback) { m_sniCallback = callback; if (m_kind == TLSContextKind.serverSNI) { () @trusted { SSL_CTX_callback_ctrl(m_ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, cast(OSSLCallback)&onContextForServerName); SSL_CTX_ctrl(m_ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, cast(void*)this); } (); } } @property inout(TLSServerNameCallback) sniCallback() inout { return m_sniCallback; } private extern(C) alias OSSLCallback = void function(); private static extern(C) int onContextForServerName(SSL *s, int *ad, void *arg) { auto ctx = () @trusted { return cast(OpenSSLContext)arg; } (); auto servername = () @trusted { return SSL_get_servername(s, TLSEXT_NAMETYPE_host_name); } (); if (!servername) return SSL_TLSEXT_ERR_NOACK; auto newctx = cast(OpenSSLContext)ctx.m_sniCallback(() @trusted { return servername.to!string; } ()); if (!newctx) return SSL_TLSEXT_ERR_NOACK; () @trusted { SSL_set_SSL_CTX(s, newctx.m_ctx); } (); return SSL_TLSEXT_ERR_OK; } OpenSSLStream createStream(InterfaceProxy!Stream underlying, TLSStreamState state, string peer_name = null, NetworkAddress peer_address = NetworkAddress.init) { return new OpenSSLStream(underlying, this, state, peer_name, peer_address); } /** Set the list of cipher specifications to use for SSL/TLS tunnels. The list must be a colon separated list of cipher specifications as accepted by OpenSSL. Calling this function without argument will restore the default. See_also: $(LINK https://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT) */ void setCipherList(string list = null) @trusted { if (list is null) SSL_CTX_set_cipher_list(m_ctx, "ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:" ~ "RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS"); else SSL_CTX_set_cipher_list(m_ctx, toStringz(list)); } /** Make up a context ID to assign to the SSL context. This is required when doing client cert authentication, otherwise many connections will go aborted as the client tries to revive a session that it used to have on another machine. The session ID context should be unique within a pool of servers. Currently, this is achieved by taking the hostname. */ private void guessSessionIDContext() @trusted { string contextID = Socket.hostName; SSL_CTX_set_session_id_context(m_ctx, cast(ubyte*)contextID.toStringz(), cast(uint)contextID.length); } /** Set params to use for DH cipher. * * By default the 2048-bit prime from RFC 3526 is used. * * Params: * pem_file = Path to a PEM file containing the DH parameters. Calling * this function without argument will restore the default. */ void setDHParams(string pem_file=null) @trusted { DH* dh; scope(exit) DH_free(dh); if (pem_file is null) { dh = enforce(DH_new(), "Unable to create DH structure."); dh.p = get_rfc3526_prime_2048(null); ubyte dh_generator = 2; dh.g = BN_bin2bn(&dh_generator, dh_generator.sizeof, null); } else { import core.stdc.stdio : fclose, fopen; auto f = enforce(fopen(toStringz(pem_file), "r"), "Failed to load dhparams file "~pem_file); scope(exit) fclose(f); dh = enforce(PEM_read_DHparams(f, null, null, null), "Failed to read dhparams file "~pem_file); } SSL_CTX_set_tmp_dh(m_ctx, dh); } /** Set the elliptic curve to use for ECDH cipher. * * By default a curve is either chosen automatically or prime256v1 is used. * * Params: * curve = The short name of the elliptic curve to use. Calling this * function without argument will restore the default. * */ void setECDHCurve(string curve = null) @trusted { static if (haveECDH) { static if (OPENSSL_VERSION_NUMBER >= 0x10200000) { // use automatic ecdh curve selection by default if (curve is null) { SSL_CTX_set_ecdh_auto(m_ctx, true); return; } // but disable it when an explicit curve is given SSL_CTX_set_ecdh_auto(m_ctx, false); } int nid; if (curve is null) nid = NID_X9_62_prime256v1; else nid = enforce(OBJ_sn2nid(toStringz(curve)), "Unknown ECDH curve '"~curve~"'."); auto ecdh = enforce(EC_KEY_new_by_curve_name(nid), "Unable to create ECDH curve."); SSL_CTX_set_tmp_ecdh(m_ctx, ecdh); EC_KEY_free(ecdh); } else assert(false, "ECDH curve selection not available for old versions of OpenSSL"); } /// Sets a certificate file to use for authenticating to the remote peer void useCertificateChainFile(string path) { enforce(() @trusted { return SSL_CTX_use_certificate_chain_file(m_ctx, toStringz(path)); } (), "Failed to load certificate file " ~ path); } /// Sets the private key to use for authenticating to the remote peer based /// on the configured certificate chain file. void usePrivateKeyFile(string path) { enforce(() @trusted { return SSL_CTX_use_PrivateKey_file(m_ctx, toStringz(path), SSL_FILETYPE_PEM); } (), "Failed to load private key file " ~ path); } /** Sets the list of trusted certificates for verifying peer certificates. If this is a server context, this also entails that the given certificates are advertised to connecting clients during handshake. On Linux, the system's root certificate authority list is usually found at "/etc/ssl/certs/ca-certificates.crt", "/etc/pki/tls/certs/ca-bundle.crt", or "/etc/ssl/ca-bundle.pem". */ void useTrustedCertificateFile(string path) @trusted { immutable cPath = toStringz(path); enforce(SSL_CTX_load_verify_locations(m_ctx, cPath, null), "Failed to load trusted certificate file " ~ path); if (m_kind == TLSContextKind.server) { auto certNames = enforce(SSL_load_client_CA_file(cPath), "Failed to load client CA name list from file " ~ path); SSL_CTX_set_client_CA_list(m_ctx, certNames); } } private SSLState createClientCtx() { return () @trusted { return SSL_new(m_ctx); } (); } private static struct VerifyData { int verifyDepth; TLSPeerValidationMode validationMode; TLSPeerValidationCallback callback; string peerName; NetworkAddress peerAddress; } private static extern(C) nothrow int verify_callback(int valid, X509_STORE_CTX* ctx) @trusted { X509* err_cert = X509_STORE_CTX_get_current_cert(ctx); int err = X509_STORE_CTX_get_error(ctx); int depth = X509_STORE_CTX_get_error_depth(ctx); SSL* ssl = cast(SSL*)X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()); VerifyData* vdata = cast(VerifyData*)SSL_get_ex_data(ssl, gs_verifyDataIndex); char[1024] buf; X509_NAME_oneline(X509_get_subject_name(err_cert), buf.ptr, 256); buf[$-1] = 0; try { logDebug("validate callback for %s", buf.ptr.to!string); if (depth > vdata.verifyDepth) { logDiagnostic("SSL cert chain too long: %s vs. %s", depth, vdata.verifyDepth); valid = false; err = X509_V_ERR_CERT_CHAIN_TOO_LONG; } if (err != X509_V_OK) logDebug("SSL cert initial error: %s", X509_verify_cert_error_string(err).to!string); if (!valid) { switch (err) { default: break; case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT: case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY: case X509_V_ERR_CERT_UNTRUSTED: assert(err_cert !is null); X509_NAME_oneline(X509_get_issuer_name(err_cert), buf.ptr, buf.length); buf[$-1] = 0; logDebug("SSL cert not trusted or unknown issuer: %s", buf.ptr.to!string); if (!(vdata.validationMode & TLSPeerValidationMode.checkTrust)) { valid = true; err = X509_V_OK; } break; } } if (!(vdata.validationMode & TLSPeerValidationMode.checkCert)) { valid = true; err = X509_V_OK; } if (vdata.callback) { TLSPeerValidationData pvdata; // ... if (!valid) { if (vdata.callback(pvdata)) { valid = true; err = X509_V_OK; } } else { if (!vdata.callback(pvdata)) { logDebug("SSL application verification failed"); valid = false; err = X509_V_ERR_APPLICATION_VERIFICATION; } } } } catch (Exception e) { logWarn("SSL verification failed due to exception: %s", e.msg); err = X509_V_ERR_APPLICATION_VERIFICATION; valid = false; } X509_STORE_CTX_set_error(ctx, err); logDebug("SSL validation result: %s (%s)", valid, err); return valid; } } alias SSLState = ssl_st*; /**************************************************************************************************/ /* Private functions */ /**************************************************************************************************/ private { __gshared InterruptibleTaskMutex[] g_cryptoMutexes; __gshared int gs_verifyDataIndex; } shared static this() { logDebug("Initializing OpenSSL..."); SSL_load_error_strings(); SSL_library_init(); g_cryptoMutexes.length = CRYPTO_num_locks(); // TODO: investigate if a normal Mutex is enough - not sure if BIO is called in a locked state foreach (i; 0 .. g_cryptoMutexes.length) g_cryptoMutexes[i] = new InterruptibleTaskMutex; foreach (ref m; g_cryptoMutexes) { assert(m !is null); } CRYPTO_set_id_callback(&onCryptoGetThreadID); CRYPTO_set_locking_callback(&onCryptoLock); enforce(RAND_poll(), "Fatal: failed to initialize random number generator entropy (RAND_poll)."); logDebug("... done."); gs_verifyDataIndex = SSL_get_ex_new_index(0, cast(void*)"VerifyData".ptr, null, null, null); } private bool verifyCertName(X509* cert, int field, in char[] value, bool allow_wildcards = true) @trusted { bool delegate(in char[]) @safe str_match; bool check_value(ASN1_STRING* str, int type) { if (!str.data || !str.length) return false; if (type > 0) { if (type != str.type) return 0; auto strstr = cast(string)str.data[0 .. str.length]; return type == V_ASN1_IA5STRING ? str_match(strstr) : strstr == value; } char* utfstr; auto utflen = ASN1_STRING_to_UTF8(&utfstr, str); enforce (utflen >= 0, "Error converting ASN1 string to UTF-8."); scope (exit) OPENSSL_free(utfstr); return str_match(utfstr[0 .. utflen]); } int cnid; int alt_type; final switch (field) { case GENERAL_NAME.GEN_DNS: cnid = NID_commonName; alt_type = V_ASN1_IA5STRING; str_match = allow_wildcards ? s => matchWildcard(value, s) : s => s.icmp(value) == 0; break; case GENERAL_NAME.GEN_IPADD: cnid = 0; alt_type = V_ASN1_OCTET_STRING; str_match = s => s == value; break; } if (auto gens = cast(STACK_OF!GENERAL_NAME*)X509_get_ext_d2i(cert, NID_subject_alt_name, null, null)) { scope(exit) GENERAL_NAMES_free(gens); foreach (i; 0 .. sk_GENERAL_NAME_num(gens)) { auto gen = sk_GENERAL_NAME_value(gens, i); if (gen.type != field) continue; ASN1_STRING *cstr = field == GENERAL_NAME.GEN_DNS ? gen.d.dNSName : gen.d.iPAddress; if (check_value(cstr, alt_type)) return true; } if (!cnid) return false; } X509_NAME* name = X509_get_subject_name(cert); int i; while ((i = X509_NAME_get_index_by_NID(name, cnid, i)) >= 0) { X509_NAME_ENTRY* ne = X509_NAME_get_entry(name, i); ASN1_STRING* str = X509_NAME_ENTRY_get_data(ne); if (check_value(str, -1)) return true; } return false; } private bool matchWildcard(const(char)[] str, const(char)[] pattern) @safe { auto strparts = str.split("."); auto patternparts = pattern.split("."); if (strparts.length != patternparts.length) return false; bool isValidChar(dchar ch) { if (ch >= '0' && ch <= '9') return true; if (ch >= 'a' && ch <= 'z') return true; if (ch >= 'A' && ch <= 'Z') return true; if (ch == '-' || ch == '.') return true; return false; } if (!pattern.all!(c => isValidChar(c) || c == '*') || !str.all!(c => isValidChar(c))) return false; foreach (i; 0 .. strparts.length) { import std.regex; auto p = patternparts[i]; auto s = strparts[i]; if (!p.length || !s.length) return false; auto rex = "^" ~ std.array.replace(p, "*", "[^.]*") ~ "$"; if (!match(s, rex)) return false; } return true; } unittest { assert(matchWildcard("www.example.org", "*.example.org")); assert(matchWildcard("www.example.org", "*w.example.org")); assert(matchWildcard("www.example.org", "w*w.example.org")); assert(matchWildcard("www.example.org", "*w*.example.org")); assert(matchWildcard("test.abc.example.org", "test.*.example.org")); assert(!matchWildcard("test.abc.example.org", "abc.example.org")); assert(!matchWildcard("test.abc.example.org", ".abc.example.org")); assert(!matchWildcard("abc.example.org", "a.example.org")); assert(!matchWildcard("abc.example.org", "bc.example.org")); assert(!matchWildcard("abcdexample.org", "abc.example.org")); } private nothrow @safe extern(C) { import core.stdc.config; int chooser(SSL* ssl, const(char)** output, ubyte* outlen, const(char) *input_, uint inlen, void* arg) { const(char)[] input = () @trusted { return input_[0 .. inlen]; } (); logDebug("Got chooser input: %s", input); OpenSSLContext ctx = () @trusted { return cast(OpenSSLContext) arg; } (); import vibe.utils.array : AllocAppender, AppenderResetMode; size_t i; size_t len; Appender!(string[]) alpn_list; while (i < inlen) { len = cast(size_t) input[i]; ++i; auto proto = input[i .. i+len]; i += len; () @trusted { alpn_list ~= cast(string)proto; } (); } string alpn; try { alpn = ctx.m_alpnCallback(alpn_list.data); } catch (Exception e) { } if (alpn) { i = 0; while (i < inlen) { len = input[i]; ++i; auto proto = input[i .. i+len]; i += len; if (proto == alpn) { *output = &proto[0]; *outlen = cast(ubyte) proto.length; } } } if (!output) { logError("None of the proposed ALPN were selected: %s / falling back on HTTP/1.1", input); enum hdr = "http/1.1"; *output = &hdr[0]; *outlen = cast(ubyte)hdr.length; } return 0; } c_ulong onCryptoGetThreadID() { try { return cast(c_ulong)(cast(size_t)() @trusted { return cast(void*)Thread.getThis(); } () * 0x35d2c57); } catch (Exception e) { logWarn("OpenSSL: failed to get current thread ID: %s", e.msg); return 0; } } void onCryptoLock(int mode, int n, const(char)* file, int line) { try { enforce(n >= 0 && n < () @trusted { return g_cryptoMutexes; } ().length, "Mutex index out of range."); auto mutex = () @trusted { return g_cryptoMutexes[n]; } (); assert(mutex !is null); if (mode & CRYPTO_LOCK) mutex.lock(); else mutex.unlock(); } catch (Exception e) { logWarn("OpenSSL: failed to lock/unlock mutex: %s", e.msg); } } int onBioNew(BIO *b) nothrow { b.init_ = 0; b.num = -1; b.ptr = null; b.flags = 0; return 1; } int onBioFree(BIO *b) { if( !b ) return 0; if( b.shutdown ){ //if( b.init && b.ptr ) b.ptr.stream.free(); b.init_ = 0; b.flags = 0; b.ptr = null; } return 1; } int onBioRead(BIO *b, char *outb, int outlen) { auto stream = () @trusted { return cast(OpenSSLStream)b.ptr; } (); try { outlen = min(outlen, stream.m_stream.leastSize); stream.m_stream.read(() @trusted { return cast(ubyte[])outb[0 .. outlen]; } ()); } catch (Exception e) { setSSLError("Error reading from underlying stream", e.msg); return -1; } return outlen; } int onBioWrite(BIO *b, const(char) *inb, int inlen) { auto stream = () @trusted { return cast(OpenSSLStream)b.ptr; } (); try { stream.m_stream.write(() @trusted { return inb[0 .. inlen]; } ()); } catch (Exception e) { setSSLError("Error writing to underlying stream", e.msg); return -1; } return inlen; } c_long onBioCtrl(BIO *b, int cmd, c_long num, void *ptr) { auto stream = () @trusted { return cast(OpenSSLStream)b.ptr; } (); c_long ret = 1; switch(cmd){ case BIO_CTRL_GET_CLOSE: ret = b.shutdown; break; case BIO_CTRL_SET_CLOSE: logTrace("SSL set close %d", num); b.shutdown = cast(int)num; break; case BIO_CTRL_PENDING: try { auto sz = stream.m_stream.leastSize; // FIXME: .peek.length should be sufficient here return sz <= c_long.max ? cast(c_long)sz : c_long.max; } catch( Exception e ){ setSSLError("Error reading from underlying stream", e.msg); return -1; } case BIO_CTRL_WPENDING: return 0; case BIO_CTRL_DUP: case BIO_CTRL_FLUSH: ret = 1; break; default: ret = 0; break; } return ret; } int onBioPuts(BIO *b, const(char) *s) { return onBioWrite(b, s, cast(int)() @trusted { return strlen(s); } ()); } } private void setSSLError(string msg, string submsg, int line = __LINE__, string file = __FILE__) @trusted nothrow { import std.string : toStringz; ERR_put_error(ERR_LIB_USER, 0, 1, file.toStringz, line); ERR_add_error_data(3, msg.toStringz, ": ".ptr, submsg.toStringz); } private BIO_METHOD s_bio_methods = { 57, "SslStream", &onBioWrite, &onBioRead, &onBioPuts, null, // &onBioGets &onBioCtrl, &onBioNew, &onBioFree, null, // &onBioCallbackCtrl }; private nothrow extern(C): static if (haveALPN) { alias ALPNCallback = int function(SSL *ssl, const(char) **output, ubyte* outlen, const(char) *input, uint inlen, void *arg); void SSL_CTX_set_alpn_select_cb(SSL_CTX *ctx, ALPNCallback cb, void *arg); int SSL_set_alpn_protos(SSL *ssl, const char *data, uint len); int SSL_CTX_set_alpn_protos(SSL_CTX *ctx, const char* protos, uint protos_len); void SSL_get0_alpn_selected(const SSL *ssl, const char* data, uint *len); } const(ssl_method_st)* TLSv1_2_server_method();