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