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