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