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