2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2019 Matt Schatz <genius3000@g3k.solutions>
5 * Copyright (C) 2016-2019 Sadie Powell <sadie@witchery.services>
6 * Copyright (C) 2016-2017 Attila Molnar <attilamolnar@hush.com>
8 * This file is part of InspIRCd. InspIRCd is free software: you can
9 * redistribute it and/or modify it under the terms of the GNU General Public
10 * License as published by the Free Software Foundation, version 2.
12 * This program is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21 /// $LinkerFlags: -lmbedtls
23 /// $PackageInfo: require_system("arch") mbedtls
24 /// $PackageInfo: require_system("darwin") mbedtls
25 /// $PackageInfo: require_system("debian" "9.0") libmbedtls-dev
26 /// $PackageInfo: require_system("ubuntu" "16.04") libmbedtls-dev
30 #include "modules/ssl.h"
32 #include <mbedtls/ctr_drbg.h>
33 #include <mbedtls/dhm.h>
34 #include <mbedtls/ecp.h>
35 #include <mbedtls/entropy.h>
36 #include <mbedtls/error.h>
37 #include <mbedtls/md.h>
38 #include <mbedtls/pk.h>
39 #include <mbedtls/ssl.h>
40 #include <mbedtls/ssl_ciphersuites.h>
41 #include <mbedtls/version.h>
42 #include <mbedtls/x509.h>
43 #include <mbedtls/x509_crt.h>
44 #include <mbedtls/x509_crl.h>
46 #ifdef INSPIRCD_MBEDTLS_LIBRARY_DEBUG
47 #include <mbedtls/debug.h>
52 class Exception : public ModuleException
55 Exception(const std::string& reason)
56 : ModuleException(reason) { }
59 std::string ErrorToString(int errcode)
62 mbedtls_strerror(errcode, buf, sizeof(buf));
66 void ThrowOnError(int errcode, const char* msg)
70 std::string reason = msg;
71 reason.append(" :").append(ErrorToString(errcode));
72 throw Exception(reason);
76 template <typename T, void (*init)(T*), void (*deinit)(T*)>
92 T* get() { return &obj; }
93 const T* get() const { return &obj; }
96 typedef RAIIObj<mbedtls_entropy_context, mbedtls_entropy_init, mbedtls_entropy_free> Entropy;
98 class CTRDRBG : private RAIIObj<mbedtls_ctr_drbg_context, mbedtls_ctr_drbg_init, mbedtls_ctr_drbg_free>
101 bool Seed(Entropy& entropy)
103 return (mbedtls_ctr_drbg_seed(get(), mbedtls_entropy_func, entropy.get(), NULL, 0) == 0);
106 void SetupConf(mbedtls_ssl_config* conf)
108 mbedtls_ssl_conf_rng(conf, mbedtls_ctr_drbg_random, get());
112 class DHParams : public RAIIObj<mbedtls_dhm_context, mbedtls_dhm_init, mbedtls_dhm_free>
115 void set(const std::string& dhstr)
117 // Last parameter is buffer size, must include the terminating null
118 int ret = mbedtls_dhm_parse_dhm(get(), reinterpret_cast<const unsigned char*>(dhstr.c_str()), dhstr.size()+1);
119 ThrowOnError(ret, "Unable to import DH params");
123 class X509Key : public RAIIObj<mbedtls_pk_context, mbedtls_pk_init, mbedtls_pk_free>
127 X509Key(const std::string& keystr)
129 int ret = mbedtls_pk_parse_key(get(), reinterpret_cast<const unsigned char*>(keystr.c_str()), keystr.size()+1, NULL, 0);
130 ThrowOnError(ret, "Unable to import private key");
136 std::vector<int> list;
139 Ciphersuites(const std::string& str)
141 // mbedTLS uses the ciphersuite format "TLS-ECDHE-RSA-WITH-AES-128-GCM-SHA256" internally.
142 // This is a bit verbose, so we make life a bit simpler for admins by not requiring them to supply the static parts.
143 irc::sepstream ss(str, ':');
144 for (std::string token; ss.GetToken(token); )
146 // Prepend "TLS-" if not there
147 if (token.compare(0, 4, "TLS-", 4))
148 token.insert(0, "TLS-");
150 const int id = mbedtls_ssl_get_ciphersuite_id(token.c_str());
152 throw Exception("Unknown ciphersuite " + token);
158 const int* get() const { return &list.front(); }
159 bool empty() const { return (list.size() <= 1); }
164 std::vector<mbedtls_ecp_group_id> list;
167 Curves(const std::string& str)
169 irc::sepstream ss(str, ':');
170 for (std::string token; ss.GetToken(token); )
172 const mbedtls_ecp_curve_info* curve = mbedtls_ecp_curve_info_from_name(token.c_str());
174 throw Exception("Unknown curve " + token);
175 list.push_back(curve->grp_id);
177 list.push_back(MBEDTLS_ECP_DP_NONE);
180 const mbedtls_ecp_group_id* get() const { return &list.front(); }
181 bool empty() const { return (list.size() <= 1); }
184 class X509CertList : public RAIIObj<mbedtls_x509_crt, mbedtls_x509_crt_init, mbedtls_x509_crt_free>
187 /** Import or create empty */
188 X509CertList(const std::string& certstr, bool allowempty = false)
190 if ((allowempty) && (certstr.empty()))
192 int ret = mbedtls_x509_crt_parse(get(), reinterpret_cast<const unsigned char*>(certstr.c_str()), certstr.size()+1);
193 ThrowOnError(ret, "Unable to load certificates");
196 bool empty() const { return (get()->raw.p != NULL); }
199 class X509CRL : public RAIIObj<mbedtls_x509_crl, mbedtls_x509_crl_init, mbedtls_x509_crl_free>
202 X509CRL(const std::string& crlstr)
206 int ret = mbedtls_x509_crl_parse(get(), reinterpret_cast<const unsigned char*>(crlstr.c_str()), crlstr.size()+1);
207 ThrowOnError(ret, "Unable to load CRL");
211 class X509Credentials
217 /** Certificate list, presented to the peer
222 X509Credentials(const std::string& certstr, const std::string& keystr)
226 // Verify that one of the certs match the private key
228 for (mbedtls_x509_crt* cert = certs.get(); cert; cert = cert->next)
230 if (mbedtls_pk_check_pair(&cert->pk, key.get()) == 0)
237 throw Exception("Public/private key pair does not match");
240 mbedtls_pk_context* getkey() { return key.get(); }
241 mbedtls_x509_crt* getcerts() { return certs.get(); }
246 mbedtls_ssl_config conf;
248 #ifdef INSPIRCD_MBEDTLS_LIBRARY_DEBUG
249 static void DebugLogFunc(void* userptr, int level, const char* file, int line, const char* msg)
251 // Remove trailing \n
252 size_t len = strlen(msg);
253 if ((len > 0) && (msg[len-1] == '\n'))
255 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "%s:%d %.*s", file, line, len, msg);
260 Context(CTRDRBG& ctrdrbg, unsigned int endpoint)
262 mbedtls_ssl_config_init(&conf);
263 #ifdef INSPIRCD_MBEDTLS_LIBRARY_DEBUG
264 mbedtls_debug_set_threshold(INT_MAX);
265 mbedtls_ssl_conf_dbg(&conf, DebugLogFunc, NULL);
268 // TODO: check ret of mbedtls_ssl_config_defaults
269 mbedtls_ssl_config_defaults(&conf, endpoint, MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT);
270 ctrdrbg.SetupConf(&conf);
275 mbedtls_ssl_config_free(&conf);
278 void SetMinDHBits(unsigned int mindh)
280 mbedtls_ssl_conf_dhm_min_bitlen(&conf, mindh);
283 void SetDHParams(DHParams& dh)
285 mbedtls_ssl_conf_dh_param_ctx(&conf, dh.get());
288 void SetX509CertAndKey(X509Credentials& x509cred)
290 mbedtls_ssl_conf_own_cert(&conf, x509cred.getcerts(), x509cred.getkey());
293 void SetCiphersuites(const Ciphersuites& ciphersuites)
295 mbedtls_ssl_conf_ciphersuites(&conf, ciphersuites.get());
298 void SetCurves(const Curves& curves)
300 mbedtls_ssl_conf_curves(&conf, curves.get());
303 void SetVersion(int minver, int maxver)
305 // SSL v3 support cannot be enabled
307 mbedtls_ssl_conf_min_version(&conf, MBEDTLS_SSL_MAJOR_VERSION_3, minver);
309 mbedtls_ssl_conf_max_version(&conf, MBEDTLS_SSL_MAJOR_VERSION_3, maxver);
312 void SetCA(X509CertList& certs, X509CRL& crl)
314 mbedtls_ssl_conf_ca_chain(&conf, certs.get(), crl.get());
317 void SetOptionalVerifyCert()
319 mbedtls_ssl_conf_authmode(&conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
322 const mbedtls_ssl_config* GetConf() const { return &conf; }
327 const mbedtls_md_info_t* md;
329 /** Buffer where cert hashes are written temporarily
331 mutable std::vector<unsigned char> buf;
334 Hash(std::string hashstr)
336 std::transform(hashstr.begin(), hashstr.end(), hashstr.begin(), ::toupper);
337 md = mbedtls_md_info_from_string(hashstr.c_str());
339 throw Exception("Unknown hash: " + hashstr);
341 buf.resize(mbedtls_md_get_size(md));
344 std::string hash(const unsigned char* input, size_t length) const
346 mbedtls_md(md, input, length, &buf.front());
347 return BinToHex(&buf.front(), buf.size());
353 /** Name of this profile
355 const std::string name;
357 X509Credentials x509cred;
359 /** Ciphersuites to use
361 Ciphersuites ciphersuites;
363 /** Curves accepted for use in ECDHE and in the peer's end-entity certificate
372 X509CertList cacerts;
376 /** Hashing algorithm to use when generating certificate fingerprints
380 /** Rough max size of records to send
382 const unsigned int outrecsize;
387 const std::string name;
391 const std::string certstr;
392 const std::string keystr;
393 const std::string dhstr;
395 const std::string ciphersuitestr;
396 const std::string curvestr;
397 const unsigned int mindh;
398 const std::string hashstr;
405 const unsigned int outrecsize;
406 const bool requestclientcert;
408 Config(const std::string& profilename, ConfigTag* tag, CTRDRBG& ctr_drbg)
411 , certstr(ReadFile(tag->getString("certfile", "cert.pem")))
412 , keystr(ReadFile(tag->getString("keyfile", "key.pem")))
413 , dhstr(ReadFile(tag->getString("dhfile", "dhparams.pem")))
414 , ciphersuitestr(tag->getString("ciphersuites"))
415 , curvestr(tag->getString("curves"))
416 , mindh(tag->getUInt("mindhbits", 2048))
417 , hashstr(tag->getString("hash", "sha256"))
418 , castr(tag->getString("cafile"))
419 , minver(tag->getUInt("minver", 0))
420 , maxver(tag->getUInt("maxver", 0))
421 , outrecsize(tag->getUInt("outrecsize", 2048, 512, 16384))
422 , requestclientcert(tag->getBool("requestclientcert", true))
426 castr = ReadFile(castr);
427 crlstr = tag->getString("crlfile");
429 crlstr = ReadFile(crlstr);
434 Profile(Config& config)
436 , x509cred(config.certstr, config.keystr)
437 , ciphersuites(config.ciphersuitestr)
438 , curves(config.curvestr)
439 , serverctx(config.ctrdrbg, MBEDTLS_SSL_IS_SERVER)
440 , clientctx(config.ctrdrbg, MBEDTLS_SSL_IS_CLIENT)
441 , cacerts(config.castr, true)
443 , hash(config.hashstr)
444 , outrecsize(config.outrecsize)
446 serverctx.SetX509CertAndKey(x509cred);
447 clientctx.SetX509CertAndKey(x509cred);
448 clientctx.SetMinDHBits(config.mindh);
450 if (!ciphersuites.empty())
452 serverctx.SetCiphersuites(ciphersuites);
453 clientctx.SetCiphersuites(ciphersuites);
458 serverctx.SetCurves(curves);
459 clientctx.SetCurves(curves);
462 serverctx.SetVersion(config.minver, config.maxver);
463 clientctx.SetVersion(config.minver, config.maxver);
465 if (!config.dhstr.empty())
467 dhparams.set(config.dhstr);
468 serverctx.SetDHParams(dhparams);
471 clientctx.SetOptionalVerifyCert();
472 clientctx.SetCA(cacerts, crl);
473 // The default for servers is to not request a client certificate from the peer
474 if (config.requestclientcert)
476 serverctx.SetOptionalVerifyCert();
477 serverctx.SetCA(cacerts, crl);
481 static std::string ReadFile(const std::string& filename)
483 FileReader reader(filename);
484 std::string ret = reader.GetString();
486 throw Exception("Cannot read file " + filename);
490 /** Set up the given session with the settings in this profile
492 void SetupClientSession(mbedtls_ssl_context* sess)
494 mbedtls_ssl_setup(sess, clientctx.GetConf());
497 void SetupServerSession(mbedtls_ssl_context* sess)
499 mbedtls_ssl_setup(sess, serverctx.GetConf());
502 const std::string& GetName() const { return name; }
503 X509Credentials& GetX509Credentials() { return x509cred; }
504 unsigned int GetOutgoingRecordSize() const { return outrecsize; }
505 const Hash& GetHash() const { return hash; }
509 class mbedTLSIOHook : public SSLIOHook
518 mbedtls_ssl_context sess;
523 if (status == ISSL_NONE)
526 mbedtls_ssl_close_notify(&sess);
527 mbedtls_ssl_free(&sess);
532 // Returns 1 if handshake succeeded, 0 if it is still in progress, -1 if it failed
533 int Handshake(StreamSocket* sock)
535 int ret = mbedtls_ssl_handshake(&sess);
538 // Change the seesion state
539 this->status = ISSL_HANDSHAKEN;
543 // Finish writing, if any left
544 SocketEngine::ChangeEventMask(sock, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
549 this->status = ISSL_HANDSHAKING;
550 if (ret == MBEDTLS_ERR_SSL_WANT_READ)
552 SocketEngine::ChangeEventMask(sock, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
555 else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE)
557 SocketEngine::ChangeEventMask(sock, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
561 sock->SetError("Handshake Failed - " + mbedTLS::ErrorToString(ret));
566 // Returns 1 if application I/O should proceed, 0 if it must wait for the underlying protocol to progress, -1 on fatal error
567 int PrepareIO(StreamSocket* sock)
569 if (status == ISSL_HANDSHAKEN)
571 else if (status == ISSL_HANDSHAKING)
573 // The handshake isn't finished, try to finish it
574 return Handshake(sock);
578 sock->SetError("No SSL session");
582 void VerifyCertificate()
584 this->certificate = new ssl_cert;
585 const mbedtls_x509_crt* const cert = mbedtls_ssl_get_peer_cert(&sess);
588 certificate->error = "No client certificate sent";
592 // If there is a certificate we can always generate a fingerprint
593 certificate->fingerprint = GetProfile().GetHash().hash(cert->raw.p, cert->raw.len);
595 // At this point mbedTLS verified the cert already, we just need to check the results
596 const uint32_t flags = mbedtls_ssl_get_verify_result(&sess);
597 if (flags == 0xFFFFFFFF)
599 certificate->error = "Internal error during verification";
605 // Verification succeeded
606 certificate->trusted = true;
610 // Verification failed
611 certificate->trusted = false;
612 if ((flags & MBEDTLS_X509_BADCERT_EXPIRED) || (flags & MBEDTLS_X509_BADCERT_FUTURE))
613 certificate->error = "Not activated, or expired certificate";
616 certificate->unknownsigner = (flags & MBEDTLS_X509_BADCERT_NOT_TRUSTED);
617 certificate->revoked = (flags & MBEDTLS_X509_BADCERT_REVOKED);
618 certificate->invalid = ((flags & MBEDTLS_X509_BADCERT_BAD_KEY) || (flags & MBEDTLS_X509_BADCERT_BAD_MD) || (flags & MBEDTLS_X509_BADCERT_BAD_PK));
620 GetDNString(&cert->subject, certificate->dn);
621 GetDNString(&cert->issuer, certificate->issuer);
624 static void GetDNString(const mbedtls_x509_name* x509name, std::string& out)
627 const int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), x509name);
631 out.assign(buf, ret);
634 static int Pull(void* userptr, unsigned char* buffer, size_t size)
636 StreamSocket* const sock = reinterpret_cast<StreamSocket*>(userptr);
637 if (sock->GetEventMask() & FD_READ_WILL_BLOCK)
638 return MBEDTLS_ERR_SSL_WANT_READ;
640 const int ret = SocketEngine::Recv(sock, reinterpret_cast<char*>(buffer), size, 0);
643 SocketEngine::ChangeEventMask(sock, FD_READ_WILL_BLOCK);
644 if ((ret == -1) && (SocketEngine::IgnoreError()))
645 return MBEDTLS_ERR_SSL_WANT_READ;
650 static int Push(void* userptr, const unsigned char* buffer, size_t size)
652 StreamSocket* const sock = reinterpret_cast<StreamSocket*>(userptr);
653 if (sock->GetEventMask() & FD_WRITE_WILL_BLOCK)
654 return MBEDTLS_ERR_SSL_WANT_WRITE;
656 const int ret = SocketEngine::Send(sock, buffer, size, 0);
659 SocketEngine::ChangeEventMask(sock, FD_WRITE_WILL_BLOCK);
660 if ((ret == -1) && (SocketEngine::IgnoreError()))
661 return MBEDTLS_ERR_SSL_WANT_WRITE;
667 mbedTLSIOHook(IOHookProvider* hookprov, StreamSocket* sock, bool isserver)
668 : SSLIOHook(hookprov)
671 mbedtls_ssl_init(&sess);
673 GetProfile().SetupServerSession(&sess);
675 GetProfile().SetupClientSession(&sess);
677 mbedtls_ssl_set_bio(&sess, reinterpret_cast<void*>(sock), Push, Pull, NULL);
679 sock->AddIOHook(this);
683 void OnStreamSocketClose(StreamSocket* sock) CXX11_OVERRIDE
688 int OnStreamSocketRead(StreamSocket* sock, std::string& recvq) CXX11_OVERRIDE
690 // Finish handshake if needed
691 int prepret = PrepareIO(sock);
695 // If we resumed the handshake then this->status will be ISSL_HANDSHAKEN.
696 char* const readbuf = ServerInstance->GetReadBuffer();
697 const size_t readbufsize = ServerInstance->Config->NetBufferSize;
698 int ret = mbedtls_ssl_read(&sess, reinterpret_cast<unsigned char*>(readbuf), readbufsize);
701 recvq.append(readbuf, ret);
703 // Schedule a read if there is still data in the mbedTLS buffer
704 if (mbedtls_ssl_get_bytes_avail(&sess) > 0)
705 SocketEngine::ChangeEventMask(sock, FD_ADD_TRIAL_READ);
708 else if (ret == MBEDTLS_ERR_SSL_WANT_READ)
710 SocketEngine::ChangeEventMask(sock, FD_WANT_POLL_READ);
713 else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE)
715 SocketEngine::ChangeEventMask(sock, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
720 sock->SetError("Connection closed");
724 else // error or MBEDTLS_ERR_SSL_CLIENT_RECONNECT which we treat as an error
726 sock->SetError(mbedTLS::ErrorToString(ret));
732 int OnStreamSocketWrite(StreamSocket* sock, StreamSocket::SendQueue& sendq) CXX11_OVERRIDE
734 // Finish handshake if needed
735 int prepret = PrepareIO(sock);
739 // Session is ready for transferring application data
740 while (!sendq.empty())
742 FlattenSendQueue(sendq, GetProfile().GetOutgoingRecordSize());
743 const StreamSocket::SendQueue::Element& buffer = sendq.front();
744 int ret = mbedtls_ssl_write(&sess, reinterpret_cast<const unsigned char*>(buffer.data()), buffer.length());
745 if (ret == (int)buffer.length())
747 // Wrote entire record, continue sending
752 sendq.erase_front(ret);
753 SocketEngine::ChangeEventMask(sock, FD_WANT_SINGLE_WRITE);
758 sock->SetError("Connection closed");
762 else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE)
764 SocketEngine::ChangeEventMask(sock, FD_WANT_SINGLE_WRITE);
767 else if (ret == MBEDTLS_ERR_SSL_WANT_READ)
769 SocketEngine::ChangeEventMask(sock, FD_WANT_POLL_READ);
774 sock->SetError(mbedTLS::ErrorToString(ret));
780 SocketEngine::ChangeEventMask(sock, FD_WANT_NO_WRITE);
784 void GetCiphersuite(std::string& out) const CXX11_OVERRIDE
786 if (!IsHandshakeDone())
788 out.append(mbedtls_ssl_get_version(&sess)).push_back('-');
790 // All mbedTLS ciphersuite names currently begin with "TLS-" which provides no useful information so skip it, but be prepared if it changes
791 const char* const ciphersuitestr = mbedtls_ssl_get_ciphersuite(&sess);
792 const char prefix[] = "TLS-";
793 unsigned int skip = sizeof(prefix)-1;
794 if (strncmp(ciphersuitestr, prefix, sizeof(prefix)-1))
796 out.append(ciphersuitestr + skip);
799 bool GetServerName(std::string& out) const CXX11_OVERRIDE
801 // TODO: Implement SNI support.
805 mbedTLS::Profile& GetProfile();
806 bool IsHandshakeDone() const { return (status == ISSL_HANDSHAKEN); }
809 class mbedTLSIOHookProvider : public IOHookProvider
811 mbedTLS::Profile profile;
814 mbedTLSIOHookProvider(Module* mod, mbedTLS::Profile::Config& config)
815 : IOHookProvider(mod, "ssl/" + config.name, IOHookProvider::IOH_SSL)
818 ServerInstance->Modules->AddService(*this);
821 ~mbedTLSIOHookProvider()
823 ServerInstance->Modules->DelService(*this);
826 void OnAccept(StreamSocket* sock, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) CXX11_OVERRIDE
828 new mbedTLSIOHook(this, sock, true);
831 void OnConnect(StreamSocket* sock) CXX11_OVERRIDE
833 new mbedTLSIOHook(this, sock, false);
836 mbedTLS::Profile& GetProfile() { return profile; }
839 mbedTLS::Profile& mbedTLSIOHook::GetProfile()
841 IOHookProvider* hookprov = prov;
842 return static_cast<mbedTLSIOHookProvider*>(hookprov)->GetProfile();
845 class ModuleSSLmbedTLS : public Module
847 typedef std::vector<reference<mbedTLSIOHookProvider> > ProfileList;
849 mbedTLS::Entropy entropy;
850 mbedTLS::CTRDRBG ctr_drbg;
851 ProfileList profiles;
855 // First, store all profiles in a new, temporary container. If no problems occur, swap the two
856 // containers; this way if something goes wrong we can go back and continue using the current profiles,
857 // avoiding unpleasant situations where no new SSL connections are possible.
858 ProfileList newprofiles;
860 ConfigTagList tags = ServerInstance->Config->ConfTags("sslprofile");
861 if (tags.first == tags.second)
863 // No <sslprofile> tags found, create a profile named "mbedtls" from settings in the <mbedtls> block
864 const std::string defname = "mbedtls";
865 ConfigTag* tag = ServerInstance->Config->ConfValue(defname);
866 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "No <sslprofile> tags found; using settings from the <mbedtls> tag");
870 mbedTLS::Profile::Config profileconfig(defname, tag, ctr_drbg);
871 newprofiles.push_back(new mbedTLSIOHookProvider(this, profileconfig));
873 catch (CoreException& ex)
875 throw ModuleException("Error while initializing the default SSL profile - " + ex.GetReason());
879 for (ConfigIter i = tags.first; i != tags.second; ++i)
881 ConfigTag* tag = i->second;
882 if (!stdalgo::string::equalsci(tag->getString("provider"), "mbedtls"))
885 std::string name = tag->getString("name");
888 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Ignoring <sslprofile> tag without name at " + tag->getTagLocation());
892 reference<mbedTLSIOHookProvider> prov;
895 mbedTLS::Profile::Config profileconfig(name, tag, ctr_drbg);
896 prov = new mbedTLSIOHookProvider(this, profileconfig);
898 catch (CoreException& ex)
900 throw ModuleException("Error while initializing SSL profile \"" + name + "\" at " + tag->getTagLocation() + " - " + ex.GetReason());
903 newprofiles.push_back(prov);
906 // New profiles are ok, begin using them
907 // Old profiles are deleted when their refcount drops to zero
908 for (ProfileList::iterator i = profiles.begin(); i != profiles.end(); ++i)
910 mbedTLSIOHookProvider& prov = **i;
911 ServerInstance->Modules.DelService(prov);
914 profiles.swap(newprofiles);
918 void init() CXX11_OVERRIDE
920 char verbuf[16]; // Should be at least 9 bytes in size
921 mbedtls_version_get_string(verbuf);
922 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "mbedTLS lib version %s module was compiled for " MBEDTLS_VERSION_STRING, verbuf);
924 if (!ctr_drbg.Seed(entropy))
925 throw ModuleException("CTR DRBG seed failed");
929 void OnModuleRehash(User* user, const std::string ¶m) CXX11_OVERRIDE
931 if (!irc::equals(param, "ssl"))
937 ServerInstance->SNO->WriteToSnoMask('a', "SSL module %s rehashed.", MODNAME);
939 catch (ModuleException& ex)
941 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, ex.GetReason() + " Not applying settings.");
945 void OnCleanup(ExtensionItem::ExtensibleType type, Extensible* item) CXX11_OVERRIDE
947 if (type != ExtensionItem::EXT_USER)
950 LocalUser* user = IS_LOCAL(static_cast<User*>(item));
951 if ((user) && (user->eh.GetModHook(this)))
953 // User is using SSL, they're a local user, and they're using our IOHook.
954 // Potentially there could be multiple SSL modules loaded at once on different ports.
955 ServerInstance->Users.QuitUser(user, "SSL module unloading");
959 ModResult OnCheckReady(LocalUser* user) CXX11_OVERRIDE
961 const mbedTLSIOHook* const iohook = static_cast<mbedTLSIOHook*>(user->eh.GetModHook(this));
962 if ((iohook) && (!iohook->IsHandshakeDone()))
964 return MOD_RES_PASSTHRU;
967 Version GetVersion() CXX11_OVERRIDE
969 return Version("Provides SSL support via mbedTLS (PolarSSL)", VF_VENDOR);
973 MODULE_INIT(ModuleSSLmbedTLS)