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