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