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