]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ssl_openssl.cpp
openssl should now work too
[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 &hostandport, const std::vector<std::string> &portlist)
50 {
51         return std::find(portlist.begin(), portlist.end(), hostandport) != portlist.end();
52 }
53
54 char* get_error()
55 {
56         return ERR_error_string(ERR_get_error(), NULL);
57 }
58
59 static int error_callback(const char *str, size_t len, void *u);
60
61 /** Represents an SSL user's extra data
62  */
63 class issl_session : public classbase
64 {
65 public:
66         SSL* sess;
67         issl_status status;
68         issl_io_status rstat;
69         issl_io_status wstat;
70
71         unsigned int inbufoffset;
72         char* inbuf;                    // Buffer OpenSSL reads into.
73         std::string outbuf;     // Buffer for outgoing data that OpenSSL will not take.
74         int fd;
75         bool outbound;
76
77         issl_session()
78         {
79                 outbound = false;
80                 rstat = ISSL_READ;
81                 wstat = ISSL_WRITE;
82         }
83 };
84
85 static int OnVerify(int preverify_ok, X509_STORE_CTX *ctx)
86 {
87         /* XXX: This will allow self signed certificates.
88          * In the future if we want an option to not allow this,
89          * we can just return preverify_ok here, and openssl
90          * will boot off self-signed and invalid peer certs.
91          */
92         int ve = X509_STORE_CTX_get_error(ctx);
93
94         SelfSigned = (ve == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
95
96         return 1;
97 }
98
99 class ModuleSSLOpenSSL : public Module
100 {
101         std::vector<std::string> listenports;
102
103         int inbufsize;
104         issl_session sessions[MAX_DESCRIPTORS];
105
106         SSL_CTX* ctx;
107         SSL_CTX* clictx;
108
109         char* dummy;
110         char cipher[MAXBUF];
111
112         std::string keyfile;
113         std::string certfile;
114         std::string cafile;
115         // std::string crlfile;
116         std::string dhfile;
117         std::string sslports;
118
119         int clientactive;
120
121  public:
122
123         InspIRCd* PublicInstance;
124
125         ModuleSSLOpenSSL(InspIRCd* Me)
126         : Module(Me), PublicInstance(Me)
127         {
128                 ServerInstance->Modules->PublishInterface("BufferedSocketHook", this);
129
130                 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
131                 inbufsize = ServerInstance->Config->NetBufferSize;
132
133                 /* Global SSL library initialization*/
134                 SSL_library_init();
135                 SSL_load_error_strings();
136
137                 /* Build our SSL contexts:
138                  * NOTE: OpenSSL makes us have two contexts, one for servers and one for clients. ICK.
139                  */
140                 ctx = SSL_CTX_new( SSLv23_server_method() );
141                 clictx = SSL_CTX_new( SSLv23_client_method() );
142
143                 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
144                 SSL_CTX_set_verify(clictx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
145
146                 // Needs the flag as it ignores a plain /rehash
147                 OnRehash(NULL,"ssl");
148                 Implementation eventlist[] = { I_OnRawSocketConnect, I_OnRawSocketAccept, I_OnRawSocketClose, I_OnRawSocketRead, I_OnRawSocketWrite, I_OnCleanup, I_On005Numeric,
149                         I_OnBufferFlushed, I_OnRequest, I_OnSyncUserMetaData, I_OnDecodeMetaData, I_OnUnloadModule, I_OnRehash, I_OnWhois, I_OnPostConnect, I_OnHookUserIO };
150                 ServerInstance->Modules->Attach(eventlist, this, 16);
151         }
152
153         virtual void OnHookUserIO(User* user, const std::string &targetip)
154         {
155                 if (!user->io && isin(targetip + ":" + ConvToStr(user->GetPort()), listenports))
156                 {
157                         /* Hook the user with our module */
158                         user->io = this;
159                 }
160         }
161
162         virtual void OnRehash(User* user, const std::string &param)
163         {
164                 ConfigReader Conf(ServerInstance);
165
166                 listenports.clear();
167                 clientactive = 0;
168                 sslports.clear();
169
170                 for(int index = 0; index < Conf.Enumerate("bind"); index++)
171                 {
172                         // For each <bind> tag
173                         std::string x = Conf.ReadValue("bind", "type", index);
174                         if(((x.empty()) || (x == "clients")) && (Conf.ReadValue("bind", "ssl", index) == "openssl"))
175                         {
176                                 // Get the port we're meant to be listening on with SSL
177                                 std::string port = Conf.ReadValue("bind", "port", index);
178                                 std::string addr = Conf.ReadValue("bind", "address", index);
179
180                                 irc::portparser portrange(port, false);
181                                 long portno = -1;
182                                 while ((portno = portrange.GetToken()))
183                                 {
184                                         clientactive++;
185                                         try
186                                         {
187                                                 listenports.push_back(addr + ":" + ConvToStr(portno));
188
189                                                 for (size_t i = 0; i < ServerInstance->Config->ports.size(); i++)
190                                                         if ((ServerInstance->Config->ports[i]->GetPort() == portno) && (ServerInstance->Config->ports[i]->GetIP() == addr))
191                                                                 ServerInstance->Config->ports[i]->SetDescription("ssl");
192                                                 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_gnutls.so: Enabling SSL for port %d", portno);
193
194                                                 sslports.append((addr.empty() ? "*" : addr)).append(":").append(ConvToStr(portno)).append(";");
195                                         }
196                                         catch (ModuleException &e)
197                                         {
198                                                 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_gnutls.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 an other SSL or similar module loaded?", portno, e.GetReason());
199                                         }
200                                 }
201                         }
202                 }
203
204                 if (!sslports.empty())
205                         sslports.erase(sslports.end() - 1);
206
207                 if (param != "ssl")
208                 {
209                         return;
210                 }
211
212                 std::string confdir(ServerInstance->ConfigFileName);
213                 // +1 so we the path ends with a /
214                 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
215
216                 cafile   = Conf.ReadValue("openssl", "cafile", 0);
217                 certfile = Conf.ReadValue("openssl", "certfile", 0);
218                 keyfile  = Conf.ReadValue("openssl", "keyfile", 0);
219                 dhfile   = Conf.ReadValue("openssl", "dhfile", 0);
220
221                 // Set all the default values needed.
222                 if (cafile.empty())
223                         cafile = "ca.pem";
224
225                 if (certfile.empty())
226                         certfile = "cert.pem";
227
228                 if (keyfile.empty())
229                         keyfile = "key.pem";
230
231                 if (dhfile.empty())
232                         dhfile = "dhparams.pem";
233
234                 // Prepend relative paths with the path to the config directory.
235                 if (cafile[0] != '/')
236                         cafile = confdir + cafile;
237
238                 if (certfile[0] != '/')
239                         certfile = confdir + certfile;
240
241                 if (keyfile[0] != '/')
242                         keyfile = confdir + keyfile;
243
244                 if (dhfile[0] != '/')
245                         dhfile = confdir + dhfile;
246
247                 /* Load our keys and certificates
248                  * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck.
249                  */
250                 if ((!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str())) || (!SSL_CTX_use_certificate_chain_file(clictx, certfile.c_str())))
251                 {
252                         ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s. %s", certfile.c_str(), strerror(errno));
253                         ERR_print_errors_cb(error_callback, this);
254                 }
255
256                 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)))
257                 {
258                         ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read key file %s. %s", keyfile.c_str(), strerror(errno));
259                         ERR_print_errors_cb(error_callback, this);
260                 }
261
262                 /* Load the CAs we trust*/
263                 if (((!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))) || (!SSL_CTX_load_verify_locations(clictx, cafile.c_str(), 0)))
264                 {
265                         ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read CA list from %s. %s", cafile.c_str(), strerror(errno));
266                         ERR_print_errors_cb(error_callback, this);
267                 }
268
269                 FILE* dhpfile = fopen(dhfile.c_str(), "r");
270                 DH* ret;
271
272                 if (dhpfile == NULL)
273                 {
274                         ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
275                         throw ModuleException("Couldn't open DH file " + dhfile + ": " + strerror(errno));
276                 }
277                 else
278                 {
279                         ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
280                         if ((SSL_CTX_set_tmp_dh(ctx, ret) < 0) || (SSL_CTX_set_tmp_dh(clictx, ret) < 0))
281                         {
282                                 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters %s. SSL errors follow:", dhfile.c_str());
283                                 ERR_print_errors_cb(error_callback, this);
284                         }
285                 }
286
287                 fclose(dhpfile);
288         }
289
290         virtual void On005Numeric(std::string &output)
291         {
292                 output.append(" SSL=" + sslports);
293         }
294
295         virtual ~ModuleSSLOpenSSL()
296         {
297                 SSL_CTX_free(ctx);
298                 SSL_CTX_free(clictx);
299         }
300
301         virtual void OnCleanup(int target_type, void* item)
302         {
303                 if (target_type == TYPE_USER)
304                 {
305                         User* user = (User*)item;
306
307                         if (user->GetExt("ssl", dummy) && IS_LOCAL(user) && user->io == this)
308                         {
309                                 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
310                                 // Potentially there could be multiple SSL modules loaded at once on different ports.
311                                 User::QuitUser(ServerInstance, user, "SSL module unloading");
312                         }
313                         if (user->GetExt("ssl_cert", dummy))
314                         {
315                                 ssl_cert* tofree;
316                                 user->GetExt("ssl_cert", tofree);
317                                 delete tofree;
318                                 user->Shrink("ssl_cert");
319                         }
320
321                         user->io = NULL;
322                 }
323         }
324
325         virtual void OnUnloadModule(Module* mod, const std::string &name)
326         {
327                 if (mod == this)
328                 {
329                         for(unsigned int i = 0; i < listenports.size(); i++)
330                         {
331                                 for (size_t j = 0; j < ServerInstance->Config->ports.size(); j++)
332                                         if (listenports[i] == (ServerInstance->Config->ports[j]->GetIP()+":"+ConvToStr(ServerInstance->Config->ports[j]->GetPort())))
333                                                 ServerInstance->Config->ports[j]->SetDescription("plaintext");
334                         }
335                 }
336         }
337
338         virtual Version GetVersion()
339         {
340                 return Version(1, 2, 0, 0, VF_VENDOR, API_VERSION);
341         }
342
343
344         virtual const 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                         const char* ret = "OK";
354                         try
355                         {
356                                 ret = ServerInstance->Config->AddIOHook((Module*)this, (BufferedSocket*)ISR->Sock) ? "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) ? "OK" : NULL;
368                 }
369                 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
370                 {
371                         if (ISR->Sock->GetFd() < 0)
372                                 return "OK";
373
374                         issl_session* session = &sessions[ISR->Sock->GetFd()];
375                         return (session->status == ISSL_HANDSHAKING) ? NULL : "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->Logs->Log("m_ssl_openssl",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->Logs->Log("m_ssl_openssl",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) && dest->io == this)))
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->Logs->Log("m_ssl_openssl",DEFAULT, "SSL error: " + std::string(str, len - 1));
888         return 0;
889 }
890
891 MODULE_INIT(ModuleSSLOpenSSL)