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