]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ssl_openssl.cpp
f2189f257e237954693efdbe29d7d9d9e6a10d34
[user/henk/code/inspircd.git] / src / modules / extra / m_ssl_openssl.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
5  *   Copyright (C) 2008 Pippijn van Steenhoven <pip88nl@gmail.com>
6  *   Copyright (C) 2006-2008 Craig Edwards <craigedwards@brainbox.cc>
7  *   Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
8  *   Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
9  *   Copyright (C) 2006 Oliver Lupton <oliverlupton@gmail.com>
10  *
11  * This file is part of InspIRCd.  InspIRCd is free software: you can
12  * redistribute it and/or modify it under the terms of the GNU General Public
13  * License as published by the Free Software Foundation, version 2.
14  *
15  * This program is distributed in the hope that it will be useful, but WITHOUT
16  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22  */
23
24  /* HACK: This prevents OpenSSL on OS X 10.7 and later from spewing deprecation
25   * warnings for every single function call. As far as I (SaberUK) know, Apple
26   * have no plans to remove OpenSSL so this warning just causes needless spam.
27   */
28 #ifdef __APPLE__
29 # define __AVAILABILITYMACROS__
30 # define DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER
31 #endif
32  
33 #include "inspircd.h"
34 #include <openssl/ssl.h>
35 #include <openssl/err.h>
36 #include <openssl/dh.h>
37 #include "ssl.h"
38
39 #ifdef _WIN32
40 # pragma comment(lib, "ssleay32.lib")
41 # pragma comment(lib, "libeay32.lib")
42 # undef MAX_DESCRIPTORS
43 # define MAX_DESCRIPTORS 10000
44 #endif
45
46 // Compatibility layer to allow OpenSSL 1.0 to use the 1.1 API.
47 #if ((defined LIBRESSL_VERSION_NUMBER) || (OPENSSL_VERSION_NUMBER < 0x10100000L))
48 # define X509_getm_notAfter X509_get_notAfter
49 # define X509_getm_notBefore X509_get_notBefore
50 # define OPENSSL_init_ssl(OPTIONS, SETTINGS) \
51         SSL_library_init(); \
52         SSL_load_error_strings();
53 #endif
54
55 /* $ModDesc: Provides SSL support for clients */
56
57 /* $LinkerFlags: if("USE_FREEBSD_BASE_SSL") -lssl -lcrypto */
58 /* $CompileFlags: if(!"USE_FREEBSD_BASE_SSL") pkgconfversion("openssl","0.9.7") pkgconfincludes("openssl","/openssl/ssl.h","") */
59 /* $LinkerFlags: if(!"USE_FREEBSD_BASE_SSL") rpath("pkg-config --libs openssl") pkgconflibs("openssl","/libssl.so","-lssl -lcrypto -ldl") */
60
61 /* $NoPedantic */
62
63
64 class ModuleSSLOpenSSL;
65
66 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING, ISSL_OPEN };
67
68 static bool SelfSigned = false;
69
70 #ifdef INSPIRCD_OPENSSL_ENABLE_RENEGO_DETECTION
71 static ModuleSSLOpenSSL* opensslmod = NULL;
72 #endif
73
74 char* get_error()
75 {
76         return ERR_error_string(ERR_get_error(), NULL);
77 }
78
79 static int error_callback(const char *str, size_t len, void *u);
80
81 /** Represents an SSL user's extra data
82  */
83 class issl_session
84 {
85 public:
86         SSL* sess;
87         issl_status status;
88         reference<ssl_cert> cert;
89
90         bool outbound;
91         bool data_to_write;
92
93         issl_session()
94                 : sess(NULL)
95                 , status(ISSL_NONE)
96         {
97                 outbound = false;
98                 data_to_write = false;
99         }
100 };
101
102 static int OnVerify(int preverify_ok, X509_STORE_CTX *ctx)
103 {
104         /* XXX: This will allow self signed certificates.
105          * In the future if we want an option to not allow this,
106          * we can just return preverify_ok here, and openssl
107          * will boot off self-signed and invalid peer certs.
108          */
109         int ve = X509_STORE_CTX_get_error(ctx);
110
111         SelfSigned = (ve == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
112
113         return 1;
114 }
115
116 class ModuleSSLOpenSSL : public Module
117 {
118         issl_session* sessions;
119
120         SSL_CTX* ctx;
121         SSL_CTX* clictx;
122
123         long ctx_options;
124         long clictx_options;
125
126         std::string sslports;
127         bool use_sha;
128
129         ServiceProvider iohook;
130
131         static void SetContextOptions(SSL_CTX* ctx, long defoptions, const std::string& ctxname, ConfigTag* tag)
132         {
133                 long setoptions = tag->getInt(ctxname + "setoptions");
134                 // User-friendly config options for setting context options
135 #ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
136                 if (tag->getBool("cipherserverpref"))
137                         setoptions |= SSL_OP_CIPHER_SERVER_PREFERENCE;
138 #endif
139 #ifdef SSL_OP_NO_COMPRESSION
140                 if (!tag->getBool("compression", true))
141                         setoptions |= SSL_OP_NO_COMPRESSION;
142 #endif
143                 if (!tag->getBool("sslv3", true))
144                         setoptions |= SSL_OP_NO_SSLv3;
145                 if (!tag->getBool("tlsv1", true))
146                         setoptions |= SSL_OP_NO_TLSv1;
147
148                 long clearoptions = tag->getInt(ctxname + "clearoptions");
149                 ServerInstance->Logs->Log("m_ssl_openssl", DEBUG, "Setting OpenSSL %s context options, default: %ld set: %ld clear: %ld", ctxname.c_str(), defoptions, setoptions, clearoptions);
150
151                 // Clear everything
152                 SSL_CTX_clear_options(ctx, SSL_CTX_get_options(ctx));
153
154                 // Set the default options and what is in the conf
155                 SSL_CTX_set_options(ctx, defoptions | setoptions);
156                 long final = SSL_CTX_clear_options(ctx, clearoptions);
157                 ServerInstance->Logs->Log("m_ssl_openssl", DEFAULT, "OpenSSL %s context options: %ld", ctxname.c_str(), final);
158         }
159
160 #ifdef INSPIRCD_OPENSSL_ENABLE_ECDH
161         void SetupECDH(ConfigTag* tag)
162         {
163                 std::string curvename = tag->getString("ecdhcurve", "prime256v1");
164                 if (curvename.empty())
165                         return;
166
167                 int nid = OBJ_sn2nid(curvename.c_str());
168                 if (nid == 0)
169                 {
170                         ServerInstance->Logs->Log("m_ssl_openssl", DEFAULT, "m_ssl_openssl.so: Unknown curve: \"%s\"", curvename.c_str());
171                         return;
172                 }
173
174                 EC_KEY* eckey = EC_KEY_new_by_curve_name(nid);
175                 if (!eckey)
176                 {
177                         ServerInstance->Logs->Log("m_ssl_openssl", DEFAULT, "m_ssl_openssl.so: Unable to create EC key object");
178                         return;
179                 }
180
181                 ERR_clear_error();
182                 if (SSL_CTX_set_tmp_ecdh(ctx, eckey) < 0)
183                 {
184                         ServerInstance->Logs->Log("m_ssl_openssl", DEFAULT, "m_ssl_openssl.so: Couldn't set ECDH parameters");
185                         ERR_print_errors_cb(error_callback, this);
186                 }
187
188                 EC_KEY_free(eckey);
189         }
190 #endif
191
192 #ifdef INSPIRCD_OPENSSL_ENABLE_RENEGO_DETECTION
193         static void SSLInfoCallback(const SSL* ssl, int where, int rc)
194         {
195                 int fd = SSL_get_fd(const_cast<SSL*>(ssl));
196                 issl_session& session = opensslmod->sessions[fd];
197
198                 if ((where & SSL_CB_HANDSHAKE_START) && (session.status == ISSL_OPEN))
199                 {
200                         // The other side is trying to renegotiate, kill the connection and change status
201                         // to ISSL_NONE so CheckRenego() closes the session
202                         session.status = ISSL_NONE;
203                         ServerInstance->SE->Shutdown(fd, 2);
204                 }
205         }
206
207         bool CheckRenego(StreamSocket* sock, issl_session* session)
208         {
209                 if (session->status != ISSL_NONE)
210                         return true;
211
212                 ServerInstance->Logs->Log("m_ssl_openssl", DEBUG, "Session %p killed, attempted to renegotiate", (void*)session->sess);
213                 CloseSession(session);
214                 sock->SetError("Renegotiation is not allowed");
215                 return false;
216         }
217 #endif
218
219  public:
220
221         ModuleSSLOpenSSL() : iohook(this, "ssl/openssl", SERVICE_IOHOOK)
222         {
223 #ifdef INSPIRCD_OPENSSL_ENABLE_RENEGO_DETECTION
224                 opensslmod = this;
225 #endif
226                 sessions = new issl_session[ServerInstance->SE->GetMaxFds()];
227
228                 /* Global SSL library initialization*/
229                 OPENSSL_init_ssl(0, NULL);
230
231                 /* Build our SSL contexts:
232                  * NOTE: OpenSSL makes us have two contexts, one for servers and one for clients. ICK.
233                  */
234                 ctx = SSL_CTX_new( SSLv23_server_method() );
235                 clictx = SSL_CTX_new( SSLv23_client_method() );
236
237                 SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
238                 SSL_CTX_set_mode(clictx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
239
240                 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
241                 SSL_CTX_set_verify(clictx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
242
243                 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
244                 SSL_CTX_set_session_cache_mode(clictx, SSL_SESS_CACHE_OFF);
245
246                 long opts = SSL_OP_NO_SSLv2 | SSL_OP_SINGLE_DH_USE;
247                 // Only turn options on if they exist
248 #ifdef SSL_OP_SINGLE_ECDH_USE
249                 opts |= SSL_OP_SINGLE_ECDH_USE;
250 #endif
251 #ifdef SSL_OP_NO_TICKET
252                 opts |= SSL_OP_NO_TICKET;
253 #endif
254
255                 ctx_options = SSL_CTX_set_options(ctx, opts);
256                 clictx_options = SSL_CTX_set_options(clictx, opts);
257         }
258
259         void init()
260         {
261                 // Needs the flag as it ignores a plain /rehash
262                 OnModuleRehash(NULL,"ssl");
263                 Implementation eventlist[] = { I_On005Numeric, I_OnRehash, I_OnModuleRehash, I_OnHookIO, I_OnUserConnect };
264                 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
265                 ServerInstance->Modules->AddService(iohook);
266         }
267
268         void OnHookIO(StreamSocket* user, ListenSocket* lsb)
269         {
270                 if (!user->GetIOHook() && lsb->bind_tag->getString("ssl") == "openssl")
271                 {
272                         /* Hook the user with our module */
273                         user->AddIOHook(this);
274                 }
275         }
276
277         void OnRehash(User* user)
278         {
279                 sslports.clear();
280
281                 ConfigTag* Conf = ServerInstance->Config->ConfValue("openssl");
282
283 #ifdef INSPIRCD_OPENSSL_ENABLE_RENEGO_DETECTION
284                 // Set the callback if we are not allowing renegotiations, unset it if we do
285                 if (Conf->getBool("renegotiation", true))
286                 {
287                         SSL_CTX_set_info_callback(ctx, NULL);
288                         SSL_CTX_set_info_callback(clictx, NULL);
289                 }
290                 else
291                 {
292                         SSL_CTX_set_info_callback(ctx, SSLInfoCallback);
293                         SSL_CTX_set_info_callback(clictx, SSLInfoCallback);
294                 }
295 #endif
296
297                 if (Conf->getBool("showports", true))
298                 {
299                         sslports = Conf->getString("advertisedports");
300                         if (!sslports.empty())
301                                 return;
302
303                         for (size_t i = 0; i < ServerInstance->ports.size(); i++)
304                         {
305                                 ListenSocket* port = ServerInstance->ports[i];
306                                 if (port->bind_tag->getString("ssl") != "openssl")
307                                         continue;
308
309                                 const std::string& portid = port->bind_desc;
310                                 ServerInstance->Logs->Log("m_ssl_openssl", DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %s", portid.c_str());
311
312                                 if (port->bind_tag->getString("type", "clients") == "clients" && port->bind_addr != "127.0.0.1")
313                                 {
314                                         /*
315                                          * Found an SSL port for clients that is not bound to 127.0.0.1 and handled by us, display
316                                          * the IP:port in ISUPPORT.
317                                          *
318                                          * We used to advertise all ports seperated by a ';' char that matched the above criteria,
319                                          * but this resulted in too long ISUPPORT lines if there were lots of ports to be displayed.
320                                          * To solve this by default we now only display the first IP:port found and let the user
321                                          * configure the exact value for the 005 token, if necessary.
322                                          */
323                                         sslports = portid;
324                                         break;
325                                 }
326                         }
327                 }
328         }
329
330         void OnModuleRehash(User* user, const std::string &param)
331         {
332                 if (param != "ssl")
333                         return;
334
335                 std::string keyfile;
336                 std::string certfile;
337                 std::string cafile;
338                 std::string dhfile;
339                 OnRehash(user);
340
341                 ConfigTag* conf = ServerInstance->Config->ConfValue("openssl");
342
343                 cafile   = conf->getString("cafile", CONFIG_PATH "/ca.pem");
344                 certfile = conf->getString("certfile", CONFIG_PATH "/cert.pem");
345                 keyfile  = conf->getString("keyfile", CONFIG_PATH "/key.pem");
346                 dhfile   = conf->getString("dhfile", CONFIG_PATH "/dhparams.pem");
347                 std::string hash = conf->getString("hash", "md5");
348                 if (hash != "sha1" && hash != "md5")
349                         throw ModuleException("Unknown hash type " + hash);
350                 use_sha = (hash == "sha1");
351
352                 if (conf->getBool("customcontextoptions"))
353                 {
354                         SetContextOptions(ctx, ctx_options, "server", conf);
355                         SetContextOptions(clictx, clictx_options, "client", conf);
356                 }
357
358                 std::string ciphers = conf->getString("ciphers", "");
359
360                 if (!ciphers.empty())
361                 {
362                         ERR_clear_error();
363                         if ((!SSL_CTX_set_cipher_list(ctx, ciphers.c_str())) || (!SSL_CTX_set_cipher_list(clictx, ciphers.c_str())))
364                         {
365                                 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't set cipher list to %s.", ciphers.c_str());
366                                 ERR_print_errors_cb(error_callback, this);
367                         }
368                 }
369
370                 /* Load our keys and certificates
371                  * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck.
372                  */
373                 ERR_clear_error();
374                 if ((!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str())) || (!SSL_CTX_use_certificate_chain_file(clictx, certfile.c_str())))
375                 {
376                         ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s. %s", certfile.c_str(), strerror(errno));
377                         ERR_print_errors_cb(error_callback, this);
378                 }
379
380                 ERR_clear_error();
381                 if (((!SSL_CTX_use_PrivateKey_file(ctx, keyfile.c_str(), SSL_FILETYPE_PEM))) || (!SSL_CTX_use_PrivateKey_file(clictx, keyfile.c_str(), SSL_FILETYPE_PEM)))
382                 {
383                         ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read key file %s. %s", keyfile.c_str(), strerror(errno));
384                         ERR_print_errors_cb(error_callback, this);
385                 }
386
387                 /* Load the CAs we trust*/
388                 ERR_clear_error();
389                 if (((!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))) || (!SSL_CTX_load_verify_locations(clictx, cafile.c_str(), 0)))
390                 {
391                         ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read CA list from %s. This is only a problem if you want to verify client certificates, otherwise it's safe to ignore this message. Error: %s", cafile.c_str(), strerror(errno));
392                         ERR_print_errors_cb(error_callback, this);
393                 }
394
395 #ifdef _WIN32
396                 BIO* dhpfile = BIO_new_file(dhfile.c_str(), "r");
397 #else
398                 FILE* dhpfile = fopen(dhfile.c_str(), "r");
399 #endif
400                 DH* ret;
401
402                 if (dhpfile == NULL)
403                 {
404                         ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
405                         throw ModuleException("Couldn't open DH file " + dhfile + ": " + strerror(errno));
406                 }
407                 else
408                 {
409 #ifdef _WIN32
410                         ret = PEM_read_bio_DHparams(dhpfile, NULL, NULL, NULL);
411                         BIO_free(dhpfile);
412 #else
413                         ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
414 #endif
415
416                         ERR_clear_error();
417                         if (ret)
418                         {
419                                 if ((SSL_CTX_set_tmp_dh(ctx, ret) < 0) || (SSL_CTX_set_tmp_dh(clictx, ret) < 0))
420                                 {
421                                         ServerInstance->Logs->Log("m_ssl_openssl", DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters %s. SSL errors follow:", dhfile.c_str());
422                                         ERR_print_errors_cb(error_callback, this);
423                                 }
424                                 DH_free(ret);
425                         }
426                         else
427                         {
428                                 ServerInstance->Logs->Log("m_ssl_openssl", DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters %s.", dhfile.c_str());
429                         }
430                 }
431
432 #ifndef _WIN32
433                 fclose(dhpfile);
434 #endif
435
436 #ifdef INSPIRCD_OPENSSL_ENABLE_ECDH
437                 SetupECDH(conf);
438 #endif
439         }
440
441         void On005Numeric(std::string &output)
442         {
443                 if (!sslports.empty())
444                         output.append(" SSL=" + sslports);
445         }
446
447         ~ModuleSSLOpenSSL()
448         {
449                 SSL_CTX_free(ctx);
450                 SSL_CTX_free(clictx);
451                 delete[] sessions;
452         }
453
454         void OnUserConnect(LocalUser* user)
455         {
456                 if (user->eh.GetIOHook() == this)
457                 {
458                         if (sessions[user->eh.GetFd()].sess)
459                         {
460                                 if (!sessions[user->eh.GetFd()].cert->fingerprint.empty())
461                                         user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\""
462                                                 " and your SSL fingerprint is %s", user->nick.c_str(), SSL_get_cipher(sessions[user->eh.GetFd()].sess), sessions[user->eh.GetFd()].cert->fingerprint.c_str());
463                                 else
464                                         user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\"", user->nick.c_str(), SSL_get_cipher(sessions[user->eh.GetFd()].sess));
465                         }
466                 }
467         }
468
469         void OnCleanup(int target_type, void* item)
470         {
471                 if (target_type == TYPE_USER)
472                 {
473                         LocalUser* user = IS_LOCAL((User*)item);
474
475                         if (user && user->eh.GetIOHook() == this)
476                         {
477                                 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
478                                 // Potentially there could be multiple SSL modules loaded at once on different ports.
479                                 ServerInstance->Users->QuitUser(user, "SSL module unloading");
480                         }
481                 }
482         }
483
484         Version GetVersion()
485         {
486                 return Version("Provides SSL support for clients", VF_VENDOR);
487         }
488
489         void OnRequest(Request& request)
490         {
491                 if (strcmp("GET_SSL_CERT", request.id) == 0)
492                 {
493                         SocketCertificateRequest& req = static_cast<SocketCertificateRequest&>(request);
494                         int fd = req.sock->GetFd();
495                         issl_session* session = &sessions[fd];
496
497                         req.cert = session->cert;
498                 }
499                 else if (!strcmp("GET_RAW_SSL_SESSION", request.id))
500                 {
501                         SSLRawSessionRequest& req = static_cast<SSLRawSessionRequest&>(request);
502                         if ((req.fd >= 0) && (req.fd < ServerInstance->SE->GetMaxFds()))
503                                 req.data = reinterpret_cast<void*>(sessions[req.fd].sess);
504                 }
505         }
506
507         void OnStreamSocketAccept(StreamSocket* user, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
508         {
509                 int fd = user->GetFd();
510
511                 issl_session* session = &sessions[fd];
512
513                 session->sess = SSL_new(ctx);
514                 session->status = ISSL_NONE;
515                 session->outbound = false;
516                 session->data_to_write = false;
517
518                 if (session->sess == NULL)
519                         return;
520
521                 if (SSL_set_fd(session->sess, fd) == 0)
522                 {
523                         ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
524                         return;
525                 }
526
527                 Handshake(user, session);
528         }
529
530         void OnStreamSocketConnect(StreamSocket* user)
531         {
532                 int fd = user->GetFd();
533                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
534                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() -1))
535                         return;
536
537                 issl_session* session = &sessions[fd];
538
539                 session->sess = SSL_new(clictx);
540                 session->status = ISSL_NONE;
541                 session->outbound = true;
542                 session->data_to_write = false;
543
544                 if (session->sess == NULL)
545                         return;
546
547                 if (SSL_set_fd(session->sess, fd) == 0)
548                 {
549                         ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
550                         return;
551                 }
552
553                 Handshake(user, session);
554         }
555
556         void OnStreamSocketClose(StreamSocket* user)
557         {
558                 int fd = user->GetFd();
559                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
560                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
561                         return;
562
563                 CloseSession(&sessions[fd]);
564         }
565
566         int OnStreamSocketRead(StreamSocket* user, std::string& recvq)
567         {
568                 int fd = user->GetFd();
569                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
570                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
571                         return -1;
572
573                 issl_session* session = &sessions[fd];
574
575                 if (!session->sess)
576                 {
577                         CloseSession(session);
578                         return -1;
579                 }
580
581                 if (session->status == ISSL_HANDSHAKING)
582                 {
583                         // The handshake isn't finished and it wants to read, try to finish it.
584                         if (!Handshake(user, session))
585                         {
586                                 // Couldn't resume handshake.
587                                 if (session->status == ISSL_NONE)
588                                         return -1;
589                                 return 0;
590                         }
591                 }
592
593                 // If we resumed the handshake then session->status will be ISSL_OPEN
594
595                 if (session->status == ISSL_OPEN)
596                 {
597                         ERR_clear_error();
598                         char* buffer = ServerInstance->GetReadBuffer();
599                         size_t bufsiz = ServerInstance->Config->NetBufferSize;
600                         int ret = SSL_read(session->sess, buffer, bufsiz);
601
602 #ifdef INSPIRCD_OPENSSL_ENABLE_RENEGO_DETECTION
603                         if (!CheckRenego(user, session))
604                                 return -1;
605 #endif
606
607                         if (ret > 0)
608                         {
609                                 recvq.append(buffer, ret);
610
611                                 int mask = 0;
612                                 // Schedule a read if there is still data in the OpenSSL buffer
613                                 if (SSL_pending(session->sess) > 0)
614                                         mask |= FD_ADD_TRIAL_READ;
615                                 if (session->data_to_write)
616                                         mask |= FD_WANT_POLL_READ | FD_WANT_SINGLE_WRITE;
617                                 if (mask != 0)
618                                         ServerInstance->SE->ChangeEventMask(user, mask);
619                                 return 1;
620                         }
621                         else if (ret == 0)
622                         {
623                                 // Client closed connection.
624                                 CloseSession(session);
625                                 user->SetError("Connection closed");
626                                 return -1;
627                         }
628                         else if (ret < 0)
629                         {
630                                 int err = SSL_get_error(session->sess, ret);
631
632                                 if (err == SSL_ERROR_WANT_READ)
633                                 {
634                                         ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ);
635                                         return 0;
636                                 }
637                                 else if (err == SSL_ERROR_WANT_WRITE)
638                                 {
639                                         ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
640                                         return 0;
641                                 }
642                                 else
643                                 {
644                                         CloseSession(session);
645                                         return -1;
646                                 }
647                         }
648                 }
649
650                 return 0;
651         }
652
653         int OnStreamSocketWrite(StreamSocket* user, std::string& buffer)
654         {
655                 int fd = user->GetFd();
656
657                 issl_session* session = &sessions[fd];
658
659                 if (!session->sess)
660                 {
661                         CloseSession(session);
662                         return -1;
663                 }
664
665                 session->data_to_write = true;
666
667                 if (session->status == ISSL_HANDSHAKING)
668                 {
669                         if (!Handshake(user, session))
670                         {
671                                 // Couldn't resume handshake.
672                                 if (session->status == ISSL_NONE)
673                                         return -1;
674                                 return 0;
675                         }
676                 }
677
678                 if (session->status == ISSL_OPEN)
679                 {
680                         ERR_clear_error();
681                         int ret = SSL_write(session->sess, buffer.data(), buffer.size());
682
683 #ifdef INSPIRCD_OPENSSL_ENABLE_RENEGO_DETECTION
684                         if (!CheckRenego(user, session))
685                                 return -1;
686 #endif
687
688                         if (ret == (int)buffer.length())
689                         {
690                                 session->data_to_write = false;
691                                 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
692                                 return 1;
693                         }
694                         else if (ret > 0)
695                         {
696                                 buffer = buffer.substr(ret);
697                                 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
698                                 return 0;
699                         }
700                         else if (ret == 0)
701                         {
702                                 CloseSession(session);
703                                 return -1;
704                         }
705                         else if (ret < 0)
706                         {
707                                 int err = SSL_get_error(session->sess, ret);
708
709                                 if (err == SSL_ERROR_WANT_WRITE)
710                                 {
711                                         ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
712                                         return 0;
713                                 }
714                                 else if (err == SSL_ERROR_WANT_READ)
715                                 {
716                                         ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ);
717                                         return 0;
718                                 }
719                                 else
720                                 {
721                                         CloseSession(session);
722                                         return -1;
723                                 }
724                         }
725                 }
726                 return 0;
727         }
728
729         bool Handshake(StreamSocket* user, issl_session* session)
730         {
731                 int ret;
732
733                 ERR_clear_error();
734                 if (session->outbound)
735                         ret = SSL_connect(session->sess);
736                 else
737                         ret = SSL_accept(session->sess);
738
739                 if (ret < 0)
740                 {
741                         int err = SSL_get_error(session->sess, ret);
742
743                         if (err == SSL_ERROR_WANT_READ)
744                         {
745                                 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
746                                 session->status = ISSL_HANDSHAKING;
747                                 return true;
748                         }
749                         else if (err == SSL_ERROR_WANT_WRITE)
750                         {
751                                 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
752                                 session->status = ISSL_HANDSHAKING;
753                                 return true;
754                         }
755                         else
756                         {
757                                 CloseSession(session);
758                         }
759
760                         return false;
761                 }
762                 else if (ret > 0)
763                 {
764                         // Handshake complete.
765                         VerifyCertificate(session, user);
766
767                         session->status = ISSL_OPEN;
768
769                         ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
770
771                         return true;
772                 }
773                 else if (ret == 0)
774                 {
775                         CloseSession(session);
776                 }
777                 return false;
778         }
779
780         void CloseSession(issl_session* session)
781         {
782                 if (session->sess)
783                 {
784                         SSL_shutdown(session->sess);
785                         SSL_free(session->sess);
786                 }
787
788                 session->sess = NULL;
789                 session->status = ISSL_NONE;
790                 session->cert = NULL;
791         }
792
793         void VerifyCertificate(issl_session* session, StreamSocket* user)
794         {
795                 if (!session->sess || !user)
796                         return;
797
798                 X509* cert;
799                 ssl_cert* certinfo = new ssl_cert;
800                 session->cert = certinfo;
801                 unsigned int n;
802                 unsigned char md[EVP_MAX_MD_SIZE];
803                 const EVP_MD *digest = use_sha ? EVP_sha1() : EVP_md5();
804
805                 cert = SSL_get_peer_certificate((SSL*)session->sess);
806
807                 if (!cert)
808                 {
809                         certinfo->error = "Could not get peer certificate: "+std::string(get_error());
810                         return;
811                 }
812
813                 certinfo->invalid = (SSL_get_verify_result(session->sess) != X509_V_OK);
814
815                 if (!SelfSigned)
816                 {
817                         certinfo->unknownsigner = false;
818                         certinfo->trusted = true;
819                 }
820                 else
821                 {
822                         certinfo->unknownsigner = true;
823                         certinfo->trusted = false;
824                 }
825
826                 char buf[512];
827                 X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf));
828                 certinfo->dn = buf;
829                 // Make sure there are no chars in the string that we consider invalid
830                 if (certinfo->dn.find_first_of("\r\n") != std::string::npos)
831                         certinfo->dn.clear();
832
833                 X509_NAME_oneline(X509_get_issuer_name(cert), buf, sizeof(buf));
834                 certinfo->issuer = buf;
835                 if (certinfo->issuer.find_first_of("\r\n") != std::string::npos)
836                         certinfo->issuer.clear();
837
838                 if (!X509_digest(cert, digest, md, &n))
839                 {
840                         certinfo->error = "Out of memory generating fingerprint";
841                 }
842                 else
843                 {
844                         certinfo->fingerprint = irc::hex(md, n);
845                 }
846
847                 if ((ASN1_UTCTIME_cmp_time_t(X509_getm_notAfter(cert), ServerInstance->Time()) == -1) || (ASN1_UTCTIME_cmp_time_t(X509_getm_notBefore(cert), ServerInstance->Time()) == 0))
848                 {
849                         certinfo->error = "Not activated, or expired certificate";
850                 }
851
852                 X509_free(cert);
853         }
854 };
855
856 static int error_callback(const char *str, size_t len, void *u)
857 {
858         ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "SSL error: " + std::string(str, len - 1));
859
860         //
861         // XXX: Remove this line, it causes valgrind warnings...
862         //
863         // MD_update(&m, buf, j);
864         //
865         //
866         // ... ONLY JOKING! :-)
867         //
868
869         return 0;
870 }
871
872 MODULE_INIT(ModuleSSLOpenSSL)