vibe.stream.botan 0/0(100%) 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
/** Botan TLS implementation Copyright: © 2015 RejectedSoftware e.K., GlobecSys Inc Authors: Sönke Ludwig, Etienne Cimon License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file. */ module vibe.stream.botan; version(Have_botan): version = X509; import botan.constants; import botan.cert.x509.x509cert; import botan.cert.x509.certstor; import botan.cert.x509.x509path; import botan.math.bigint.bigint; import botan.tls.blocking; import botan.tls.channel; import botan.tls.credentials_manager; import botan.tls.exceptn; import botan.tls.server; import botan.tls.session_manager; import botan.tls.server_info; import botan.tls.ciphersuite; import botan.rng.auto_rng; import vibe.core.stream; import vibe.stream.tls; import vibe.core.net; import vibe.internal.interfaceproxy : InterfaceProxy; import std.datetime; import std.exception; class BotanTLSStream : TLSStream/*, Buffered*/ { @safe: private { InterfaceProxy!Stream m_stream; TLSBlockingChannel m_tlsChannel; BotanTLSContext m_ctx; OnAlert m_alertCB; OnHandshakeComplete m_handshakeComplete; TLSCiphersuite m_cipher; TLSProtocolVersion m_ver; SysTime m_session_age; X509Certificate m_peer_cert; TLSCertificateInformation m_cert_compat; ubyte[] m_sess_id; Exception m_ex; } /// Returns the date/time the session was started @property SysTime started() const { return m_session_age; } /// Get the session ID @property const(ubyte[]) sessionId() { return m_sess_id; } /// Returns the remote public certificate from the chain @property const(X509Certificate) x509Certificate() const @system { return m_peer_cert; } /// Returns the negotiated version of the TLS Protocol @property TLSProtocolVersion protocol() const { return m_ver; } /// Returns the complete ciphersuite details from the negotiated TLS connection @property TLSCiphersuite cipher() const { return m_cipher; } @property string alpn() const @trusted { return m_tlsChannel.underlyingChannel().applicationProtocol(); } @property TLSCertificateInformation peerCertificate() { import vibe.core.log : logWarn; if (!!m_peer_cert) logWarn("BotanTLSStream.peerCertificate is not implemented and does not return the actual certificate information."); return TLSCertificateInformation.init; } // Constructs a new TLS Client Stream and connects with the specified handlers this(InterfaceProxy!Stream underlying, BotanTLSContext ctx, void delegate(in TLSAlert alert, in ubyte[] ub) alert_cb, bool delegate(in TLSSession session) hs_cb, string peer_name = null, NetworkAddress peer_address = NetworkAddress.init) @trusted { m_ctx = ctx; m_stream = underlying; m_alertCB = alert_cb; m_handshakeComplete = hs_cb; assert(m_ctx.m_kind == TLSContextKind.client, "Connecting through a server context is not supported"); // todo: add service name? TLSServerInformation server_info = TLSServerInformation(peer_name, peer_address.port); m_tlsChannel = TLSBlockingChannel(&onRead, &onWrite, &onAlert, &onHandhsakeComplete, m_ctx.m_sessionManager, m_ctx.m_credentials, m_ctx.m_policy, m_ctx.m_rng, server_info, m_ctx.m_offer_version, m_ctx.m_clientOffers.dup); try m_tlsChannel.doHandshake(); catch (Exception e) { m_ex = e; } } // This constructor is used by the TLS Context for both server and client streams this(InterfaceProxy!Stream underlying, BotanTLSContext ctx, TLSStreamState state, string peer_name = null, NetworkAddress peer_address = NetworkAddress.init) @trusted { m_ctx = ctx; m_stream = underlying; if (state == TLSStreamState.accepting) { assert(m_ctx.m_kind != TLSContextKind.client, "Accepting through a client context is not supported"); m_tlsChannel = TLSBlockingChannel(&onRead, &onWrite, &onAlert, &onHandhsakeComplete, m_ctx.m_sessionManager, m_ctx.m_credentials, m_ctx.m_policy, m_ctx.m_rng, &m_ctx.nextProtocolHandler, &m_ctx.sniHandler, m_ctx.m_is_datagram); } else if (state == TLSStreamState.connecting) { assert(m_ctx.m_kind == TLSContextKind.client, "Connecting through a server context is not supported"); // todo: add service name? TLSServerInformation server_info = TLSServerInformation(peer_name, peer_address.port); m_tlsChannel = TLSBlockingChannel(&onRead, &onWrite, &onAlert, &onHandhsakeComplete, m_ctx.m_sessionManager, m_ctx.m_credentials, m_ctx.m_policy, m_ctx.m_rng, server_info, m_ctx.m_offer_version, m_ctx.m_clientOffers.dup); } else /*if (state == TLSStreamState.connected)*/ { m_tlsChannel = TLSBlockingChannel.init; throw new Exception("Cannot load BotanTLSSteam from a connected TLS session"); } try m_tlsChannel.doHandshake(); catch (Exception e) { m_ex = e; } } ~this() @trusted { try m_tlsChannel.destroy(); catch (Exception e) { } } void flush() { processException(); m_stream.flush(); } void finalize() { if (() @trusted { return m_tlsChannel.isClosed(); } ()) return; processException(); scope(success) processException(); () @trusted { m_tlsChannel.close(); } (); m_stream.flush(); } size_t read(scope ubyte[] dst, IOMode) { processException(); scope(success) processException(); () @trusted { m_tlsChannel.read(dst); } (); return dst.length; } alias read = Stream.read; ubyte[] readChunk(ubyte[] buf) { processException(); scope(success) processException(); return () @trusted { return m_tlsChannel.readBuf(buf); } (); } size_t write(in ubyte[] src, IOMode) { processException(); scope(success) processException(); () @trusted { m_tlsChannel.write(src); } (); return src.length; } alias write = Stream.write; @property bool empty() { processException(); return leastSize() == 0; } @property ulong leastSize() { size_t ret = () @trusted { return m_tlsChannel.pending(); } (); if (ret > 0) return ret; if (() @trusted { return m_tlsChannel.isClosed(); } () || m_ex !is null) return 0; try () @trusted { m_tlsChannel.readBuf(null); } (); // force an exchange catch (Exception e) { return 0; } ret = () @trusted { return m_tlsChannel.pending(); } (); //logDebug("Least size returned: ", ret); return ret > 0 ? ret : m_stream.empty ? 0 : 1; } @property bool dataAvailableForRead() { processException(); if (() @trusted { return m_tlsChannel.pending(); } () > 0) return true; if (!m_stream.dataAvailableForRead) return false; () @trusted { m_tlsChannel.readBuf(null); } (); // force an exchange return () @trusted { return m_tlsChannel.pending(); } () > 0; } const(ubyte)[] peek() { processException(); auto peeked = () @trusted { return m_tlsChannel.peek(); } (); //logDebug("Peeked data: ", cast(ubyte[])peeked); //logDebug("Peeked data ptr: ", peeked.ptr); return peeked; } void setAlertCallback(OnAlert alert_cb) @system { processException(); m_alertCB = alert_cb; } void setHandshakeCallback(OnHandshakeComplete hs_cb) @system { processException(); m_handshakeComplete = hs_cb; } private void processException() @safe { if (auto ex = m_ex) { m_ex = null; throw ex; } } private void onAlert(in TLSAlert alert, in ubyte[] data) @trusted { if (alert.isFatal) m_ex = new Exception("TLS Alert Received: " ~ alert.typeString()); if (m_alertCB) m_alertCB(alert, data); } private bool onHandhsakeComplete(in TLSSession session) @trusted { m_sess_id = cast(ubyte[])session.sessionId()[].dup; m_cipher = session.ciphersuite(); m_session_age = session.startTime(); m_ver = session.Version(); if (session.peerCerts().length > 0) m_peer_cert = session.peerCerts()[0]; if (m_handshakeComplete) return m_handshakeComplete(session); return true; } private ubyte[] onRead(ubyte[] buf) { import std.algorithm : min; ubyte[] ret; /*if (auto buffered = cast(Buffered)m_stream) { ret = buffered.readChunk(buf); return ret; }*/ size_t len = min(m_stream.leastSize(), buf.length); if (len == 0) return null; m_stream.read(buf[0 .. len]); return buf[0 .. len]; } private void onWrite(in ubyte[] src) { //logDebug("Write: %s", src); m_stream.write(src); } } class BotanTLSContext : TLSContext { private { TLSSessionManager m_sessionManager; TLSPolicy m_policy; TLSCredentialsManager m_credentials; TLSContextKind m_kind; AutoSeededRNG m_rng; TLSProtocolVersion m_offer_version; TLSServerNameCallback m_sniCallback; TLSALPNCallback m_serverCb; Vector!string m_clientOffers; bool m_is_datagram; bool m_certChecked; } this(TLSContextKind kind, TLSCredentialsManager credentials = null, TLSPolicy policy = null, TLSSessionManager session_manager = null, bool is_datagram = false) @trusted { if (!credentials) credentials = new CustomTLSCredentials(); m_kind = kind; m_credentials = credentials; m_is_datagram = is_datagram; if (is_datagram) m_offer_version = TLSProtocolVersion.DTLS_V12; else m_offer_version = TLSProtocolVersion.TLS_V12; m_rng = new AutoSeededRNG(); if (!session_manager) session_manager = new TLSSessionManagerInMemory(m_rng); m_sessionManager = session_manager; if (!policy) { if (!gs_default_policy) gs_default_policy = new CustomTLSPolicy(); policy = cast(TLSPolicy)gs_default_policy; } m_policy = policy; } /// The kind of TLS context (client/server) @property TLSContextKind kind() const { return m_kind; } /// Used by clients to indicate protocol preference, use TLSPolicy to restrict the protocol versions @property void defaultProtocolOffer(TLSProtocolVersion ver) { m_offer_version = ver; } /// ditto @property TLSProtocolVersion defaultProtocolOffer() { return m_offer_version; } @property void sniCallback(TLSServerNameCallback callback) { m_sniCallback = callback; } @property inout(TLSServerNameCallback) sniCallback() inout { return m_sniCallback; } /// Callback function invoked by server to choose alpn @property void alpnCallback(TLSALPNCallback alpn_chooser) { m_serverCb = alpn_chooser; } /// Get the current ALPN callback function @property TLSALPNCallback alpnCallback() const { return m_serverCb; } /// Invoked by client to offer alpn, all strings are copied on the GC @property void setClientALPN(string[] alpn_list) { () @trusted { m_clientOffers.clear(); } (); foreach (alpn; alpn_list) () @trusted { m_clientOffers ~= alpn.idup; } (); } /** Creates a new stream associated to this context. */ TLSStream createStream(InterfaceProxy!Stream underlying, TLSStreamState state, string peer_name = null, NetworkAddress peer_address = NetworkAddress.init) { if (!m_certChecked) () @trusted { checkCert(); } (); return new BotanTLSStream(underlying, this, state, peer_name, peer_address); } /** 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) { if (auto credentials = cast(CustomTLSCredentials)m_credentials) { credentials.m_validationMode = mode; return; } else assert(false, "Cannot handle peerValidationMode if CustomTLSCredentials is not used"); } /// ditto @property TLSPeerValidationMode peerValidationMode() const { if (auto credentials = cast(const(CustomTLSCredentials))m_credentials) { return credentials.m_validationMode; } else assert(false, "Cannot handle peerValidationMode if CustomTLSCredentials is not used"); } /** An optional user callback for peer validation. Peer validation callback is unused in Botan. Specify a custom TLS Policy to handle peer certificate data. */ @property void peerValidationCallback(TLSPeerValidationCallback callback) { assert(false, "Peer validation callback is unused in Botan. Specify a custom TLS Policy to handle peer certificate data."); } /// ditto @property inout(TLSPeerValidationCallback) peerValidationCallback() inout { return TLSPeerValidationCallback.init; } /** The maximum length of an accepted certificate chain. Any certificate chain longer than this will result in the TLS negitiation failing. The default value is 9. */ @property void maxCertChainLength(int val) { if (auto credentials = cast(CustomTLSCredentials)m_credentials) { credentials.m_max_cert_chain_length = val; return; } else assert(false, "Cannot handle maxCertChainLength if CustomTLSCredentials is not used"); } /// ditto @property int maxCertChainLength() const { if (auto credentials = cast(const(CustomTLSCredentials))m_credentials) { return credentials.m_max_cert_chain_length; } else assert(false, "Cannot handle maxCertChainLength if CustomTLSCredentials is not used"); } void setCipherList(string list = null) { assert(false, "Incompatible interface method requested"); } /** 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) { assert(false, "Incompatible interface method requested"); } /** 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) { assert(false, "Incompatible interface method requested"); } /// Sets a certificate file to use for authenticating to the remote peer void useCertificateChainFile(string path) { if (auto credentials = cast(CustomTLSCredentials)m_credentials) { m_certChecked = false; () @trusted { credentials.m_server_cert = X509Certificate(path); } (); return; } else assert(false, "Cannot handle useCertificateChainFile if CustomTLSCredentials is not used"); } /// Sets the private key to use for authenticating to the remote peer based /// on the configured certificate chain file. /// todo: Use passphrase? void usePrivateKeyFile(string path) { if (auto credentials = cast(CustomTLSCredentials)m_credentials) { import botan.pubkey.pkcs8 : loadKey; credentials.m_key = () @trusted { return loadKey(path, m_rng); } (); return; } else assert(false, "Cannot handle usePrivateKeyFile if CustomTLSCredentials is not used"); } /** 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) { if (auto credentials = cast(CustomTLSCredentials)m_credentials) { auto store = () @trusted { return new CertificateStoreInMemory; } (); () @trusted { store.addCertificate(X509Certificate(path)); } (); () @trusted { credentials.m_stores.pushBack(store); } (); return; } else assert(false, "Cannot handle useTrustedCertificateFile if CustomTLSCredentials is not used"); } private SNIContextSwitchInfo sniHandler(string hostname) { auto ctx = onSNI(hostname); if (!ctx) return SNIContextSwitchInfo.init; SNIContextSwitchInfo chgctx; chgctx.session_manager = ctx.m_sessionManager; chgctx.credentials = ctx.m_credentials; chgctx.policy = ctx.m_policy; chgctx.next_proto = &ctx.nextProtocolHandler; //chgctx.user_data = cast(void*)hostname.toStringz(); return chgctx; } private string nextProtocolHandler(in Vector!string offers) { enforce(m_kind == TLSContextKind.server, "Attempted ALPN selection on a " ~ m_kind.to!string); if (m_serverCb !is null) return m_serverCb(offers[]); else return ""; } private BotanTLSContext onSNI(string hostname) { if (m_kind != TLSContextKind.serverSNI) return null; TLSContext ctx = m_sniCallback(hostname); if (auto bctx = cast(BotanTLSContext) ctx) { // Since this happens in a BotanTLSStream, the stream info (r/w callback) remains the same return bctx; } // We cannot use anything else than a Botan stream, and any null value with serverSNI is a failure throw new Exception("Could not find specified hostname"); } private void checkCert() { m_certChecked = true; if (m_kind == TLSContextKind.client) return; if (auto creds = cast(CustomTLSCredentials) m_credentials) { auto sigs = m_policy.allowedSignatureMethods(); import botan.asn1.oids : OIDS; import vibe.core.log : logDebug; auto sig_algo = OIDS.lookup(creds.m_server_cert.signatureAlgorithm().oid()); import std.range : front; import std.algorithm.iteration : splitter; string sig_algo_str = sig_algo.splitter("/").front.to!string; logDebug("Certificate algorithm: %s", sig_algo_str); bool found; foreach (sig; sigs[]) { if (sig == sig_algo_str) { found = true; break; } } assert(found, "Server Certificate uses a signing algorithm that is not accepted in the server policy."); } } } /** * TLS Policy as a settings object */ private class CustomTLSPolicy : TLSPolicy { private { TLSProtocolVersion m_min_ver = TLSProtocolVersion.TLS_V10; int m_min_dh_group_size = 1024; Vector!TLSCiphersuite m_pri_ciphersuites; Vector!string m_pri_ecc_curves; Duration m_session_lifetime = 24.hours; bool m_pri_ciphers_exclusive; bool m_pri_curves_exclusive; } /// Sets the minimum acceptable protocol version @property void minProtocolVersion(TLSProtocolVersion ver) { m_min_ver = ver; } /// Get the minimum acceptable protocol version @property TLSProtocolVersion minProtocolVersion() { return m_min_ver; } @property void minDHGroupSize(int sz) { m_min_dh_group_size = sz; } @property int minDHGroupSize() { return m_min_dh_group_size; } /// Add a cipher suite to the priority ciphers with lowest ordering value void addPriorityCiphersuites(TLSCiphersuite[] suites) { m_pri_ciphersuites ~= suites; } @property TLSCiphersuite[] ciphers() { return m_pri_ciphersuites[]; } /// Set to true to use excuslively priority ciphers passed through "addCiphersuites" @property void priorityCiphersOnly(bool b) { m_pri_ciphers_exclusive = b; } @property bool priorityCiphersOnly() { return m_pri_ciphers_exclusive; } void addPriorityCurves(string[] curves) { m_pri_ecc_curves ~= curves; } @property string[] priorityCurves() { return m_pri_ecc_curves[]; } /// Uses only priority curves passed through "add" @property void priorityCurvesOnly(bool b) { m_pri_curves_exclusive = b; } @property bool priorityCurvesOnly() { return m_pri_curves_exclusive; } override string chooseCurve(in Vector!string curve_names) const { import std.algorithm : countUntil; foreach (curve; m_pri_ecc_curves[]) { if (curve_names[].countUntil(curve) != -1) return curve; } if (!m_pri_curves_exclusive) return super.chooseCurve((cast(Vector!string)curve_names).move); return ""; } override Vector!string allowedEccCurves() const { Vector!string ret; if (!m_pri_ecc_curves.empty) ret ~= m_pri_ecc_curves[]; if (!m_pri_curves_exclusive) ret ~= super.allowedEccCurves(); return ret; } override Vector!ushort ciphersuiteList(TLSProtocolVersion _version, bool have_srp) const { Vector!ushort ret; if (m_pri_ciphersuites.length > 0) { foreach (suite; m_pri_ciphersuites) { ret ~= suite.ciphersuiteCode(); } } if (!m_pri_ciphers_exclusive) { ret ~= super.ciphersuiteList(_version, have_srp); } return ret; } override bool acceptableProtocolVersion(TLSProtocolVersion _version) const { if (m_min_ver != TLSProtocolVersion.init) return _version >= m_min_ver; return super.acceptableProtocolVersion(_version); } override Duration sessionTicketLifetime() const { return m_session_lifetime; } override size_t minimumDhGroupSize() const { return m_min_dh_group_size; } } private class CustomTLSCredentials : TLSCredentialsManager { private { TLSPeerValidationMode m_validationMode = TLSPeerValidationMode.none; int m_max_cert_chain_length = 9; } public { X509Certificate m_server_cert, m_ca_cert; PrivateKey m_key; Vector!CertificateStore m_stores; } this() { } // Client constructor this(TLSPeerValidationMode validation_mode = TLSPeerValidationMode.checkPeer) { m_validationMode = validation_mode; } // Server constructor this(X509Certificate server_cert, X509Certificate ca_cert, PrivateKey server_key) { m_server_cert = server_cert; m_ca_cert = ca_cert; m_key = server_key; auto store = new CertificateStoreInMemory; store.addCertificate(m_ca_cert); m_stores.pushBack(store); m_validationMode = TLSPeerValidationMode.none; } override Vector!CertificateStore trustedCertificateAuthorities(in string, in string) { // todo: Check machine stores for client mode return m_stores.dup; } override Vector!X509Certificate certChain(const ref Vector!string cert_key_types, in string type, in string) { Vector!X509Certificate chain; if (type == "tls-server") { bool have_match = false; foreach (cert_key_type; cert_key_types[]) { if (cert_key_type == m_key.algoName) { enforce(m_server_cert, "Private Key was defined but no corresponding server certificate was found."); have_match = true; } } if (have_match) { chain.pushBack(m_server_cert); if (m_ca_cert) chain.pushBack(m_ca_cert); } } return chain.move(); } override void verifyCertificateChain(in string type, in string purported_hostname, const ref Vector!X509Certificate cert_chain) { if (cert_chain.empty) throw new InvalidArgument("Certificate chain was empty"); if (m_validationMode == TLSPeerValidationMode.validCert) { auto trusted_CAs = trustedCertificateAuthorities(type, purported_hostname); PathValidationRestrictions restrictions; restrictions.maxCertChainLength = m_max_cert_chain_length; auto result = x509PathValidate(cert_chain, restrictions, trusted_CAs); if (!result.successfulValidation()) throw new Exception("Certificate validation failure: " ~ result.resultString()); if (!certInSomeStore(trusted_CAs, result.trustRoot())) throw new Exception("Certificate chain roots in unknown/untrusted CA"); if (purported_hostname != "" && !cert_chain[0].matchesDnsName(purported_hostname)) throw new Exception("Certificate did not match hostname"); return; } if (m_validationMode & TLSPeerValidationMode.checkTrust) { auto trusted_CAs = trustedCertificateAuthorities(type, purported_hostname); PathValidationRestrictions restrictions; restrictions.maxCertChainLength = m_max_cert_chain_length; PathValidationResult result; try result = x509PathValidate(cert_chain, restrictions, trusted_CAs); catch (Exception e) { } if (!certInSomeStore(trusted_CAs, result.trustRoot())) throw new Exception("Certificate chain roots in unknown/untrusted CA"); } // Commit to basic tests for other validation modes if (m_validationMode & TLSPeerValidationMode.checkCert) { import botan.asn1.asn1_time : X509Time; X509Time current_time = X509Time(Clock.currTime()); // Check all certs for valid time range if (current_time < X509Time(cert_chain[0].startTime())) throw new Exception("Certificate is not yet valid"); if (current_time > X509Time(cert_chain[0].endTime())) throw new Exception("Certificate has expired"); if (cert_chain[0].isSelfSigned()) throw new Exception("Certificate was self signed"); } if (m_validationMode & TLSPeerValidationMode.checkPeer) if (purported_hostname != "" && !cert_chain[0].matchesDnsName(purported_hostname)) throw new Exception("Certificate did not match hostname"); } override PrivateKey privateKeyFor(in X509Certificate, in string, in string) { return m_key; } // Interface fallthrough override Vector!X509Certificate certChainSingleType(in string cert_key_type, in string type, in string context) { return super.certChainSingleType(cert_key_type, type, context); } override bool attemptSrp(in string type, in string context) { return super.attemptSrp(type, context); } override string srpIdentifier(in string type, in string context) { return super.srpIdentifier(type, context); } override string srpPassword(in string type, in string context, in string identifier) { return super.srpPassword(type, context, identifier); } override bool srpVerifier(in string type, in string context, in string identifier, ref string group_name, ref BigInt verifier, ref Vector!ubyte salt, bool generate_fake_on_unknown) { return super.srpVerifier(type, context, identifier, group_name, verifier, salt, generate_fake_on_unknown); } override string pskIdentityHint(in string type, in string context) { return super.pskIdentityHint(type, context); } override string pskIdentity(in string type, in string context, in string identity_hint) { return super.pskIdentity(type, context, identity_hint); } override SymmetricKey psk(in string type, in string context, in string identity) { return super.psk(type, context, identity); } override bool hasPsk() { return super.hasPsk(); } } private CustomTLSCredentials createCreds() { import botan.rng.auto_rng; import botan.cert.x509.pkcs10; import botan.cert.x509.x509self; import botan.cert.x509.x509_ca; import botan.pubkey.algo.rsa; import botan.codec.hex; import botan.utils.types; scope rng = new AutoSeededRNG(); auto ca_key = RSAPrivateKey(rng, 1024); scope(exit) ca_key.destroy(); X509CertOptions ca_opts; ca_opts.common_name = "Test CA"; ca_opts.country = "US"; ca_opts.CAKey(1); X509Certificate ca_cert = x509self.createSelfSignedCert(ca_opts, *ca_key, "SHA-256", rng); auto server_key = RSAPrivateKey(rng, 1024); X509CertOptions server_opts; server_opts.common_name = "localhost"; server_opts.country = "US"; PKCS10Request req = x509self.createCertReq(server_opts, *server_key, "SHA-256", rng); X509CA ca = X509CA(ca_cert, *ca_key, "SHA-256"); auto now = Clock.currTime(UTC()); X509Time start_time = X509Time(now); X509Time end_time = X509Time(now + 365.days); X509Certificate server_cert = ca.signRequest(req, rng, start_time, end_time); return new CustomTLSCredentials(server_cert, ca_cert, server_key.release()); } private { __gshared CustomTLSPolicy gs_default_policy; }