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