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/>.
20 /* $LinkerFlags: -lmbedtls */
23 #include "modules/ssl.h"
25 #include <mbedtls/ctr_drbg.h>
26 #include <mbedtls/dhm.h>
27 #include <mbedtls/ecp.h>
28 #include <mbedtls/entropy.h>
29 #include <mbedtls/error.h>
30 #include <mbedtls/md.h>
31 #include <mbedtls/pk.h>
32 #include <mbedtls/ssl.h>
33 #include <mbedtls/ssl_ciphersuites.h>
34 #include <mbedtls/version.h>
35 #include <mbedtls/x509.h>
36 #include <mbedtls/x509_crt.h>
37 #include <mbedtls/x509_crl.h>
39 #ifdef INSPIRCD_MBEDTLS_LIBRARY_DEBUG
40 #include <mbedtls/debug.h>
45 class Exception : public ModuleException
48 Exception(const std::string& reason)
49 : ModuleException(reason) { }
52 std::string ErrorToString(int errcode)
55 mbedtls_strerror(errcode, buf, sizeof(buf));
59 void ThrowOnError(int errcode, const char* msg)
63 std::string reason = msg;
64 reason.append(" :").append(ErrorToString(errcode));
65 throw Exception(reason);
69 template <typename T, void (*init)(T*), void (*deinit)(T*)>
85 T* get() { return &obj; }
86 const T* get() const { return &obj; }
89 typedef RAIIObj<mbedtls_entropy_context, mbedtls_entropy_init, mbedtls_entropy_free> Entropy;
91 class CTRDRBG : private RAIIObj<mbedtls_ctr_drbg_context, mbedtls_ctr_drbg_init, mbedtls_ctr_drbg_free>
94 bool Seed(Entropy& entropy)
96 return (mbedtls_ctr_drbg_seed(get(), mbedtls_entropy_func, entropy.get(), NULL, 0) == 0);
99 void SetupConf(mbedtls_ssl_config* conf)
101 mbedtls_ssl_conf_rng(conf, mbedtls_ctr_drbg_random, get());
105 class DHParams : public RAIIObj<mbedtls_dhm_context, mbedtls_dhm_init, mbedtls_dhm_free>
108 void set(const std::string& dhstr)
110 // Last parameter is buffer size, must include the terminating null
111 int ret = mbedtls_dhm_parse_dhm(get(), reinterpret_cast<const unsigned char*>(dhstr.c_str()), dhstr.size()+1);
112 ThrowOnError(ret, "Unable to import DH params");
116 class X509Key : public RAIIObj<mbedtls_pk_context, mbedtls_pk_init, mbedtls_pk_free>
120 X509Key(const std::string& keystr)
122 int ret = mbedtls_pk_parse_key(get(), reinterpret_cast<const unsigned char*>(keystr.c_str()), keystr.size()+1, NULL, 0);
123 ThrowOnError(ret, "Unable to import private key");
129 std::vector<int> list;
132 Ciphersuites(const std::string& str)
134 // mbedTLS uses the ciphersuite format "TLS-ECDHE-RSA-WITH-AES-128-GCM-SHA256" internally.
135 // This is a bit verbose, so we make life a bit simpler for admins by not requiring them to supply the static parts.
136 irc::sepstream ss(str, ':');
137 for (std::string token; ss.GetToken(token); )
139 // Prepend "TLS-" if not there
140 if (token.compare(0, 4, "TLS-", 4))
141 token.insert(0, "TLS-");
143 const int id = mbedtls_ssl_get_ciphersuite_id(token.c_str());
145 throw Exception("Unknown ciphersuite " + token);
151 const int* get() const { return &list.front(); }
152 bool empty() const { return (list.size() <= 1); }
157 std::vector<mbedtls_ecp_group_id> list;
160 Curves(const std::string& str)
162 irc::sepstream ss(str, ':');
163 for (std::string token; ss.GetToken(token); )
165 const mbedtls_ecp_curve_info* curve = mbedtls_ecp_curve_info_from_name(token.c_str());
167 throw Exception("Unknown curve " + token);
168 list.push_back(curve->grp_id);
170 list.push_back(MBEDTLS_ECP_DP_NONE);
173 const mbedtls_ecp_group_id* get() const { return &list.front(); }
174 bool empty() const { return (list.size() <= 1); }
177 class X509CertList : public RAIIObj<mbedtls_x509_crt, mbedtls_x509_crt_init, mbedtls_x509_crt_free>
180 /** Import or create empty */
181 X509CertList(const std::string& certstr, bool allowempty = false)
183 if ((allowempty) && (certstr.empty()))
185 int ret = mbedtls_x509_crt_parse(get(), reinterpret_cast<const unsigned char*>(certstr.c_str()), certstr.size()+1);
186 ThrowOnError(ret, "Unable to load certificates");
189 bool empty() const { return (get()->raw.p != NULL); }
192 class X509CRL : public RAIIObj<mbedtls_x509_crl, mbedtls_x509_crl_init, mbedtls_x509_crl_free>
195 X509CRL(const std::string& crlstr)
199 int ret = mbedtls_x509_crl_parse(get(), reinterpret_cast<const unsigned char*>(crlstr.c_str()), crlstr.size()+1);
200 ThrowOnError(ret, "Unable to load CRL");
204 class X509Credentials
210 /** Certificate list, presented to the peer
215 X509Credentials(const std::string& certstr, const std::string& keystr)
219 // Verify that one of the certs match the private key
221 for (mbedtls_x509_crt* cert = certs.get(); cert; cert = cert->next)
223 if (mbedtls_pk_check_pair(&cert->pk, key.get()) == 0)
230 throw Exception("Public/private key pair does not match");
233 mbedtls_pk_context* getkey() { return key.get(); }
234 mbedtls_x509_crt* getcerts() { return certs.get(); }
239 mbedtls_ssl_config conf;
241 #ifdef INSPIRCD_MBEDTLS_LIBRARY_DEBUG
242 static void DebugLogFunc(void* userptr, int level, const char* file, int line, const char* msg)
244 // Remove trailing \n
245 size_t len = strlen(msg);
246 if ((len > 0) && (msg[len-1] == '\n'))
248 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "%s:%d %.*s", file, line, len, msg);
253 Context(CTRDRBG& ctrdrbg, unsigned int endpoint)
255 mbedtls_ssl_config_init(&conf);
256 #ifdef INSPIRCD_MBEDTLS_LIBRARY_DEBUG
257 mbedtls_debug_set_threshold(INT_MAX);
258 mbedtls_ssl_conf_dbg(&conf, DebugLogFunc, NULL);
260 mbedtls_ssl_conf_authmode(&conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
262 // TODO: check ret of mbedtls_ssl_config_defaults
263 mbedtls_ssl_config_defaults(&conf, endpoint, MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT);
264 ctrdrbg.SetupConf(&conf);
269 mbedtls_ssl_config_free(&conf);
272 void SetMinDHBits(unsigned int mindh)
274 mbedtls_ssl_conf_dhm_min_bitlen(&conf, mindh);
277 void SetDHParams(DHParams& dh)
279 mbedtls_ssl_conf_dh_param_ctx(&conf, dh.get());
282 void SetX509CertAndKey(X509Credentials& x509cred)
284 mbedtls_ssl_conf_own_cert(&conf, x509cred.getcerts(), x509cred.getkey());
287 void SetCiphersuites(const Ciphersuites& ciphersuites)
289 mbedtls_ssl_conf_ciphersuites(&conf, ciphersuites.get());
292 void SetCurves(const Curves& curves)
294 mbedtls_ssl_conf_curves(&conf, curves.get());
297 void SetVersion(int minver, int maxver)
299 // SSL v3 support cannot be enabled
301 mbedtls_ssl_conf_min_version(&conf, MBEDTLS_SSL_MAJOR_VERSION_3, minver);
303 mbedtls_ssl_conf_max_version(&conf, MBEDTLS_SSL_MAJOR_VERSION_3, maxver);
306 void SetCA(X509CertList& certs, X509CRL& crl)
308 mbedtls_ssl_conf_ca_chain(&conf, certs.get(), crl.get());
311 const mbedtls_ssl_config* GetConf() const { return &conf; }
316 const mbedtls_md_info_t* md;
318 /** Buffer where cert hashes are written temporarily
320 mutable std::vector<unsigned char> buf;
323 Hash(std::string hashstr)
325 std::transform(hashstr.begin(), hashstr.end(), hashstr.begin(), ::toupper);
326 md = mbedtls_md_info_from_string(hashstr.c_str());
328 throw Exception("Unknown hash: " + hashstr);
330 buf.resize(mbedtls_md_get_size(md));
333 std::string hash(const unsigned char* input, size_t length) const
335 mbedtls_md(md, input, length, &buf.front());
336 return BinToHex(&buf.front(), buf.size());
340 class Profile : public refcountbase
342 /** Name of this profile
344 const std::string name;
346 X509Credentials x509cred;
348 /** Ciphersuites to use
350 Ciphersuites ciphersuites;
352 /** Curves accepted for use in ECDHE and in the peer's end-entity certificate
361 X509CertList cacerts;
365 /** Hashing algorithm to use when generating certificate fingerprints
369 /** Rough max size of records to send
371 const unsigned int outrecsize;
373 Profile(const std::string& profilename, const std::string& certstr, const std::string& keystr,
374 const std::string& dhstr, unsigned int mindh, const std::string& hashstr,
375 const std::string& ciphersuitestr, const std::string& curvestr,
376 const std::string& castr, const std::string& crlstr,
377 unsigned int recsize,
379 int minver, int maxver
382 , x509cred(certstr, keystr)
383 , ciphersuites(ciphersuitestr)
385 , serverctx(ctrdrbg, MBEDTLS_SSL_IS_SERVER)
386 , clientctx(ctrdrbg, MBEDTLS_SSL_IS_CLIENT)
387 , cacerts(castr, true)
390 , outrecsize(recsize)
392 serverctx.SetX509CertAndKey(x509cred);
393 clientctx.SetX509CertAndKey(x509cred);
394 clientctx.SetMinDHBits(mindh);
396 if (!ciphersuites.empty())
398 serverctx.SetCiphersuites(ciphersuites);
399 clientctx.SetCiphersuites(ciphersuites);
404 serverctx.SetCurves(curves);
405 clientctx.SetCurves(curves);
408 serverctx.SetVersion(minver, maxver);
409 clientctx.SetVersion(minver, maxver);
414 serverctx.SetDHParams(dhparams);
417 serverctx.SetCA(cacerts, crl);
420 static std::string ReadFile(const std::string& filename)
422 FileReader reader(filename);
423 std::string ret = reader.GetString();
425 throw Exception("Cannot read file " + filename);
430 static reference<Profile> Create(const std::string& profilename, ConfigTag* tag, CTRDRBG& ctr_drbg)
432 const std::string certstr = ReadFile(tag->getString("certfile", "cert.pem"));
433 const std::string keystr = ReadFile(tag->getString("keyfile", "key.pem"));
434 const std::string dhstr = ReadFile(tag->getString("dhfile", "dhparams.pem"));
436 const std::string ciphersuitestr = tag->getString("ciphersuites");
437 const std::string curvestr = tag->getString("curves");
438 unsigned int mindh = tag->getInt("mindhbits", 2048);
439 std::string hashstr = tag->getString("hash", "sha256");
442 std::string castr = tag->getString("cafile");
445 castr = ReadFile(castr);
446 crlstr = tag->getString("crlfile");
448 crlstr = ReadFile(crlstr);
451 int minver = tag->getInt("minver");
452 int maxver = tag->getInt("maxver");
453 unsigned int outrecsize = tag->getInt("outrecsize", 2048, 512, 16384);
454 return new Profile(profilename, certstr, keystr, dhstr, mindh, hashstr, ciphersuitestr, curvestr, castr, crlstr, outrecsize, ctr_drbg, minver, maxver);
457 /** Set up the given session with the settings in this profile
459 void SetupClientSession(mbedtls_ssl_context* sess)
461 mbedtls_ssl_setup(sess, clientctx.GetConf());
464 void SetupServerSession(mbedtls_ssl_context* sess)
466 mbedtls_ssl_setup(sess, serverctx.GetConf());
469 const std::string& GetName() const { return name; }
470 X509Credentials& GetX509Credentials() { return x509cred; }
471 unsigned int GetOutgoingRecordSize() const { return outrecsize; }
472 const Hash& GetHash() const { return hash; }
476 class mbedTLSIOHook : public SSLIOHook
485 mbedtls_ssl_context sess;
487 reference<mbedTLS::Profile> profile;
491 if (status == ISSL_NONE)
494 mbedtls_ssl_close_notify(&sess);
495 mbedtls_ssl_free(&sess);
500 // Returns 1 if handshake succeeded, 0 if it is still in progress, -1 if it failed
501 int Handshake(StreamSocket* sock)
503 int ret = mbedtls_ssl_handshake(&sess);
506 // Change the seesion state
507 this->status = ISSL_HANDSHAKEN;
511 // Finish writing, if any left
512 SocketEngine::ChangeEventMask(sock, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
517 this->status = ISSL_HANDSHAKING;
518 if (ret == MBEDTLS_ERR_SSL_WANT_READ)
520 SocketEngine::ChangeEventMask(sock, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
523 else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE)
525 SocketEngine::ChangeEventMask(sock, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
529 sock->SetError("Handshake Failed - " + mbedTLS::ErrorToString(ret));
534 // Returns 1 if application I/O should proceed, 0 if it must wait for the underlying protocol to progress, -1 on fatal error
535 int PrepareIO(StreamSocket* sock)
537 if (status == ISSL_HANDSHAKEN)
539 else if (status == ISSL_HANDSHAKING)
541 // The handshake isn't finished, try to finish it
542 return Handshake(sock);
546 sock->SetError("No SSL session");
550 void VerifyCertificate()
552 this->certificate = new ssl_cert;
553 const mbedtls_x509_crt* const cert = mbedtls_ssl_get_peer_cert(&sess);
556 certificate->error = "No client certificate sent";
560 // If there is a certificate we can always generate a fingerprint
561 certificate->fingerprint = profile->GetHash().hash(cert->raw.p, cert->raw.len);
563 // At this point mbedTLS verified the cert already, we just need to check the results
564 const uint32_t flags = mbedtls_ssl_get_verify_result(&sess);
565 if (flags == 0xFFFFFFFF)
567 certificate->error = "Internal error during verification";
573 // Verification succeeded
574 certificate->trusted = true;
578 // Verification failed
579 certificate->trusted = false;
580 if ((flags & MBEDTLS_X509_BADCERT_EXPIRED) || (flags & MBEDTLS_X509_BADCERT_FUTURE))
581 certificate->error = "Not activated, or expired certificate";
584 certificate->unknownsigner = (flags & MBEDTLS_X509_BADCERT_NOT_TRUSTED);
585 certificate->revoked = (flags & MBEDTLS_X509_BADCERT_REVOKED);
586 certificate->invalid = ((flags & MBEDTLS_X509_BADCERT_BAD_KEY) || (flags & MBEDTLS_X509_BADCERT_BAD_MD) || (flags & MBEDTLS_X509_BADCERT_BAD_PK));
588 GetDNString(&cert->subject, certificate->dn);
589 GetDNString(&cert->issuer, certificate->issuer);
592 static void GetDNString(const mbedtls_x509_name* x509name, std::string& out)
595 const int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), x509name);
599 out.assign(buf, ret);
602 static int Pull(void* userptr, unsigned char* buffer, size_t size)
604 StreamSocket* const sock = reinterpret_cast<StreamSocket*>(userptr);
605 if (sock->GetEventMask() & FD_READ_WILL_BLOCK)
606 return MBEDTLS_ERR_SSL_WANT_READ;
608 const int ret = SocketEngine::Recv(sock, reinterpret_cast<char*>(buffer), size, 0);
611 SocketEngine::ChangeEventMask(sock, FD_READ_WILL_BLOCK);
612 if ((ret == -1) && (SocketEngine::IgnoreError()))
613 return MBEDTLS_ERR_SSL_WANT_READ;
618 static int Push(void* userptr, const unsigned char* buffer, size_t size)
620 StreamSocket* const sock = reinterpret_cast<StreamSocket*>(userptr);
621 if (sock->GetEventMask() & FD_WRITE_WILL_BLOCK)
622 return MBEDTLS_ERR_SSL_WANT_WRITE;
624 const int ret = SocketEngine::Send(sock, buffer, size, 0);
627 SocketEngine::ChangeEventMask(sock, FD_WRITE_WILL_BLOCK);
628 if ((ret == -1) && (SocketEngine::IgnoreError()))
629 return MBEDTLS_ERR_SSL_WANT_WRITE;
635 mbedTLSIOHook(IOHookProvider* hookprov, StreamSocket* sock, bool isserver, mbedTLS::Profile* sslprofile)
636 : SSLIOHook(hookprov)
638 , profile(sslprofile)
640 mbedtls_ssl_init(&sess);
642 profile->SetupServerSession(&sess);
644 profile->SetupClientSession(&sess);
646 mbedtls_ssl_set_bio(&sess, reinterpret_cast<void*>(sock), Push, Pull, NULL);
648 sock->AddIOHook(this);
652 void OnStreamSocketClose(StreamSocket* sock) CXX11_OVERRIDE
657 int OnStreamSocketRead(StreamSocket* sock, std::string& recvq) CXX11_OVERRIDE
659 // Finish handshake if needed
660 int prepret = PrepareIO(sock);
664 // If we resumed the handshake then this->status will be ISSL_HANDSHAKEN.
665 char* const readbuf = ServerInstance->GetReadBuffer();
666 const size_t readbufsize = ServerInstance->Config->NetBufferSize;
667 int ret = mbedtls_ssl_read(&sess, reinterpret_cast<unsigned char*>(readbuf), readbufsize);
670 recvq.append(readbuf, ret);
672 // Schedule a read if there is still data in the mbedTLS buffer
673 if (mbedtls_ssl_get_bytes_avail(&sess) > 0)
674 SocketEngine::ChangeEventMask(sock, FD_ADD_TRIAL_READ);
677 else if (ret == MBEDTLS_ERR_SSL_WANT_READ)
679 SocketEngine::ChangeEventMask(sock, FD_WANT_POLL_READ);
682 else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE)
684 SocketEngine::ChangeEventMask(sock, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
689 sock->SetError("Connection closed");
693 else // error or MBEDTLS_ERR_SSL_CLIENT_RECONNECT which we treat as an error
695 sock->SetError(mbedTLS::ErrorToString(ret));
701 int OnStreamSocketWrite(StreamSocket* sock, StreamSocket::SendQueue& sendq) CXX11_OVERRIDE
703 // Finish handshake if needed
704 int prepret = PrepareIO(sock);
708 // Session is ready for transferring application data
709 while (!sendq.empty())
711 FlattenSendQueue(sendq, profile->GetOutgoingRecordSize());
712 const StreamSocket::SendQueue::Element& buffer = sendq.front();
713 int ret = mbedtls_ssl_write(&sess, reinterpret_cast<const unsigned char*>(buffer.data()), buffer.length());
714 if (ret == (int)buffer.length())
716 // Wrote entire record, continue sending
721 sendq.erase_front(ret);
722 SocketEngine::ChangeEventMask(sock, FD_WANT_SINGLE_WRITE);
727 sock->SetError("Connection closed");
731 else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE)
733 SocketEngine::ChangeEventMask(sock, FD_WANT_SINGLE_WRITE);
736 else if (ret == MBEDTLS_ERR_SSL_WANT_READ)
738 SocketEngine::ChangeEventMask(sock, FD_WANT_POLL_READ);
743 sock->SetError(mbedTLS::ErrorToString(ret));
749 SocketEngine::ChangeEventMask(sock, FD_WANT_NO_WRITE);
753 void GetCiphersuite(std::string& out) const CXX11_OVERRIDE
755 if (!IsHandshakeDone())
757 out.append(mbedtls_ssl_get_version(&sess)).push_back('-');
759 // All mbedTLS ciphersuite names currently begin with "TLS-" which provides no useful information so skip it, but be prepared if it changes
760 const char* const ciphersuitestr = mbedtls_ssl_get_ciphersuite(&sess);
761 const char prefix[] = "TLS-";
762 unsigned int skip = sizeof(prefix)-1;
763 if (strncmp(ciphersuitestr, prefix, sizeof(prefix)-1))
765 out.append(ciphersuitestr + skip);
768 bool IsHandshakeDone() const { return (status == ISSL_HANDSHAKEN); }
771 class mbedTLSIOHookProvider : public refcountbase, public IOHookProvider
773 reference<mbedTLS::Profile> profile;
776 mbedTLSIOHookProvider(Module* mod, mbedTLS::Profile* prof)
777 : IOHookProvider(mod, "ssl/" + prof->GetName(), IOHookProvider::IOH_SSL)
780 ServerInstance->Modules->AddService(*this);
783 ~mbedTLSIOHookProvider()
785 ServerInstance->Modules->DelService(*this);
788 void OnAccept(StreamSocket* sock, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) CXX11_OVERRIDE
790 new mbedTLSIOHook(this, sock, true, profile);
793 void OnConnect(StreamSocket* sock) CXX11_OVERRIDE
795 new mbedTLSIOHook(this, sock, false, profile);
799 class ModuleSSLmbedTLS : public Module
801 typedef std::vector<reference<mbedTLSIOHookProvider> > ProfileList;
803 mbedTLS::Entropy entropy;
804 mbedTLS::CTRDRBG ctr_drbg;
805 ProfileList profiles;
809 // First, store all profiles in a new, temporary container. If no problems occur, swap the two
810 // containers; this way if something goes wrong we can go back and continue using the current profiles,
811 // avoiding unpleasant situations where no new SSL connections are possible.
812 ProfileList newprofiles;
814 ConfigTagList tags = ServerInstance->Config->ConfTags("sslprofile");
815 if (tags.first == tags.second)
817 // No <sslprofile> tags found, create a profile named "mbedtls" from settings in the <mbedtls> block
818 const std::string defname = "mbedtls";
819 ConfigTag* tag = ServerInstance->Config->ConfValue(defname);
820 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "No <sslprofile> tags found; using settings from the <mbedtls> tag");
824 reference<mbedTLS::Profile> profile(mbedTLS::Profile::Create(defname, tag, ctr_drbg));
825 newprofiles.push_back(new mbedTLSIOHookProvider(this, profile));
827 catch (CoreException& ex)
829 throw ModuleException("Error while initializing the default SSL profile - " + ex.GetReason());
833 for (ConfigIter i = tags.first; i != tags.second; ++i)
835 ConfigTag* tag = i->second;
836 if (tag->getString("provider") != "mbedtls")
839 std::string name = tag->getString("name");
842 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Ignoring <sslprofile> tag without name at " + tag->getTagLocation());
846 reference<mbedTLS::Profile> profile;
849 profile = mbedTLS::Profile::Create(name, tag, ctr_drbg);
851 catch (CoreException& ex)
853 throw ModuleException("Error while initializing SSL profile \"" + name + "\" at " + tag->getTagLocation() + " - " + ex.GetReason());
856 newprofiles.push_back(new mbedTLSIOHookProvider(this, profile));
859 // New profiles are ok, begin using them
860 // Old profiles are deleted when their refcount drops to zero
861 profiles.swap(newprofiles);
865 void init() CXX11_OVERRIDE
867 char verbuf[16]; // Should be at least 9 bytes in size
868 mbedtls_version_get_string(verbuf);
869 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "mbedTLS lib version %s module was compiled for " MBEDTLS_VERSION_STRING, verbuf);
871 if (!ctr_drbg.Seed(entropy))
872 throw ModuleException("CTR DRBG seed failed");
876 void OnModuleRehash(User* user, const std::string ¶m) CXX11_OVERRIDE
885 catch (ModuleException& ex)
887 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, ex.GetReason() + " Not applying settings.");
891 void OnCleanup(int target_type, void* item) CXX11_OVERRIDE
893 if (target_type != TYPE_USER)
896 LocalUser* user = IS_LOCAL(static_cast<User*>(item));
897 if ((user) && (user->eh.GetIOHook()) && (user->eh.GetIOHook()->prov->creator == this))
899 // User is using SSL, they're a local user, and they're using our IOHook.
900 // Potentially there could be multiple SSL modules loaded at once on different ports.
901 ServerInstance->Users.QuitUser(user, "SSL module unloading");
905 ModResult OnCheckReady(LocalUser* user) CXX11_OVERRIDE
907 if ((user->eh.GetIOHook()) && (user->eh.GetIOHook()->prov->creator == this))
909 mbedTLSIOHook* iohook = static_cast<mbedTLSIOHook*>(user->eh.GetIOHook());
910 if (!iohook->IsHandshakeDone())
914 return MOD_RES_PASSTHRU;
917 Version GetVersion() CXX11_OVERRIDE
919 return Version("Provides SSL support via mbedTLS (PolarSSL)", VF_VENDOR);
923 MODULE_INIT(ModuleSSLmbedTLS)