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("darwin") mbedtls
22 /// $PackageInfo: require_system("debian" "9.0") libmbedtls-dev
23 /// $PackageInfo: require_system("ubuntu" "16.04") libmbedtls-dev
27 #include "modules/ssl.h"
29 #include <mbedtls/ctr_drbg.h>
30 #include <mbedtls/dhm.h>
31 #include <mbedtls/ecp.h>
32 #include <mbedtls/entropy.h>
33 #include <mbedtls/error.h>
34 #include <mbedtls/md.h>
35 #include <mbedtls/pk.h>
36 #include <mbedtls/ssl.h>
37 #include <mbedtls/ssl_ciphersuites.h>
38 #include <mbedtls/version.h>
39 #include <mbedtls/x509.h>
40 #include <mbedtls/x509_crt.h>
41 #include <mbedtls/x509_crl.h>
43 #ifdef INSPIRCD_MBEDTLS_LIBRARY_DEBUG
44 #include <mbedtls/debug.h>
49 class Exception : public ModuleException
52 Exception(const std::string& reason)
53 : ModuleException(reason) { }
56 std::string ErrorToString(int errcode)
59 mbedtls_strerror(errcode, buf, sizeof(buf));
63 void ThrowOnError(int errcode, const char* msg)
67 std::string reason = msg;
68 reason.append(" :").append(ErrorToString(errcode));
69 throw Exception(reason);
73 template <typename T, void (*init)(T*), void (*deinit)(T*)>
89 T* get() { return &obj; }
90 const T* get() const { return &obj; }
93 typedef RAIIObj<mbedtls_entropy_context, mbedtls_entropy_init, mbedtls_entropy_free> Entropy;
95 class CTRDRBG : private RAIIObj<mbedtls_ctr_drbg_context, mbedtls_ctr_drbg_init, mbedtls_ctr_drbg_free>
98 bool Seed(Entropy& entropy)
100 return (mbedtls_ctr_drbg_seed(get(), mbedtls_entropy_func, entropy.get(), NULL, 0) == 0);
103 void SetupConf(mbedtls_ssl_config* conf)
105 mbedtls_ssl_conf_rng(conf, mbedtls_ctr_drbg_random, get());
109 class DHParams : public RAIIObj<mbedtls_dhm_context, mbedtls_dhm_init, mbedtls_dhm_free>
112 void set(const std::string& dhstr)
114 // Last parameter is buffer size, must include the terminating null
115 int ret = mbedtls_dhm_parse_dhm(get(), reinterpret_cast<const unsigned char*>(dhstr.c_str()), dhstr.size()+1);
116 ThrowOnError(ret, "Unable to import DH params");
120 class X509Key : public RAIIObj<mbedtls_pk_context, mbedtls_pk_init, mbedtls_pk_free>
124 X509Key(const std::string& keystr)
126 int ret = mbedtls_pk_parse_key(get(), reinterpret_cast<const unsigned char*>(keystr.c_str()), keystr.size()+1, NULL, 0);
127 ThrowOnError(ret, "Unable to import private key");
133 std::vector<int> list;
136 Ciphersuites(const std::string& str)
138 // mbedTLS uses the ciphersuite format "TLS-ECDHE-RSA-WITH-AES-128-GCM-SHA256" internally.
139 // This is a bit verbose, so we make life a bit simpler for admins by not requiring them to supply the static parts.
140 irc::sepstream ss(str, ':');
141 for (std::string token; ss.GetToken(token); )
143 // Prepend "TLS-" if not there
144 if (token.compare(0, 4, "TLS-", 4))
145 token.insert(0, "TLS-");
147 const int id = mbedtls_ssl_get_ciphersuite_id(token.c_str());
149 throw Exception("Unknown ciphersuite " + token);
155 const int* get() const { return &list.front(); }
156 bool empty() const { return (list.size() <= 1); }
161 std::vector<mbedtls_ecp_group_id> list;
164 Curves(const std::string& str)
166 irc::sepstream ss(str, ':');
167 for (std::string token; ss.GetToken(token); )
169 const mbedtls_ecp_curve_info* curve = mbedtls_ecp_curve_info_from_name(token.c_str());
171 throw Exception("Unknown curve " + token);
172 list.push_back(curve->grp_id);
174 list.push_back(MBEDTLS_ECP_DP_NONE);
177 const mbedtls_ecp_group_id* get() const { return &list.front(); }
178 bool empty() const { return (list.size() <= 1); }
181 class X509CertList : public RAIIObj<mbedtls_x509_crt, mbedtls_x509_crt_init, mbedtls_x509_crt_free>
184 /** Import or create empty */
185 X509CertList(const std::string& certstr, bool allowempty = false)
187 if ((allowempty) && (certstr.empty()))
189 int ret = mbedtls_x509_crt_parse(get(), reinterpret_cast<const unsigned char*>(certstr.c_str()), certstr.size()+1);
190 ThrowOnError(ret, "Unable to load certificates");
193 bool empty() const { return (get()->raw.p != NULL); }
196 class X509CRL : public RAIIObj<mbedtls_x509_crl, mbedtls_x509_crl_init, mbedtls_x509_crl_free>
199 X509CRL(const std::string& crlstr)
203 int ret = mbedtls_x509_crl_parse(get(), reinterpret_cast<const unsigned char*>(crlstr.c_str()), crlstr.size()+1);
204 ThrowOnError(ret, "Unable to load CRL");
208 class X509Credentials
214 /** Certificate list, presented to the peer
219 X509Credentials(const std::string& certstr, const std::string& keystr)
223 // Verify that one of the certs match the private key
225 for (mbedtls_x509_crt* cert = certs.get(); cert; cert = cert->next)
227 if (mbedtls_pk_check_pair(&cert->pk, key.get()) == 0)
234 throw Exception("Public/private key pair does not match");
237 mbedtls_pk_context* getkey() { return key.get(); }
238 mbedtls_x509_crt* getcerts() { return certs.get(); }
243 mbedtls_ssl_config conf;
245 #ifdef INSPIRCD_MBEDTLS_LIBRARY_DEBUG
246 static void DebugLogFunc(void* userptr, int level, const char* file, int line, const char* msg)
248 // Remove trailing \n
249 size_t len = strlen(msg);
250 if ((len > 0) && (msg[len-1] == '\n'))
252 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "%s:%d %.*s", file, line, len, msg);
257 Context(CTRDRBG& ctrdrbg, unsigned int endpoint)
259 mbedtls_ssl_config_init(&conf);
260 #ifdef INSPIRCD_MBEDTLS_LIBRARY_DEBUG
261 mbedtls_debug_set_threshold(INT_MAX);
262 mbedtls_ssl_conf_dbg(&conf, DebugLogFunc, NULL);
265 // TODO: check ret of mbedtls_ssl_config_defaults
266 mbedtls_ssl_config_defaults(&conf, endpoint, MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT);
267 ctrdrbg.SetupConf(&conf);
272 mbedtls_ssl_config_free(&conf);
275 void SetMinDHBits(unsigned int mindh)
277 mbedtls_ssl_conf_dhm_min_bitlen(&conf, mindh);
280 void SetDHParams(DHParams& dh)
282 mbedtls_ssl_conf_dh_param_ctx(&conf, dh.get());
285 void SetX509CertAndKey(X509Credentials& x509cred)
287 mbedtls_ssl_conf_own_cert(&conf, x509cred.getcerts(), x509cred.getkey());
290 void SetCiphersuites(const Ciphersuites& ciphersuites)
292 mbedtls_ssl_conf_ciphersuites(&conf, ciphersuites.get());
295 void SetCurves(const Curves& curves)
297 mbedtls_ssl_conf_curves(&conf, curves.get());
300 void SetVersion(int minver, int maxver)
302 // SSL v3 support cannot be enabled
304 mbedtls_ssl_conf_min_version(&conf, MBEDTLS_SSL_MAJOR_VERSION_3, minver);
306 mbedtls_ssl_conf_max_version(&conf, MBEDTLS_SSL_MAJOR_VERSION_3, maxver);
309 void SetCA(X509CertList& certs, X509CRL& crl)
311 mbedtls_ssl_conf_ca_chain(&conf, certs.get(), crl.get());
314 void SetOptionalVerifyCert()
316 mbedtls_ssl_conf_authmode(&conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
319 const mbedtls_ssl_config* GetConf() const { return &conf; }
324 const mbedtls_md_info_t* md;
326 /** Buffer where cert hashes are written temporarily
328 mutable std::vector<unsigned char> buf;
331 Hash(std::string hashstr)
333 std::transform(hashstr.begin(), hashstr.end(), hashstr.begin(), ::toupper);
334 md = mbedtls_md_info_from_string(hashstr.c_str());
336 throw Exception("Unknown hash: " + hashstr);
338 buf.resize(mbedtls_md_get_size(md));
341 std::string hash(const unsigned char* input, size_t length) const
343 mbedtls_md(md, input, length, &buf.front());
344 return BinToHex(&buf.front(), buf.size());
348 class Profile : public refcountbase
350 /** Name of this profile
352 const std::string name;
354 X509Credentials x509cred;
356 /** Ciphersuites to use
358 Ciphersuites ciphersuites;
360 /** Curves accepted for use in ECDHE and in the peer's end-entity certificate
369 X509CertList cacerts;
373 /** Hashing algorithm to use when generating certificate fingerprints
377 /** Rough max size of records to send
379 const unsigned int outrecsize;
381 Profile(const std::string& profilename, const std::string& certstr, const std::string& keystr,
382 const std::string& dhstr, unsigned int mindh, const std::string& hashstr,
383 const std::string& ciphersuitestr, const std::string& curvestr,
384 const std::string& castr, const std::string& crlstr,
385 unsigned int recsize,
387 int minver, int maxver,
388 bool requestclientcert
391 , x509cred(certstr, keystr)
392 , ciphersuites(ciphersuitestr)
394 , serverctx(ctrdrbg, MBEDTLS_SSL_IS_SERVER)
395 , clientctx(ctrdrbg, MBEDTLS_SSL_IS_CLIENT)
396 , cacerts(castr, true)
399 , outrecsize(recsize)
401 serverctx.SetX509CertAndKey(x509cred);
402 clientctx.SetX509CertAndKey(x509cred);
403 clientctx.SetMinDHBits(mindh);
405 if (!ciphersuites.empty())
407 serverctx.SetCiphersuites(ciphersuites);
408 clientctx.SetCiphersuites(ciphersuites);
413 serverctx.SetCurves(curves);
414 clientctx.SetCurves(curves);
417 serverctx.SetVersion(minver, maxver);
418 clientctx.SetVersion(minver, maxver);
423 serverctx.SetDHParams(dhparams);
426 clientctx.SetOptionalVerifyCert();
427 clientctx.SetCA(cacerts, crl);
428 // The default for servers is to not request a client certificate from the peer
429 if (requestclientcert)
431 serverctx.SetOptionalVerifyCert();
432 serverctx.SetCA(cacerts, crl);
436 static std::string ReadFile(const std::string& filename)
438 FileReader reader(filename);
439 std::string ret = reader.GetString();
441 throw Exception("Cannot read file " + filename);
446 static reference<Profile> Create(const std::string& profilename, ConfigTag* tag, CTRDRBG& ctr_drbg)
448 const std::string certstr = ReadFile(tag->getString("certfile", "cert.pem"));
449 const std::string keystr = ReadFile(tag->getString("keyfile", "key.pem"));
450 const std::string dhstr = ReadFile(tag->getString("dhfile", "dhparams.pem"));
452 const std::string ciphersuitestr = tag->getString("ciphersuites");
453 const std::string curvestr = tag->getString("curves");
454 unsigned int mindh = tag->getInt("mindhbits", 2048);
455 std::string hashstr = tag->getString("hash", "sha256");
458 std::string castr = tag->getString("cafile");
461 castr = ReadFile(castr);
462 crlstr = tag->getString("crlfile");
464 crlstr = ReadFile(crlstr);
467 int minver = tag->getInt("minver");
468 int maxver = tag->getInt("maxver");
469 unsigned int outrecsize = tag->getInt("outrecsize", 2048, 512, 16384);
470 const bool requestclientcert = tag->getBool("requestclientcert", true);
471 return new Profile(profilename, certstr, keystr, dhstr, mindh, hashstr, ciphersuitestr, curvestr, castr, crlstr, outrecsize, ctr_drbg, minver, maxver, requestclientcert);
474 /** Set up the given session with the settings in this profile
476 void SetupClientSession(mbedtls_ssl_context* sess)
478 mbedtls_ssl_setup(sess, clientctx.GetConf());
481 void SetupServerSession(mbedtls_ssl_context* sess)
483 mbedtls_ssl_setup(sess, serverctx.GetConf());
486 const std::string& GetName() const { return name; }
487 X509Credentials& GetX509Credentials() { return x509cred; }
488 unsigned int GetOutgoingRecordSize() const { return outrecsize; }
489 const Hash& GetHash() const { return hash; }
493 class mbedTLSIOHook : public SSLIOHook
502 mbedtls_ssl_context sess;
504 reference<mbedTLS::Profile> profile;
508 if (status == ISSL_NONE)
511 mbedtls_ssl_close_notify(&sess);
512 mbedtls_ssl_free(&sess);
517 // Returns 1 if handshake succeeded, 0 if it is still in progress, -1 if it failed
518 int Handshake(StreamSocket* sock)
520 int ret = mbedtls_ssl_handshake(&sess);
523 // Change the seesion state
524 this->status = ISSL_HANDSHAKEN;
528 // Finish writing, if any left
529 SocketEngine::ChangeEventMask(sock, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
534 this->status = ISSL_HANDSHAKING;
535 if (ret == MBEDTLS_ERR_SSL_WANT_READ)
537 SocketEngine::ChangeEventMask(sock, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
540 else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE)
542 SocketEngine::ChangeEventMask(sock, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
546 sock->SetError("Handshake Failed - " + mbedTLS::ErrorToString(ret));
551 // Returns 1 if application I/O should proceed, 0 if it must wait for the underlying protocol to progress, -1 on fatal error
552 int PrepareIO(StreamSocket* sock)
554 if (status == ISSL_HANDSHAKEN)
556 else if (status == ISSL_HANDSHAKING)
558 // The handshake isn't finished, try to finish it
559 return Handshake(sock);
563 sock->SetError("No SSL session");
567 void VerifyCertificate()
569 this->certificate = new ssl_cert;
570 const mbedtls_x509_crt* const cert = mbedtls_ssl_get_peer_cert(&sess);
573 certificate->error = "No client certificate sent";
577 // If there is a certificate we can always generate a fingerprint
578 certificate->fingerprint = profile->GetHash().hash(cert->raw.p, cert->raw.len);
580 // At this point mbedTLS verified the cert already, we just need to check the results
581 const uint32_t flags = mbedtls_ssl_get_verify_result(&sess);
582 if (flags == 0xFFFFFFFF)
584 certificate->error = "Internal error during verification";
590 // Verification succeeded
591 certificate->trusted = true;
595 // Verification failed
596 certificate->trusted = false;
597 if ((flags & MBEDTLS_X509_BADCERT_EXPIRED) || (flags & MBEDTLS_X509_BADCERT_FUTURE))
598 certificate->error = "Not activated, or expired certificate";
601 certificate->unknownsigner = (flags & MBEDTLS_X509_BADCERT_NOT_TRUSTED);
602 certificate->revoked = (flags & MBEDTLS_X509_BADCERT_REVOKED);
603 certificate->invalid = ((flags & MBEDTLS_X509_BADCERT_BAD_KEY) || (flags & MBEDTLS_X509_BADCERT_BAD_MD) || (flags & MBEDTLS_X509_BADCERT_BAD_PK));
605 GetDNString(&cert->subject, certificate->dn);
606 GetDNString(&cert->issuer, certificate->issuer);
609 static void GetDNString(const mbedtls_x509_name* x509name, std::string& out)
612 const int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), x509name);
616 out.assign(buf, ret);
619 static int Pull(void* userptr, unsigned char* buffer, size_t size)
621 StreamSocket* const sock = reinterpret_cast<StreamSocket*>(userptr);
622 if (sock->GetEventMask() & FD_READ_WILL_BLOCK)
623 return MBEDTLS_ERR_SSL_WANT_READ;
625 const int ret = SocketEngine::Recv(sock, reinterpret_cast<char*>(buffer), size, 0);
628 SocketEngine::ChangeEventMask(sock, FD_READ_WILL_BLOCK);
629 if ((ret == -1) && (SocketEngine::IgnoreError()))
630 return MBEDTLS_ERR_SSL_WANT_READ;
635 static int Push(void* userptr, const unsigned char* buffer, size_t size)
637 StreamSocket* const sock = reinterpret_cast<StreamSocket*>(userptr);
638 if (sock->GetEventMask() & FD_WRITE_WILL_BLOCK)
639 return MBEDTLS_ERR_SSL_WANT_WRITE;
641 const int ret = SocketEngine::Send(sock, buffer, size, 0);
644 SocketEngine::ChangeEventMask(sock, FD_WRITE_WILL_BLOCK);
645 if ((ret == -1) && (SocketEngine::IgnoreError()))
646 return MBEDTLS_ERR_SSL_WANT_WRITE;
652 mbedTLSIOHook(IOHookProvider* hookprov, StreamSocket* sock, bool isserver, mbedTLS::Profile* sslprofile)
653 : SSLIOHook(hookprov)
655 , profile(sslprofile)
657 mbedtls_ssl_init(&sess);
659 profile->SetupServerSession(&sess);
661 profile->SetupClientSession(&sess);
663 mbedtls_ssl_set_bio(&sess, reinterpret_cast<void*>(sock), Push, Pull, NULL);
665 sock->AddIOHook(this);
669 void OnStreamSocketClose(StreamSocket* sock) CXX11_OVERRIDE
674 int OnStreamSocketRead(StreamSocket* sock, std::string& recvq) CXX11_OVERRIDE
676 // Finish handshake if needed
677 int prepret = PrepareIO(sock);
681 // If we resumed the handshake then this->status will be ISSL_HANDSHAKEN.
682 char* const readbuf = ServerInstance->GetReadBuffer();
683 const size_t readbufsize = ServerInstance->Config->NetBufferSize;
684 int ret = mbedtls_ssl_read(&sess, reinterpret_cast<unsigned char*>(readbuf), readbufsize);
687 recvq.append(readbuf, ret);
689 // Schedule a read if there is still data in the mbedTLS buffer
690 if (mbedtls_ssl_get_bytes_avail(&sess) > 0)
691 SocketEngine::ChangeEventMask(sock, FD_ADD_TRIAL_READ);
694 else if (ret == MBEDTLS_ERR_SSL_WANT_READ)
696 SocketEngine::ChangeEventMask(sock, FD_WANT_POLL_READ);
699 else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE)
701 SocketEngine::ChangeEventMask(sock, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
706 sock->SetError("Connection closed");
710 else // error or MBEDTLS_ERR_SSL_CLIENT_RECONNECT which we treat as an error
712 sock->SetError(mbedTLS::ErrorToString(ret));
718 int OnStreamSocketWrite(StreamSocket* sock, StreamSocket::SendQueue& sendq) CXX11_OVERRIDE
720 // Finish handshake if needed
721 int prepret = PrepareIO(sock);
725 // Session is ready for transferring application data
726 while (!sendq.empty())
728 FlattenSendQueue(sendq, profile->GetOutgoingRecordSize());
729 const StreamSocket::SendQueue::Element& buffer = sendq.front();
730 int ret = mbedtls_ssl_write(&sess, reinterpret_cast<const unsigned char*>(buffer.data()), buffer.length());
731 if (ret == (int)buffer.length())
733 // Wrote entire record, continue sending
738 sendq.erase_front(ret);
739 SocketEngine::ChangeEventMask(sock, FD_WANT_SINGLE_WRITE);
744 sock->SetError("Connection closed");
748 else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE)
750 SocketEngine::ChangeEventMask(sock, FD_WANT_SINGLE_WRITE);
753 else if (ret == MBEDTLS_ERR_SSL_WANT_READ)
755 SocketEngine::ChangeEventMask(sock, FD_WANT_POLL_READ);
760 sock->SetError(mbedTLS::ErrorToString(ret));
766 SocketEngine::ChangeEventMask(sock, FD_WANT_NO_WRITE);
770 void GetCiphersuite(std::string& out) const CXX11_OVERRIDE
772 if (!IsHandshakeDone())
774 out.append(mbedtls_ssl_get_version(&sess)).push_back('-');
776 // All mbedTLS ciphersuite names currently begin with "TLS-" which provides no useful information so skip it, but be prepared if it changes
777 const char* const ciphersuitestr = mbedtls_ssl_get_ciphersuite(&sess);
778 const char prefix[] = "TLS-";
779 unsigned int skip = sizeof(prefix)-1;
780 if (strncmp(ciphersuitestr, prefix, sizeof(prefix)-1))
782 out.append(ciphersuitestr + skip);
785 bool GetServerName(std::string& out) const CXX11_OVERRIDE
787 // TODO: Implement SNI support.
791 bool IsHandshakeDone() const { return (status == ISSL_HANDSHAKEN); }
794 class mbedTLSIOHookProvider : public refcountbase, public IOHookProvider
796 reference<mbedTLS::Profile> profile;
799 mbedTLSIOHookProvider(Module* mod, mbedTLS::Profile* prof)
800 : IOHookProvider(mod, "ssl/" + prof->GetName(), IOHookProvider::IOH_SSL)
803 ServerInstance->Modules->AddService(*this);
806 ~mbedTLSIOHookProvider()
808 ServerInstance->Modules->DelService(*this);
811 void OnAccept(StreamSocket* sock, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) CXX11_OVERRIDE
813 new mbedTLSIOHook(this, sock, true, profile);
816 void OnConnect(StreamSocket* sock) CXX11_OVERRIDE
818 new mbedTLSIOHook(this, sock, false, profile);
822 class ModuleSSLmbedTLS : public Module
824 typedef std::vector<reference<mbedTLSIOHookProvider> > ProfileList;
826 mbedTLS::Entropy entropy;
827 mbedTLS::CTRDRBG ctr_drbg;
828 ProfileList profiles;
832 // First, store all profiles in a new, temporary container. If no problems occur, swap the two
833 // containers; this way if something goes wrong we can go back and continue using the current profiles,
834 // avoiding unpleasant situations where no new SSL connections are possible.
835 ProfileList newprofiles;
837 ConfigTagList tags = ServerInstance->Config->ConfTags("sslprofile");
838 if (tags.first == tags.second)
840 // No <sslprofile> tags found, create a profile named "mbedtls" from settings in the <mbedtls> block
841 const std::string defname = "mbedtls";
842 ConfigTag* tag = ServerInstance->Config->ConfValue(defname);
843 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "No <sslprofile> tags found; using settings from the <mbedtls> tag");
847 reference<mbedTLS::Profile> profile(mbedTLS::Profile::Create(defname, tag, ctr_drbg));
848 newprofiles.push_back(new mbedTLSIOHookProvider(this, profile));
850 catch (CoreException& ex)
852 throw ModuleException("Error while initializing the default SSL profile - " + ex.GetReason());
856 for (ConfigIter i = tags.first; i != tags.second; ++i)
858 ConfigTag* tag = i->second;
859 if (tag->getString("provider") != "mbedtls")
862 std::string name = tag->getString("name");
865 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Ignoring <sslprofile> tag without name at " + tag->getTagLocation());
869 reference<mbedTLS::Profile> profile;
872 profile = mbedTLS::Profile::Create(name, tag, ctr_drbg);
874 catch (CoreException& ex)
876 throw ModuleException("Error while initializing SSL profile \"" + name + "\" at " + tag->getTagLocation() + " - " + ex.GetReason());
879 newprofiles.push_back(new mbedTLSIOHookProvider(this, profile));
882 // New profiles are ok, begin using them
883 // Old profiles are deleted when their refcount drops to zero
884 profiles.swap(newprofiles);
888 void init() CXX11_OVERRIDE
890 char verbuf[16]; // Should be at least 9 bytes in size
891 mbedtls_version_get_string(verbuf);
892 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "mbedTLS lib version %s module was compiled for " MBEDTLS_VERSION_STRING, verbuf);
894 if (!ctr_drbg.Seed(entropy))
895 throw ModuleException("CTR DRBG seed failed");
899 void OnModuleRehash(User* user, const std::string ¶m) CXX11_OVERRIDE
908 catch (ModuleException& ex)
910 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, ex.GetReason() + " Not applying settings.");
914 void OnCleanup(ExtensionItem::ExtensibleType type, Extensible* item) CXX11_OVERRIDE
916 if (type != ExtensionItem::EXT_USER)
919 LocalUser* user = IS_LOCAL(static_cast<User*>(item));
920 if ((user) && (user->eh.GetModHook(this)))
922 // User is using SSL, they're a local user, and they're using our IOHook.
923 // Potentially there could be multiple SSL modules loaded at once on different ports.
924 ServerInstance->Users.QuitUser(user, "SSL module unloading");
928 ModResult OnCheckReady(LocalUser* user) CXX11_OVERRIDE
930 const mbedTLSIOHook* const iohook = static_cast<mbedTLSIOHook*>(user->eh.GetModHook(this));
931 if ((iohook) && (!iohook->IsHandshakeDone()))
933 return MOD_RES_PASSTHRU;
936 Version GetVersion() CXX11_OVERRIDE
938 return Version("Provides SSL support via mbedTLS (PolarSSL)", VF_VENDOR);
942 MODULE_INIT(ModuleSSLmbedTLS)