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