2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2016 Attila Molnar <attilamolnar@hush.com>
6 * This file is part of InspIRCd. InspIRCd is free software: you can
7 * redistribute it and/or modify it under the terms of the GNU General Public
8 * License as published by the Free Software Foundation, version 2.
10 * This program is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
12 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 /// $LinkerFlags: -lmbedtls
21 /// $PackageInfo: require_system("arch") mbedtls
22 /// $PackageInfo: require_system("darwin") mbedtls
23 /// $PackageInfo: require_system("debian" "9.0") libmbedtls-dev
24 /// $PackageInfo: require_system("ubuntu" "16.04") libmbedtls-dev
28 #include "modules/ssl.h"
30 #include <mbedtls/ctr_drbg.h>
31 #include <mbedtls/dhm.h>
32 #include <mbedtls/ecp.h>
33 #include <mbedtls/entropy.h>
34 #include <mbedtls/error.h>
35 #include <mbedtls/md.h>
36 #include <mbedtls/pk.h>
37 #include <mbedtls/ssl.h>
38 #include <mbedtls/ssl_ciphersuites.h>
39 #include <mbedtls/version.h>
40 #include <mbedtls/x509.h>
41 #include <mbedtls/x509_crt.h>
42 #include <mbedtls/x509_crl.h>
44 #ifdef INSPIRCD_MBEDTLS_LIBRARY_DEBUG
45 #include <mbedtls/debug.h>
50 class Exception : public ModuleException
53 Exception(const std::string& reason)
54 : ModuleException(reason) { }
57 std::string ErrorToString(int errcode)
60 mbedtls_strerror(errcode, buf, sizeof(buf));
64 void ThrowOnError(int errcode, const char* msg)
68 std::string reason = msg;
69 reason.append(" :").append(ErrorToString(errcode));
70 throw Exception(reason);
74 template <typename T, void (*init)(T*), void (*deinit)(T*)>
90 T* get() { return &obj; }
91 const T* get() const { return &obj; }
94 typedef RAIIObj<mbedtls_entropy_context, mbedtls_entropy_init, mbedtls_entropy_free> Entropy;
96 class CTRDRBG : private RAIIObj<mbedtls_ctr_drbg_context, mbedtls_ctr_drbg_init, mbedtls_ctr_drbg_free>
99 bool Seed(Entropy& entropy)
101 return (mbedtls_ctr_drbg_seed(get(), mbedtls_entropy_func, entropy.get(), NULL, 0) == 0);
104 void SetupConf(mbedtls_ssl_config* conf)
106 mbedtls_ssl_conf_rng(conf, mbedtls_ctr_drbg_random, get());
110 class DHParams : public RAIIObj<mbedtls_dhm_context, mbedtls_dhm_init, mbedtls_dhm_free>
113 void set(const std::string& dhstr)
115 // Last parameter is buffer size, must include the terminating null
116 int ret = mbedtls_dhm_parse_dhm(get(), reinterpret_cast<const unsigned char*>(dhstr.c_str()), dhstr.size()+1);
117 ThrowOnError(ret, "Unable to import DH params");
121 class X509Key : public RAIIObj<mbedtls_pk_context, mbedtls_pk_init, mbedtls_pk_free>
125 X509Key(const std::string& keystr)
127 int ret = mbedtls_pk_parse_key(get(), reinterpret_cast<const unsigned char*>(keystr.c_str()), keystr.size()+1, NULL, 0);
128 ThrowOnError(ret, "Unable to import private key");
134 std::vector<int> list;
137 Ciphersuites(const std::string& str)
139 // mbedTLS uses the ciphersuite format "TLS-ECDHE-RSA-WITH-AES-128-GCM-SHA256" internally.
140 // This is a bit verbose, so we make life a bit simpler for admins by not requiring them to supply the static parts.
141 irc::sepstream ss(str, ':');
142 for (std::string token; ss.GetToken(token); )
144 // Prepend "TLS-" if not there
145 if (token.compare(0, 4, "TLS-", 4))
146 token.insert(0, "TLS-");
148 const int id = mbedtls_ssl_get_ciphersuite_id(token.c_str());
150 throw Exception("Unknown ciphersuite " + token);
156 const int* get() const { return &list.front(); }
157 bool empty() const { return (list.size() <= 1); }
162 std::vector<mbedtls_ecp_group_id> list;
165 Curves(const std::string& str)
167 irc::sepstream ss(str, ':');
168 for (std::string token; ss.GetToken(token); )
170 const mbedtls_ecp_curve_info* curve = mbedtls_ecp_curve_info_from_name(token.c_str());
172 throw Exception("Unknown curve " + token);
173 list.push_back(curve->grp_id);
175 list.push_back(MBEDTLS_ECP_DP_NONE);
178 const mbedtls_ecp_group_id* get() const { return &list.front(); }
179 bool empty() const { return (list.size() <= 1); }
182 class X509CertList : public RAIIObj<mbedtls_x509_crt, mbedtls_x509_crt_init, mbedtls_x509_crt_free>
185 /** Import or create empty */
186 X509CertList(const std::string& certstr, bool allowempty = false)
188 if ((allowempty) && (certstr.empty()))
190 int ret = mbedtls_x509_crt_parse(get(), reinterpret_cast<const unsigned char*>(certstr.c_str()), certstr.size()+1);
191 ThrowOnError(ret, "Unable to load certificates");
194 bool empty() const { return (get()->raw.p != NULL); }
197 class X509CRL : public RAIIObj<mbedtls_x509_crl, mbedtls_x509_crl_init, mbedtls_x509_crl_free>
200 X509CRL(const std::string& crlstr)
204 int ret = mbedtls_x509_crl_parse(get(), reinterpret_cast<const unsigned char*>(crlstr.c_str()), crlstr.size()+1);
205 ThrowOnError(ret, "Unable to load CRL");
209 class X509Credentials
215 /** Certificate list, presented to the peer
220 X509Credentials(const std::string& certstr, const std::string& keystr)
224 // Verify that one of the certs match the private key
226 for (mbedtls_x509_crt* cert = certs.get(); cert; cert = cert->next)
228 if (mbedtls_pk_check_pair(&cert->pk, key.get()) == 0)
235 throw Exception("Public/private key pair does not match");
238 mbedtls_pk_context* getkey() { return key.get(); }
239 mbedtls_x509_crt* getcerts() { return certs.get(); }
244 mbedtls_ssl_config conf;
246 #ifdef INSPIRCD_MBEDTLS_LIBRARY_DEBUG
247 static void DebugLogFunc(void* userptr, int level, const char* file, int line, const char* msg)
249 // Remove trailing \n
250 size_t len = strlen(msg);
251 if ((len > 0) && (msg[len-1] == '\n'))
253 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "%s:%d %.*s", file, line, len, msg);
258 Context(CTRDRBG& ctrdrbg, unsigned int endpoint)
260 mbedtls_ssl_config_init(&conf);
261 #ifdef INSPIRCD_MBEDTLS_LIBRARY_DEBUG
262 mbedtls_debug_set_threshold(INT_MAX);
263 mbedtls_ssl_conf_dbg(&conf, DebugLogFunc, NULL);
266 // TODO: check ret of mbedtls_ssl_config_defaults
267 mbedtls_ssl_config_defaults(&conf, endpoint, MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT);
268 ctrdrbg.SetupConf(&conf);
273 mbedtls_ssl_config_free(&conf);
276 void SetMinDHBits(unsigned int mindh)
278 mbedtls_ssl_conf_dhm_min_bitlen(&conf, mindh);
281 void SetDHParams(DHParams& dh)
283 mbedtls_ssl_conf_dh_param_ctx(&conf, dh.get());
286 void SetX509CertAndKey(X509Credentials& x509cred)
288 mbedtls_ssl_conf_own_cert(&conf, x509cred.getcerts(), x509cred.getkey());
291 void SetCiphersuites(const Ciphersuites& ciphersuites)
293 mbedtls_ssl_conf_ciphersuites(&conf, ciphersuites.get());
296 void SetCurves(const Curves& curves)
298 mbedtls_ssl_conf_curves(&conf, curves.get());
301 void SetVersion(int minver, int maxver)
303 // SSL v3 support cannot be enabled
305 mbedtls_ssl_conf_min_version(&conf, MBEDTLS_SSL_MAJOR_VERSION_3, minver);
307 mbedtls_ssl_conf_max_version(&conf, MBEDTLS_SSL_MAJOR_VERSION_3, maxver);
310 void SetCA(X509CertList& certs, X509CRL& crl)
312 mbedtls_ssl_conf_ca_chain(&conf, certs.get(), crl.get());
315 void SetOptionalVerifyCert()
317 mbedtls_ssl_conf_authmode(&conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
320 const mbedtls_ssl_config* GetConf() const { return &conf; }
325 const mbedtls_md_info_t* md;
327 /** Buffer where cert hashes are written temporarily
329 mutable std::vector<unsigned char> buf;
332 Hash(std::string hashstr)
334 std::transform(hashstr.begin(), hashstr.end(), hashstr.begin(), ::toupper);
335 md = mbedtls_md_info_from_string(hashstr.c_str());
337 throw Exception("Unknown hash: " + hashstr);
339 buf.resize(mbedtls_md_get_size(md));
342 std::string hash(const unsigned char* input, size_t length) const
344 mbedtls_md(md, input, length, &buf.front());
345 return BinToHex(&buf.front(), buf.size());
351 /** Name of this profile
353 const std::string name;
355 X509Credentials x509cred;
357 /** Ciphersuites to use
359 Ciphersuites ciphersuites;
361 /** Curves accepted for use in ECDHE and in the peer's end-entity certificate
370 X509CertList cacerts;
374 /** Hashing algorithm to use when generating certificate fingerprints
378 /** Rough max size of records to send
380 const unsigned int outrecsize;
385 const std::string name;
389 const std::string certstr;
390 const std::string keystr;
391 const std::string dhstr;
393 const std::string ciphersuitestr;
394 const std::string curvestr;
395 const unsigned int mindh;
396 const std::string hashstr;
403 const unsigned int outrecsize;
404 const bool requestclientcert;
406 Config(const std::string& profilename, ConfigTag* tag, CTRDRBG& ctr_drbg)
409 , certstr(ReadFile(tag->getString("certfile", "cert.pem")))
410 , keystr(ReadFile(tag->getString("keyfile", "key.pem")))
411 , dhstr(ReadFile(tag->getString("dhfile", "dhparams.pem")))
412 , ciphersuitestr(tag->getString("ciphersuites"))
413 , curvestr(tag->getString("curves"))
414 , mindh(tag->getUInt("mindhbits", 2048))
415 , hashstr(tag->getString("hash", "sha256"))
416 , castr(tag->getString("cafile"))
417 , minver(tag->getUInt("minver", 0))
418 , maxver(tag->getUInt("maxver", 0))
419 , outrecsize(tag->getUInt("outrecsize", 2048, 512, 16384))
420 , requestclientcert(tag->getBool("requestclientcert", true))
424 castr = ReadFile(castr);
425 crlstr = tag->getString("crlfile");
427 crlstr = ReadFile(crlstr);
432 Profile(Config& config)
434 , x509cred(config.certstr, config.keystr)
435 , ciphersuites(config.ciphersuitestr)
436 , curves(config.curvestr)
437 , serverctx(config.ctrdrbg, MBEDTLS_SSL_IS_SERVER)
438 , clientctx(config.ctrdrbg, MBEDTLS_SSL_IS_CLIENT)
439 , cacerts(config.castr, true)
441 , hash(config.hashstr)
442 , outrecsize(config.outrecsize)
444 serverctx.SetX509CertAndKey(x509cred);
445 clientctx.SetX509CertAndKey(x509cred);
446 clientctx.SetMinDHBits(config.mindh);
448 if (!ciphersuites.empty())
450 serverctx.SetCiphersuites(ciphersuites);
451 clientctx.SetCiphersuites(ciphersuites);
456 serverctx.SetCurves(curves);
457 clientctx.SetCurves(curves);
460 serverctx.SetVersion(config.minver, config.maxver);
461 clientctx.SetVersion(config.minver, config.maxver);
463 if (!config.dhstr.empty())
465 dhparams.set(config.dhstr);
466 serverctx.SetDHParams(dhparams);
469 clientctx.SetOptionalVerifyCert();
470 clientctx.SetCA(cacerts, crl);
471 // The default for servers is to not request a client certificate from the peer
472 if (config.requestclientcert)
474 serverctx.SetOptionalVerifyCert();
475 serverctx.SetCA(cacerts, crl);
479 static std::string ReadFile(const std::string& filename)
481 FileReader reader(filename);
482 std::string ret = reader.GetString();
484 throw Exception("Cannot read file " + filename);
488 /** Set up the given session with the settings in this profile
490 void SetupClientSession(mbedtls_ssl_context* sess)
492 mbedtls_ssl_setup(sess, clientctx.GetConf());
495 void SetupServerSession(mbedtls_ssl_context* sess)
497 mbedtls_ssl_setup(sess, serverctx.GetConf());
500 const std::string& GetName() const { return name; }
501 X509Credentials& GetX509Credentials() { return x509cred; }
502 unsigned int GetOutgoingRecordSize() const { return outrecsize; }
503 const Hash& GetHash() const { return hash; }
507 class mbedTLSIOHook : public SSLIOHook
516 mbedtls_ssl_context sess;
521 if (status == ISSL_NONE)
524 mbedtls_ssl_close_notify(&sess);
525 mbedtls_ssl_free(&sess);
530 // Returns 1 if handshake succeeded, 0 if it is still in progress, -1 if it failed
531 int Handshake(StreamSocket* sock)
533 int ret = mbedtls_ssl_handshake(&sess);
536 // Change the seesion state
537 this->status = ISSL_HANDSHAKEN;
541 // Finish writing, if any left
542 SocketEngine::ChangeEventMask(sock, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
547 this->status = ISSL_HANDSHAKING;
548 if (ret == MBEDTLS_ERR_SSL_WANT_READ)
550 SocketEngine::ChangeEventMask(sock, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
553 else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE)
555 SocketEngine::ChangeEventMask(sock, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
559 sock->SetError("Handshake Failed - " + mbedTLS::ErrorToString(ret));
564 // Returns 1 if application I/O should proceed, 0 if it must wait for the underlying protocol to progress, -1 on fatal error
565 int PrepareIO(StreamSocket* sock)
567 if (status == ISSL_HANDSHAKEN)
569 else if (status == ISSL_HANDSHAKING)
571 // The handshake isn't finished, try to finish it
572 return Handshake(sock);
576 sock->SetError("No SSL session");
580 void VerifyCertificate()
582 this->certificate = new ssl_cert;
583 const mbedtls_x509_crt* const cert = mbedtls_ssl_get_peer_cert(&sess);
586 certificate->error = "No client certificate sent";
590 // If there is a certificate we can always generate a fingerprint
591 certificate->fingerprint = GetProfile().GetHash().hash(cert->raw.p, cert->raw.len);
593 // At this point mbedTLS verified the cert already, we just need to check the results
594 const uint32_t flags = mbedtls_ssl_get_verify_result(&sess);
595 if (flags == 0xFFFFFFFF)
597 certificate->error = "Internal error during verification";
603 // Verification succeeded
604 certificate->trusted = true;
608 // Verification failed
609 certificate->trusted = false;
610 if ((flags & MBEDTLS_X509_BADCERT_EXPIRED) || (flags & MBEDTLS_X509_BADCERT_FUTURE))
611 certificate->error = "Not activated, or expired certificate";
614 certificate->unknownsigner = (flags & MBEDTLS_X509_BADCERT_NOT_TRUSTED);
615 certificate->revoked = (flags & MBEDTLS_X509_BADCERT_REVOKED);
616 certificate->invalid = ((flags & MBEDTLS_X509_BADCERT_BAD_KEY) || (flags & MBEDTLS_X509_BADCERT_BAD_MD) || (flags & MBEDTLS_X509_BADCERT_BAD_PK));
618 GetDNString(&cert->subject, certificate->dn);
619 GetDNString(&cert->issuer, certificate->issuer);
622 static void GetDNString(const mbedtls_x509_name* x509name, std::string& out)
625 const int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), x509name);
629 out.assign(buf, ret);
632 static int Pull(void* userptr, unsigned char* buffer, size_t size)
634 StreamSocket* const sock = reinterpret_cast<StreamSocket*>(userptr);
635 if (sock->GetEventMask() & FD_READ_WILL_BLOCK)
636 return MBEDTLS_ERR_SSL_WANT_READ;
638 const int ret = SocketEngine::Recv(sock, reinterpret_cast<char*>(buffer), size, 0);
641 SocketEngine::ChangeEventMask(sock, FD_READ_WILL_BLOCK);
642 if ((ret == -1) && (SocketEngine::IgnoreError()))
643 return MBEDTLS_ERR_SSL_WANT_READ;
648 static int Push(void* userptr, const unsigned char* buffer, size_t size)
650 StreamSocket* const sock = reinterpret_cast<StreamSocket*>(userptr);
651 if (sock->GetEventMask() & FD_WRITE_WILL_BLOCK)
652 return MBEDTLS_ERR_SSL_WANT_WRITE;
654 const int ret = SocketEngine::Send(sock, buffer, size, 0);
657 SocketEngine::ChangeEventMask(sock, FD_WRITE_WILL_BLOCK);
658 if ((ret == -1) && (SocketEngine::IgnoreError()))
659 return MBEDTLS_ERR_SSL_WANT_WRITE;
665 mbedTLSIOHook(IOHookProvider* hookprov, StreamSocket* sock, bool isserver)
666 : SSLIOHook(hookprov)
669 mbedtls_ssl_init(&sess);
671 GetProfile().SetupServerSession(&sess);
673 GetProfile().SetupClientSession(&sess);
675 mbedtls_ssl_set_bio(&sess, reinterpret_cast<void*>(sock), Push, Pull, NULL);
677 sock->AddIOHook(this);
681 void OnStreamSocketClose(StreamSocket* sock) CXX11_OVERRIDE
686 int OnStreamSocketRead(StreamSocket* sock, std::string& recvq) CXX11_OVERRIDE
688 // Finish handshake if needed
689 int prepret = PrepareIO(sock);
693 // If we resumed the handshake then this->status will be ISSL_HANDSHAKEN.
694 char* const readbuf = ServerInstance->GetReadBuffer();
695 const size_t readbufsize = ServerInstance->Config->NetBufferSize;
696 int ret = mbedtls_ssl_read(&sess, reinterpret_cast<unsigned char*>(readbuf), readbufsize);
699 recvq.append(readbuf, ret);
701 // Schedule a read if there is still data in the mbedTLS buffer
702 if (mbedtls_ssl_get_bytes_avail(&sess) > 0)
703 SocketEngine::ChangeEventMask(sock, FD_ADD_TRIAL_READ);
706 else if (ret == MBEDTLS_ERR_SSL_WANT_READ)
708 SocketEngine::ChangeEventMask(sock, FD_WANT_POLL_READ);
711 else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE)
713 SocketEngine::ChangeEventMask(sock, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
718 sock->SetError("Connection closed");
722 else // error or MBEDTLS_ERR_SSL_CLIENT_RECONNECT which we treat as an error
724 sock->SetError(mbedTLS::ErrorToString(ret));
730 int OnStreamSocketWrite(StreamSocket* sock, StreamSocket::SendQueue& sendq) CXX11_OVERRIDE
732 // Finish handshake if needed
733 int prepret = PrepareIO(sock);
737 // Session is ready for transferring application data
738 while (!sendq.empty())
740 FlattenSendQueue(sendq, GetProfile().GetOutgoingRecordSize());
741 const StreamSocket::SendQueue::Element& buffer = sendq.front();
742 int ret = mbedtls_ssl_write(&sess, reinterpret_cast<const unsigned char*>(buffer.data()), buffer.length());
743 if (ret == (int)buffer.length())
745 // Wrote entire record, continue sending
750 sendq.erase_front(ret);
751 SocketEngine::ChangeEventMask(sock, FD_WANT_SINGLE_WRITE);
756 sock->SetError("Connection closed");
760 else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE)
762 SocketEngine::ChangeEventMask(sock, FD_WANT_SINGLE_WRITE);
765 else if (ret == MBEDTLS_ERR_SSL_WANT_READ)
767 SocketEngine::ChangeEventMask(sock, FD_WANT_POLL_READ);
772 sock->SetError(mbedTLS::ErrorToString(ret));
778 SocketEngine::ChangeEventMask(sock, FD_WANT_NO_WRITE);
782 void GetCiphersuite(std::string& out) const CXX11_OVERRIDE
784 if (!IsHandshakeDone())
786 out.append(mbedtls_ssl_get_version(&sess)).push_back('-');
788 // All mbedTLS ciphersuite names currently begin with "TLS-" which provides no useful information so skip it, but be prepared if it changes
789 const char* const ciphersuitestr = mbedtls_ssl_get_ciphersuite(&sess);
790 const char prefix[] = "TLS-";
791 unsigned int skip = sizeof(prefix)-1;
792 if (strncmp(ciphersuitestr, prefix, sizeof(prefix)-1))
794 out.append(ciphersuitestr + skip);
797 bool GetServerName(std::string& out) const CXX11_OVERRIDE
799 // TODO: Implement SNI support.
803 mbedTLS::Profile& GetProfile();
804 bool IsHandshakeDone() const { return (status == ISSL_HANDSHAKEN); }
807 class mbedTLSIOHookProvider : public IOHookProvider
809 mbedTLS::Profile profile;
812 mbedTLSIOHookProvider(Module* mod, mbedTLS::Profile::Config& config)
813 : IOHookProvider(mod, "ssl/" + config.name, IOHookProvider::IOH_SSL)
816 ServerInstance->Modules->AddService(*this);
819 ~mbedTLSIOHookProvider()
821 ServerInstance->Modules->DelService(*this);
824 void OnAccept(StreamSocket* sock, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) CXX11_OVERRIDE
826 new mbedTLSIOHook(this, sock, true);
829 void OnConnect(StreamSocket* sock) CXX11_OVERRIDE
831 new mbedTLSIOHook(this, sock, false);
834 mbedTLS::Profile& GetProfile() { return profile; }
837 mbedTLS::Profile& mbedTLSIOHook::GetProfile()
839 IOHookProvider* hookprov = prov;
840 return static_cast<mbedTLSIOHookProvider*>(hookprov)->GetProfile();
843 class ModuleSSLmbedTLS : public Module
845 typedef std::vector<reference<mbedTLSIOHookProvider> > ProfileList;
847 mbedTLS::Entropy entropy;
848 mbedTLS::CTRDRBG ctr_drbg;
849 ProfileList profiles;
853 // First, store all profiles in a new, temporary container. If no problems occur, swap the two
854 // containers; this way if something goes wrong we can go back and continue using the current profiles,
855 // avoiding unpleasant situations where no new SSL connections are possible.
856 ProfileList newprofiles;
858 ConfigTagList tags = ServerInstance->Config->ConfTags("sslprofile");
859 if (tags.first == tags.second)
861 // No <sslprofile> tags found, create a profile named "mbedtls" from settings in the <mbedtls> block
862 const std::string defname = "mbedtls";
863 ConfigTag* tag = ServerInstance->Config->ConfValue(defname);
864 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "No <sslprofile> tags found; using settings from the <mbedtls> tag");
868 mbedTLS::Profile::Config profileconfig(defname, tag, ctr_drbg);
869 newprofiles.push_back(new mbedTLSIOHookProvider(this, profileconfig));
871 catch (CoreException& ex)
873 throw ModuleException("Error while initializing the default SSL profile - " + ex.GetReason());
877 for (ConfigIter i = tags.first; i != tags.second; ++i)
879 ConfigTag* tag = i->second;
880 if (!stdalgo::string::equalsci(tag->getString("provider"), "mbedtls"))
883 std::string name = tag->getString("name");
886 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Ignoring <sslprofile> tag without name at " + tag->getTagLocation());
890 reference<mbedTLSIOHookProvider> prov;
893 mbedTLS::Profile::Config profileconfig(name, tag, ctr_drbg);
894 prov = new mbedTLSIOHookProvider(this, profileconfig);
896 catch (CoreException& ex)
898 throw ModuleException("Error while initializing SSL profile \"" + name + "\" at " + tag->getTagLocation() + " - " + ex.GetReason());
901 newprofiles.push_back(prov);
904 // New profiles are ok, begin using them
905 // Old profiles are deleted when their refcount drops to zero
906 for (ProfileList::iterator i = profiles.begin(); i != profiles.end(); ++i)
908 mbedTLSIOHookProvider& prov = **i;
909 ServerInstance->Modules.DelService(prov);
912 profiles.swap(newprofiles);
916 void init() CXX11_OVERRIDE
918 char verbuf[16]; // Should be at least 9 bytes in size
919 mbedtls_version_get_string(verbuf);
920 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "mbedTLS lib version %s module was compiled for " MBEDTLS_VERSION_STRING, verbuf);
922 if (!ctr_drbg.Seed(entropy))
923 throw ModuleException("CTR DRBG seed failed");
927 void OnModuleRehash(User* user, const std::string ¶m) CXX11_OVERRIDE
936 catch (ModuleException& ex)
938 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, ex.GetReason() + " Not applying settings.");
942 void OnCleanup(ExtensionItem::ExtensibleType type, Extensible* item) CXX11_OVERRIDE
944 if (type != ExtensionItem::EXT_USER)
947 LocalUser* user = IS_LOCAL(static_cast<User*>(item));
948 if ((user) && (user->eh.GetModHook(this)))
950 // User is using SSL, they're a local user, and they're using our IOHook.
951 // Potentially there could be multiple SSL modules loaded at once on different ports.
952 ServerInstance->Users.QuitUser(user, "SSL module unloading");
956 ModResult OnCheckReady(LocalUser* user) CXX11_OVERRIDE
958 const mbedTLSIOHook* const iohook = static_cast<mbedTLSIOHook*>(user->eh.GetModHook(this));
959 if ((iohook) && (!iohook->IsHandshakeDone()))
961 return MOD_RES_PASSTHRU;
964 Version GetVersion() CXX11_OVERRIDE
966 return Version("Provides SSL support via mbedTLS (PolarSSL)", VF_VENDOR);
970 MODULE_INIT(ModuleSSLmbedTLS)