]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ssl_openssl.cpp
Fix IO hooking modules to use the new (not old) hooking call
[user/henk/code/inspircd.git] / src / modules / extra / m_ssl_openssl.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2008 InspIRCd Development Team
6  * See: http://www.inspircd.org/wiki/index.php/Credits
7  *
8  * This program is free but copyrighted software; see
9  *            the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 #include "inspircd.h"
15
16 #include <openssl/ssl.h>
17 #include <openssl/err.h>
18
19 #include "configreader.h"
20 #include "users.h"
21 #include "channels.h"
22 #include "modules.h"
23
24 #include "socket.h"
25 #include "hashcomp.h"
26
27 #include "transport.h"
28
29 #ifdef WINDOWS
30 #pragma comment(lib, "libeay32MTd")
31 #pragma comment(lib, "ssleay32MTd")
32 #undef MAX_DESCRIPTORS
33 #define MAX_DESCRIPTORS 10000
34 #endif
35
36 /* $ModDesc: Provides SSL support for clients */
37
38 /* $LinkerFlags: if("USE_FREEBSD_BASE_SSL") -lssl -lcrypto */
39 /* $CompileFlags: if(!"USE_FREEBSD_BASE_SSL") pkgconfversion("openssl","0.9.7") pkgconfincludes("openssl","/openssl/ssl.h","") */
40 /* $LinkerFlags: if(!"USE_FREEBSD_BASE_SSL") rpath("pkg-config --libs openssl") pkgconflibs("openssl","/libssl.so","-lssl -lcrypto -ldl") */
41
42 /* $ModDep: transport.h */
43 /* $NoPedantic */
44 /* $CopyInstall: conf/key.pem $(CONPATH) */
45 /* $CopyInstall: conf/cert.pem $(CONPATH) */
46
47
48 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING, ISSL_OPEN };
49 enum issl_io_status { ISSL_WRITE, ISSL_READ };
50
51 static bool SelfSigned = false;
52
53 bool isin(const std::string &host, int port, const std::vector<std::string> &portlist)
54 {
55         if (std::find(portlist.begin(), portlist.end(), "*:" + ConvToStr(port)) != portlist.end())
56                 return true;
57
58         if (std::find(portlist.begin(), portlist.end(), ":" + ConvToStr(port)) != portlist.end())
59                 return true;
60
61         return std::find(portlist.begin(), portlist.end(), host + ":" + ConvToStr(port)) != portlist.end();
62 }
63
64 char* get_error()
65 {
66         return ERR_error_string(ERR_get_error(), NULL);
67 }
68
69 static int error_callback(const char *str, size_t len, void *u);
70
71 /** Represents an SSL user's extra data
72  */
73 class issl_session : public classbase
74 {
75 public:
76         SSL* sess;
77         issl_status status;
78         issl_io_status rstat;
79         issl_io_status wstat;
80
81         unsigned int inbufoffset;
82         char* inbuf;                    // Buffer OpenSSL reads into.
83         std::string outbuf;     // Buffer for outgoing data that OpenSSL will not take.
84         int fd;
85         bool outbound;
86
87         issl_session()
88         {
89                 outbound = false;
90                 rstat = ISSL_READ;
91                 wstat = ISSL_WRITE;
92         }
93 };
94
95 static int OnVerify(int preverify_ok, X509_STORE_CTX *ctx)
96 {
97         /* XXX: This will allow self signed certificates.
98          * In the future if we want an option to not allow this,
99          * we can just return preverify_ok here, and openssl
100          * will boot off self-signed and invalid peer certs.
101          */
102         int ve = X509_STORE_CTX_get_error(ctx);
103
104         SelfSigned = (ve == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
105
106         return 1;
107 }
108
109 class ModuleSSLOpenSSL : public Module
110 {
111         std::vector<std::string> listenports;
112
113         int inbufsize;
114         issl_session* sessions;
115
116         SSL_CTX* ctx;
117         SSL_CTX* clictx;
118
119         char* dummy;
120         char cipher[MAXBUF];
121
122         std::string keyfile;
123         std::string certfile;
124         std::string cafile;
125         // std::string crlfile;
126         std::string dhfile;
127         std::string sslports;
128
129         int clientactive;
130
131  public:
132
133         InspIRCd* PublicInstance;
134
135         ModuleSSLOpenSSL(InspIRCd* Me)
136         : Module(Me), PublicInstance(Me)
137         {
138                 ServerInstance->Modules->PublishInterface("BufferedSocketHook", this);
139
140                 sessions = new issl_session[ServerInstance->SE->GetMaxFds()];
141
142                 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
143                 inbufsize = ServerInstance->Config->NetBufferSize;
144
145                 /* Global SSL library initialization*/
146                 SSL_library_init();
147                 SSL_load_error_strings();
148
149                 /* Build our SSL contexts:
150                  * NOTE: OpenSSL makes us have two contexts, one for servers and one for clients. ICK.
151                  */
152                 ctx = SSL_CTX_new( SSLv23_server_method() );
153                 clictx = SSL_CTX_new( SSLv23_client_method() );
154
155                 SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
156                 SSL_CTX_set_mode(clictx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
157
158                 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
159                 SSL_CTX_set_verify(clictx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
160
161                 // Needs the flag as it ignores a plain /rehash
162                 OnRehash(NULL,"ssl");
163                 Implementation eventlist[] = { I_OnRawSocketConnect, I_OnRawSocketAccept, I_OnRawSocketClose, I_OnRawSocketRead, I_OnRawSocketWrite, I_OnCleanup, I_On005Numeric,
164                         I_OnBufferFlushed, I_OnRequest, I_OnSyncUserMetaData, I_OnDecodeMetaData, I_OnUnloadModule, I_OnRehash, I_OnWhois, I_OnPostConnect, I_OnHookUserIO };
165                 ServerInstance->Modules->Attach(eventlist, this, 16);
166         }
167
168         virtual void OnHookUserIO(User* user, const std::string &targetip)
169         {
170                 if (!user->io && isin(targetip,user->GetPort(), listenports))
171                 {
172                         /* Hook the user with our module */
173                         user->io = this;
174                 }
175         }
176
177         virtual void OnRehash(User* user, const std::string &param)
178         {
179                 ConfigReader Conf(ServerInstance);
180
181                 listenports.clear();
182                 clientactive = 0;
183                 sslports.clear();
184
185                 for(int index = 0; index < Conf.Enumerate("bind"); index++)
186                 {
187                         // For each <bind> tag
188                         std::string x = Conf.ReadValue("bind", "type", index);
189                         if(((x.empty()) || (x == "clients")) && (Conf.ReadValue("bind", "ssl", index) == "openssl"))
190                         {
191                                 // Get the port we're meant to be listening on with SSL
192                                 std::string port = Conf.ReadValue("bind", "port", index);
193                                 std::string addr = Conf.ReadValue("bind", "address", index);
194
195                                 irc::portparser portrange(port, false);
196                                 long portno = -1;
197                                 while ((portno = portrange.GetToken()))
198                                 {
199                                         clientactive++;
200                                         try
201                                         {
202                                                 listenports.push_back(addr + ":" + ConvToStr(portno));
203
204                                                 for (size_t i = 0; i < ServerInstance->Config->ports.size(); i++)
205                                                         if ((ServerInstance->Config->ports[i]->GetPort() == portno) && (ServerInstance->Config->ports[i]->GetIP() == addr))
206                                                                 ServerInstance->Config->ports[i]->SetDescription("ssl");
207                                                 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_gnutls.so: Enabling SSL for port %ld", portno);
208
209                                                 sslports.append((addr.empty() ? "*" : addr)).append(":").append(ConvToStr(portno)).append(";");
210                                         }
211                                         catch (ModuleException &e)
212                                         {
213                                                 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_gnutls.so: FAILED to enable SSL on port %ld: %s. Maybe it's already hooked by the same port on a different IP, or you have an other SSL or similar module loaded?", portno, e.GetReason());
214                                         }
215                                 }
216                         }
217                 }
218
219                 if (!sslports.empty())
220                         sslports.erase(sslports.end() - 1);
221
222                 if (param != "ssl")
223                 {
224                         return;
225                 }
226
227                 std::string confdir(ServerInstance->ConfigFileName);
228                 // +1 so we the path ends with a /
229                 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
230
231                 cafile   = Conf.ReadValue("openssl", "cafile", 0);
232                 certfile = Conf.ReadValue("openssl", "certfile", 0);
233                 keyfile  = Conf.ReadValue("openssl", "keyfile", 0);
234                 dhfile   = Conf.ReadValue("openssl", "dhfile", 0);
235
236                 // Set all the default values needed.
237                 if (cafile.empty())
238                         cafile = "ca.pem";
239
240                 if (certfile.empty())
241                         certfile = "cert.pem";
242
243                 if (keyfile.empty())
244                         keyfile = "key.pem";
245
246                 if (dhfile.empty())
247                         dhfile = "dhparams.pem";
248
249                 // Prepend relative paths with the path to the config directory.
250                 if ((cafile[0] != '/') && (!ServerInstance->Config->StartsWithWindowsDriveLetter(cafile)))
251                         cafile = confdir + cafile;
252
253                 if ((certfile[0] != '/') && (!ServerInstance->Config->StartsWithWindowsDriveLetter(certfile)))
254                         certfile = confdir + certfile;
255
256                 if ((keyfile[0] != '/') && (!ServerInstance->Config->StartsWithWindowsDriveLetter(keyfile)))
257                         keyfile = confdir + keyfile;
258
259                 if ((dhfile[0] != '/') && (!ServerInstance->Config->StartsWithWindowsDriveLetter(dhfile)))
260                         dhfile = confdir + dhfile;
261
262                 /* Load our keys and certificates
263                  * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck.
264                  */
265                 if ((!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str())) || (!SSL_CTX_use_certificate_chain_file(clictx, certfile.c_str())))
266                 {
267                         ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s. %s", certfile.c_str(), strerror(errno));
268                         ERR_print_errors_cb(error_callback, this);
269                 }
270
271                 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)))
272                 {
273                         ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read key file %s. %s", keyfile.c_str(), strerror(errno));
274                         ERR_print_errors_cb(error_callback, this);
275                 }
276
277                 /* Load the CAs we trust*/
278                 if (((!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))) || (!SSL_CTX_load_verify_locations(clictx, cafile.c_str(), 0)))
279                 {
280                         ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read CA list from %s. %s", cafile.c_str(), strerror(errno));
281                         ERR_print_errors_cb(error_callback, this);
282                 }
283
284                 FILE* dhpfile = fopen(dhfile.c_str(), "r");
285                 DH* ret;
286
287                 if (dhpfile == NULL)
288                 {
289                         ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
290                         throw ModuleException("Couldn't open DH file " + dhfile + ": " + strerror(errno));
291                 }
292                 else
293                 {
294                         ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
295                         if ((SSL_CTX_set_tmp_dh(ctx, ret) < 0) || (SSL_CTX_set_tmp_dh(clictx, ret) < 0))
296                         {
297                                 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters %s. SSL errors follow:", dhfile.c_str());
298                                 ERR_print_errors_cb(error_callback, this);
299                         }
300                 }
301
302                 fclose(dhpfile);
303         }
304
305         virtual void On005Numeric(std::string &output)
306         {
307                 output.append(" SSL=" + sslports);
308         }
309
310         virtual ~ModuleSSLOpenSSL()
311         {
312                 SSL_CTX_free(ctx);
313                 SSL_CTX_free(clictx);
314                 ServerInstance->Modules->UnpublishInterface("BufferedSocketHook", this);
315                 delete[] sessions;
316         }
317
318         virtual void OnCleanup(int target_type, void* item)
319         {
320                 if (target_type == TYPE_USER)
321                 {
322                         User* user = (User*)item;
323
324                         if (user->io == this)
325                         {
326                                 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
327                                 // Potentially there could be multiple SSL modules loaded at once on different ports.
328                                 ServerInstance->Users->QuitUser(user, "SSL module unloading");
329                                 user->io = NULL;
330                         }
331                         if (user->GetExt("ssl_cert", dummy))
332                         {
333                                 ssl_cert* tofree;
334                                 user->GetExt("ssl_cert", tofree);
335                                 delete tofree;
336                                 user->Shrink("ssl_cert");
337                         }
338                 }
339         }
340
341         virtual void OnUnloadModule(Module* mod, const std::string &name)
342         {
343                 if (mod == this)
344                 {
345                         for(unsigned int i = 0; i < listenports.size(); i++)
346                         {
347                                 for (size_t j = 0; j < ServerInstance->Config->ports.size(); j++)
348                                         if (listenports[i] == (ServerInstance->Config->ports[j]->GetIP()+":"+ConvToStr(ServerInstance->Config->ports[j]->GetPort())))
349                                                 ServerInstance->Config->ports[j]->SetDescription("plaintext");
350                         }
351                 }
352         }
353
354         virtual Version GetVersion()
355         {
356                 return Version("$Id$", VF_VENDOR, API_VERSION);
357         }
358
359
360         virtual const char* OnRequest(Request* request)
361         {
362                 ISHRequest* ISR = (ISHRequest*)request;
363                 if (strcmp("IS_NAME", request->GetId()) == 0)
364                 {
365                         return "openssl";
366                 }
367                 else if (strcmp("IS_HOOK", request->GetId()) == 0)
368                 {
369                         const char* ret = "OK";
370                         try
371                         {
372                                 ret = ISR->Sock->AddIOHook((Module*)this) ? "OK" : NULL;
373                         }
374                         catch (ModuleException &e)
375                         {
376                                 return NULL;
377                         }
378
379                         return ret;
380                 }
381                 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
382                 {
383                         return ISR->Sock->DelIOHook() ? "OK" : NULL;
384                 }
385                 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
386                 {
387                         if (ISR->Sock->GetFd() < 0)
388                                 return "OK";
389
390                         issl_session* session = &sessions[ISR->Sock->GetFd()];
391                         return (session->status == ISSL_HANDSHAKING) ? NULL : "OK";
392                 }
393                 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
394                 {
395                         issl_session* session = &sessions[ISR->Sock->GetFd()];
396                         if (session->sess)
397                         {
398                                 VerifyCertificate(session, (BufferedSocket*)ISR->Sock);
399                                 return "OK";
400                         }
401                 }
402                 return NULL;
403         }
404
405
406         virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
407         {
408                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
409                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
410                         return;
411
412                 issl_session* session = &sessions[fd];
413
414                 session->fd = fd;
415                 session->inbuf = new char[inbufsize];
416                 session->inbufoffset = 0;
417                 session->sess = SSL_new(ctx);
418                 session->status = ISSL_NONE;
419                 session->outbound = false;
420
421                 if (session->sess == NULL)
422                         return;
423
424                 if (SSL_set_fd(session->sess, fd) == 0)
425                 {
426                         ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
427                         return;
428                 }
429
430                 Handshake(session);
431         }
432
433         virtual void OnRawSocketConnect(int fd)
434         {
435                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
436                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() -1))
437                         return;
438
439                 issl_session* session = &sessions[fd];
440
441                 session->fd = fd;
442                 session->inbuf = new char[inbufsize];
443                 session->inbufoffset = 0;
444                 session->sess = SSL_new(clictx);
445                 session->status = ISSL_NONE;
446                 session->outbound = true;
447
448                 if (session->sess == NULL)
449                         return;
450
451                 if (SSL_set_fd(session->sess, fd) == 0)
452                 {
453                         ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
454                         return;
455                 }
456
457                 Handshake(session);
458         }
459
460         virtual void OnRawSocketClose(int fd)
461         {
462                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
463                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
464                         return;
465
466                 CloseSession(&sessions[fd]);
467
468                 EventHandler* user = ServerInstance->SE->GetRef(fd);
469
470                 if ((user) && (user->GetExt("ssl_cert", dummy)))
471                 {
472                         ssl_cert* tofree;
473                         user->GetExt("ssl_cert", tofree);
474                         delete tofree;
475                         user->Shrink("ssl_cert");
476                 }
477         }
478
479         virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
480         {
481                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
482                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
483                         return 0;
484
485                 issl_session* session = &sessions[fd];
486
487                 if (!session->sess)
488                 {
489                         readresult = 0;
490                         CloseSession(session);
491                         return 1;
492                 }
493
494                 if (session->status == ISSL_HANDSHAKING)
495                 {
496                         if (session->rstat == ISSL_READ || session->wstat == ISSL_READ)
497                         {
498                                 // The handshake isn't finished and it wants to read, try to finish it.
499                                 if (!Handshake(session))
500                                 {
501                                         // Couldn't resume handshake.
502                                         return -1;
503                                 }
504                         }
505                         else
506                         {
507                                 errno = EAGAIN;
508                                 return -1;
509                         }
510                 }
511
512                 // If we resumed the handshake then session->status will be ISSL_OPEN
513
514                 if (session->status == ISSL_OPEN)
515                 {
516                         if (session->wstat == ISSL_READ)
517                         {
518                                 if(DoWrite(session) == 0)
519                                         return 0;
520                         }
521
522                         if (session->rstat == ISSL_READ)
523                         {
524                                 int ret = DoRead(session);
525
526                                 if (ret > 0)
527                                 {
528                                         if (count <= session->inbufoffset)
529                                         {
530                                                 memcpy(buffer, session->inbuf, count);
531                                                 // Move the stuff left in inbuf to the beginning of it
532                                                 memmove(session->inbuf, session->inbuf + count, (session->inbufoffset - count));
533                                                 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
534                                                 session->inbufoffset -= count;
535                                                 // Insp uses readresult as the count of how much data there is in buffer, so:
536                                                 readresult = count;
537                                         }
538                                         else
539                                         {
540                                                 // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
541                                                 memcpy(buffer, session->inbuf, session->inbufoffset);
542
543                                                 readresult = session->inbufoffset;
544                                                 // Zero the offset, as there's nothing there..
545                                                 session->inbufoffset = 0;
546                                         }
547                                         return 1;
548                                 }
549                                 return ret;
550                         }
551                 }
552
553                 return -1;
554         }
555
556         virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
557         {
558                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
559                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
560                         return 0;
561
562                 issl_session* session = &sessions[fd];
563
564                 if (!session->sess)
565                 {
566                         CloseSession(session);
567                         return -1;
568                 }
569
570                 session->outbuf.append(buffer, count);
571                 MakePollWrite(session);
572
573                 if (session->status == ISSL_HANDSHAKING)
574                 {
575                         // The handshake isn't finished, try to finish it.
576                         if (session->rstat == ISSL_WRITE || session->wstat == ISSL_WRITE)
577                         {
578                                 Handshake(session);
579                         }
580                 }
581
582                 if (session->status == ISSL_OPEN)
583                 {
584                         if (session->rstat == ISSL_WRITE)
585                         {
586                                 DoRead(session);
587                         }
588
589                         if (session->wstat == ISSL_WRITE)
590                         {
591                                 return DoWrite(session);
592                         }
593                 }
594
595                 return 1;
596         }
597
598         int DoWrite(issl_session* session)
599         {
600                 if (!session->outbuf.size())
601                         return -1;
602
603                 int ret = SSL_write(session->sess, session->outbuf.data(), session->outbuf.size());
604
605                 if (ret == 0)
606                 {
607                         CloseSession(session);
608                         return 0;
609                 }
610                 else if (ret < 0)
611                 {
612                         int err = SSL_get_error(session->sess, ret);
613
614                         if (err == SSL_ERROR_WANT_WRITE)
615                         {
616                                 session->wstat = ISSL_WRITE;
617                                 return -1;
618                         }
619                         else if (err == SSL_ERROR_WANT_READ)
620                         {
621                                 session->wstat = ISSL_READ;
622                                 return -1;
623                         }
624                         else
625                         {
626                                 CloseSession(session);
627                                 return 0;
628                         }
629                 }
630                 else
631                 {
632                         session->outbuf = session->outbuf.substr(ret);
633                         return ret;
634                 }
635         }
636
637         int DoRead(issl_session* session)
638         {
639                 // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
640                 // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
641
642                 int ret = SSL_read(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
643
644                 if (ret == 0)
645                 {
646                         // Client closed connection.
647                         CloseSession(session);
648                         return 0;
649                 }
650                 else if (ret < 0)
651                 {
652                         int err = SSL_get_error(session->sess, ret);
653
654                         if (err == SSL_ERROR_WANT_READ)
655                         {
656                                 session->rstat = ISSL_READ;
657                                 return -1;
658                         }
659                         else if (err == SSL_ERROR_WANT_WRITE)
660                         {
661                                 session->rstat = ISSL_WRITE;
662                                 MakePollWrite(session);
663                                 return -1;
664                         }
665                         else
666                         {
667                                 CloseSession(session);
668                                 return 0;
669                         }
670                 }
671                 else
672                 {
673                         // Read successfully 'ret' bytes into inbuf + inbufoffset
674                         // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
675                         // 'buffer' is 'count' long
676
677                         session->inbufoffset += ret;
678
679                         return ret;
680                 }
681         }
682
683         // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
684         virtual void OnWhois(User* source, User* dest)
685         {
686                 if (!clientactive)
687                         return;
688
689                 // Bugfix, only send this numeric for *our* SSL users
690                 if (dest->GetExt("ssl", dummy) || ((IS_LOCAL(dest) && dest->io == this)))
691                 {
692                         ServerInstance->SendWhoisLine(source, dest, 320, "%s %s :is using a secure connection", source->nick.c_str(), dest->nick.c_str());
693                 }
694         }
695
696         virtual void OnSyncUserMetaData(User* user, Module* proto, void* opaque, const std::string &extname, bool displayable)
697         {
698                 // check if the linking module wants to know about OUR metadata
699                 if (extname == "ssl")
700                 {
701                         // check if this user has an swhois field to send
702                         if(user->GetExt(extname, dummy))
703                         {
704                                 // call this function in the linking module, let it format the data how it
705                                 // sees fit, and send it on its way. We dont need or want to know how.
706                                 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, displayable ? "Enabled" : "ON");
707                         }
708                 }
709         }
710
711         virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
712         {
713                 // check if its our metadata key, and its associated with a user
714                 if ((target_type == TYPE_USER) && (extname == "ssl"))
715                 {
716                         User* dest = (User*)target;
717                         // if they dont already have an ssl flag, accept the remote server's
718                         if (!dest->GetExt(extname, dummy))
719                         {
720                                 dest->Extend(extname, "ON");
721                         }
722                 }
723         }
724
725         bool Handshake(issl_session* session)
726         {
727                 int ret;
728
729                 if (session->outbound)
730                         ret = SSL_connect(session->sess);
731                 else
732                         ret = SSL_accept(session->sess);
733
734                 if (ret < 0)
735                 {
736                         int err = SSL_get_error(session->sess, ret);
737
738                         if (err == SSL_ERROR_WANT_READ)
739                         {
740                                 session->rstat = ISSL_READ;
741                                 session->status = ISSL_HANDSHAKING;
742                                 return true;
743                         }
744                         else if (err == SSL_ERROR_WANT_WRITE)
745                         {
746                                 session->wstat = ISSL_WRITE;
747                                 session->status = ISSL_HANDSHAKING;
748                                 MakePollWrite(session);
749                                 return true;
750                         }
751                         else
752                         {
753                                 CloseSession(session);
754                         }
755
756                         return false;
757                 }
758                 else if (ret > 0)
759                 {
760                         // Handshake complete.
761                         // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
762                         User* u = ServerInstance->FindDescriptor(session->fd);
763                         if (u)
764                         {
765                                 if (!u->GetExt("ssl", dummy))
766                                         u->Extend("ssl", "ON");
767                         }
768
769                         session->status = ISSL_OPEN;
770
771                         MakePollWrite(session);
772
773                         return true;
774                 }
775                 else if (ret == 0)
776                 {
777                         CloseSession(session);
778                         return true;
779                 }
780
781                 return true;
782         }
783
784         virtual void OnPostConnect(User* user)
785         {
786                 // This occurs AFTER OnUserConnect so we can be sure the
787                 // protocol module has propagated the NICK message.
788                 if ((user->GetExt("ssl", dummy)) && (IS_LOCAL(user)))
789                 {
790                         // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW.
791                         ServerInstance->PI->SendMetaData(user, TYPE_USER, "SSL", "on");
792
793                         VerifyCertificate(&sessions[user->GetFd()], user);
794                         if (sessions[user->GetFd()].sess)
795                                 user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\"", user->nick.c_str(), SSL_get_cipher(sessions[user->GetFd()].sess));
796                 }
797         }
798
799         void MakePollWrite(issl_session* session)
800         {
801                 //OnRawSocketWrite(session->fd, NULL, 0);
802                 EventHandler* eh = ServerInstance->FindDescriptor(session->fd);
803                 if (eh)
804                 {
805                         ServerInstance->SE->WantWrite(eh);
806                 }
807         }
808
809         virtual void OnBufferFlushed(User* user)
810         {
811                 if (user->GetExt("ssl"))
812                 {
813                         issl_session* session = &sessions[user->GetFd()];
814                         if (session && session->outbuf.size())
815                                 OnRawSocketWrite(user->GetFd(), NULL, 0);
816                 }
817         }
818
819         void CloseSession(issl_session* session)
820         {
821                 if (session->sess)
822                 {
823                         SSL_shutdown(session->sess);
824                         SSL_free(session->sess);
825                 }
826
827                 if (session->inbuf)
828                 {
829                         delete[] session->inbuf;
830                 }
831
832                 session->outbuf.clear();
833                 session->inbuf = NULL;
834                 session->sess = NULL;
835                 session->status = ISSL_NONE;
836         }
837
838         void VerifyCertificate(issl_session* session, Extensible* user)
839         {
840                 if (!session->sess || !user)
841                         return;
842
843                 X509* cert;
844                 ssl_cert* certinfo = new ssl_cert;
845                 unsigned int n;
846                 unsigned char md[EVP_MAX_MD_SIZE];
847                 const EVP_MD *digest = EVP_md5();
848
849                 user->Extend("ssl_cert",certinfo);
850
851                 cert = SSL_get_peer_certificate((SSL*)session->sess);
852
853                 if (!cert)
854                 {
855                         certinfo->data.insert(std::make_pair("error","Could not get peer certificate: "+std::string(get_error())));
856                         return;
857                 }
858
859                 certinfo->data.insert(std::make_pair("invalid", SSL_get_verify_result(session->sess) != X509_V_OK ? ConvToStr(1) : ConvToStr(0)));
860
861                 if (SelfSigned)
862                 {
863                         certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(0)));
864                         certinfo->data.insert(std::make_pair("trusted",ConvToStr(1)));
865                 }
866                 else
867                 {
868                         certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(1)));
869                         certinfo->data.insert(std::make_pair("trusted",ConvToStr(0)));
870                 }
871
872                 certinfo->data.insert(std::make_pair("dn",std::string(X509_NAME_oneline(X509_get_subject_name(cert),0,0))));
873                 certinfo->data.insert(std::make_pair("issuer",std::string(X509_NAME_oneline(X509_get_issuer_name(cert),0,0))));
874
875                 if (!X509_digest(cert, digest, md, &n))
876                 {
877                         certinfo->data.insert(std::make_pair("error","Out of memory generating fingerprint"));
878                 }
879                 else
880                 {
881                         certinfo->data.insert(std::make_pair("fingerprint",irc::hex(md, n)));
882                 }
883
884                 if ((ASN1_UTCTIME_cmp_time_t(X509_get_notAfter(cert), time(NULL)) == -1) || (ASN1_UTCTIME_cmp_time_t(X509_get_notBefore(cert), time(NULL)) == 0))
885                 {
886                         certinfo->data.insert(std::make_pair("error","Not activated, or expired certificate"));
887                 }
888
889                 X509_free(cert);
890         }
891
892         void Prioritize()
893         {
894                 Module* server = ServerInstance->Modules->Find("m_spanningtree.so");
895                 ServerInstance->Modules->SetPriority(this, I_OnPostConnect, PRIO_AFTER, &server);
896         }
897
898 };
899
900 static int error_callback(const char *str, size_t len, void *u)
901 {
902         ModuleSSLOpenSSL* mssl = (ModuleSSLOpenSSL*)u;
903         mssl->PublicInstance->Logs->Log("m_ssl_openssl",DEFAULT, "SSL error: " + std::string(str, len - 1));
904
905         //
906         // XXX: Remove this line, it causes valgrind warnings...
907         //
908         // MD_update(&m, buf, j);
909         //
910         //
911         // ... ONLY JOKING! :-)
912         //
913
914         return 0;
915 }
916
917 MODULE_INIT(ModuleSSLOpenSSL)